/* c-args -- template for a c main, with simple args parser */

/* $Id: c-args,v 1.2 1999/03/14 16:21:01 cdua Exp cdua $ */
/* Carlos Duarte <cgd@mail.teleweb.pt>, 990302 */

/*
 * how to use this: 
 * 
 * USAGE():	change to give a typical usage message
 * options: 	add field to contain args data
 * switch: 	add case entries to catch args
 * 
 * edit after "USER CODE" to do something with other args (non options)
 * 
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int do_args(int first, int ac, char *av[]); 

#define ARG() \
s[1] ? (t=s+1, s+=strlen(s)-1, t) : ++i <argc ? argv[i] : (USAGE(),(char *)0)

#define USAGE() fprintf(stderr, "\
Usage: %s [-n] [-f file] [files]\n", argv[0]), exit(2)

struct options {
	int f_n; 
	char *farg; 
} opts; 

int
main(int argc, char *argv[]) 
{
	int i; 

	for (i=1; i<argc; i++) {
		char *t, *s = argv[i]; 
		t=0; /* shut up warnings */
		if (s[0] != '-' || s[1] == 0) 
			break; 
		if (s[1] == '-' && s[2] == 0) {
			++i;
			break; 
		}
		while (*++s) switch (*s) {
		case 'n': 	
			/* flag option */
			opts.f_n = 1; 
			break; 
		case 'f': 	
			/* one arg option */
			opts.farg = ARG(); 
			break; 
		case '?': 
		default: 
			USAGE();
			break;
		}
	}
	return do_args(i, argc, argv); 
}

/* USER CODE */

static int
do_args(int ix, int argc, char *argv[]) 
{
	if (opts.f_n) printf("received flag -n\n"); 
	if (opts.farg) printf("received arg on -f: %s\n", opts.farg); 

	if (ix == argc) {
		printf("no args\n"); 
	} else {
		printf("remaining args: "); 
		for (; ix<argc; ix++) {
			char *s = argv[ix]; 
			printf("%s ", s); 
		}
		printf("\n"); 
	}
	return 0; 
}
