/* clparse.c - Command Line Parse. */

#include <stdio.h>
#include <string.h>
#include "clparse.h"

static void  strip(char *argv[]);

static char  *describe[] = {"#", "", "", "<...>"};

int  clp_parse(char *argv[], clp_info_t cltab[])  {
	char  *progname = argv[0];
	int  argc = 0;
	clp_info_t  *clip;
	unsigned  match;

	while (*argv != NULL)  {
		if (*argv[0] == '-')  {
			match = 0;
			for (clip = cltab;  (clip->word != NULL) && (argv[0] != NULL);
					 ++clip)  {
				if (!strcmp(argv[0], clip->word))  { /* A match! */
					match = 1;
					if (clip->dtype == clp_true)
						*(unsigned *)clip->storage = 1;
					else if (clip->dtype == clp_false)
						*(unsigned *)clip->storage = 0;
					else  {
						if (argv[1] == NULL)  {
							fprintf(stderr, "%s: No argument for \"%s\" switch.\n",
											progname, clip->word);
							return(CLP_NOGOOD);
						}
						if (clip->dtype == clp_int)
							*(int *)clip->storage = atoi(argv[1]);
						else
							strcpy((char *)clip->storage, argv[1]);
						strip(argv+1);
					}
				}
			}
			if (!match)  {
				if (strcmp(*argv, "-help"))
					fprintf(stderr, "%s: Unknown switch \"%s\".\n", progname, *argv);
				fprintf(stderr, "Legal switches:\n");
				for (clip = cltab;  clip->word != NULL;  ++clip)  {
					if (clip->description != NULL)  {
						char  wordntype[21];

						sprintf(wordntype, "%s %s", clip->word, describe[clip->dtype]);
						fprintf(stderr, "  %-20s %s\n", wordntype, clip->description);
					}
				}
				return(CLP_NOGOOD);
			} else  {
				strip(argv);
			}
		} else  {
			++argv;
			++argc;
		}
	}
	return(argc);
}


static void  strip(char *argv[])  {
	do  {
		argv[0] = argv[1];
		++argv;
	} while (argv[0] != NULL);
}
