#include "config.h"
/* $Id: getarg.c,v 1.13 1994/11/08 13:30:50 a904209 Exp a904209 $
 */
#define __STANDARDC__
#include <stdarg.h>

#include <stdio.h>
#include <ctype.h>
#include "useconfig.h"
#include "proto.h"
#include "getargs.h"

/*
   Usage is like :

   argc = getargs("Module",argc,argv,
   "r", "%d", &rate,               "Integer",
   "u", "",   &ufile_name,         "String",
   "g", "%d", &gain,               "Double",
   "a", NULL, &use_audio,          "Bool -a toggles, +a sets",
   "s", ""  , &speaker,            "Booelan -s clears, +s sets",
   NULL);

 */

int getargs (const char *module, int argc, const char *argv[], ...)
{
	va_list ap;
	int i = 0;

	while (i < argc)
	{
		const char *s = argv[i];
		int flag = *s++;
		if (*s && (flag == '-' || flag == '+'))
		{
			int off = 1;
			while (*s)
			{
				const char *a;
				int count = 0;
				va_start(ap, argv);
				while ((a = va_arg(ap, const char *)) != NULL) {
					int l = (int)strlen(a);
					const char *fmt = va_arg(ap, const char *);
					void *var = va_arg(ap, void *);
					const char *desc = va_arg(ap, const char *);
					(void)desc;

					if (l > 1)
					{
						if (!count && !strcmp(s, a))
						{
							if (fmt)
							{
								if (i + off < argc)
								{
									const char *x = argv[i + off++];
									if (strchr(fmt, '%'))
									{
										if (sscanf(x, fmt, var) != 1) {
										//	fprintf(stderr, "%s : %s invalid after -%s\n", argv[0], x, a);
										}
									}
									else
										*((char **) var) = (char *) x; /* FIXME: UNCONST! */
								}
								else {
								//	fprintf(stderr, "%s : no argument after -%s\n", argv[0], a);
								}
							}
							else
							{
								if (flag == '+')
									*((int *) var) = !0;
								else
									*((int *) var) = !*((int *) var);
							}
							/* skip to end of string */
							count++;
							s += l;
							break; /* out of va_arg loop */
						}
					}
					else
					{
						if (*s == *a)
						{
							if (fmt)
							{
								if (i + off < argc)
								{
									const char *x = argv[i + off++];
									if (strchr(fmt, '%'))
									{
										if (sscanf(x, fmt, var) != 1) {
										//	fprintf(stderr, "%s : %s invalid after -%s\n", argv[0], x, a);
										}
									}
									else
										*((char **) var) = (char *) x; /* FIXME: UNCONST! */
								}
								else {
								//	fprintf(stderr, "%s : no argument after -%s\n", argv[0], a);
								}
							}
							else
							{
								if (fmt || flag == '+')
									*((int *) var) = (flag == '+');
								else
									*((int *) var) = !*((int *) var);
							}
							count++;
							s++;
							break; /* out of va_arg loop */
						}
					}
				}
				va_end(ap);
				if (!count)
				{
					off = 0;
					break;        /* Out of s loop */
				}
			}
			if (off != 0) {
				int j;
				argc -= off;
				for (j = i; j <= argc; j++) {
					argv[j] = argv[j + off];
				}
			} else {
				i++;
			}
		} else {
			i++;
		}
	}

	return argc;
}
