#include<ctype.h>
#include<stdio.h>
#include<unistd.h>

void usage(){
	fprintf(stderr, "Usage: getoptExample2 [-a aarg] [-b] [-c carg] [file ...]\n");
}

// Processing options with arguments
// The only options to this are -a aarg -b -c carg. 
// Options have no arguments associated with them.
int main(int argc, char **argv){

	// The following track the options we have seen
	int aflag = 0; char *aarg=NULL;
	int bflag = 0;
	int cflag = 0; char *carg=NULL;
	int c;

	// globals include optind, optarg 
	// the string "a:bc:" represents the only options to this command
	// this string indicates that a has an associated argument
	// and c has an associated argument (the colon following the option)
	// try 
	// getoptExample2
	// getoptExample2 -b -a
	// getoptExample2 -b 
	// getoptExample2 -a someArgumentToA
	// getoptExample2 -a someArgumentToA -b -c someArgumentToC 
	// getoptExample2 -a someArgumentToA -c someArgumentToC -b
	// getoptExample2 -a someArgumentToA -c someArgumentToC -b file1 file2 file3
     
	while ((c = getopt (argc, argv, "a:bc:")) != -1){
		switch(c) {
			case 'a':
				aflag = 1;
				aarg=optarg;
				break;
			case 'b':
				bflag = 1;
				break;
			case 'c':
				cflag = 1;
				carg=optarg;
				break;
			default:
				usage();
				return 1;	
				break;
		}
	}
	printf ("aflag = %d, bflag = %d, cflag = %d\n", aflag, bflag, cflag);
	printf ("aarg = %s, carg = %s\n", aarg, carg);

	// argv[optind], argv[optind+1], ... are the remaining (no option) command line arguments
	int index;
	for (index = optind; index < argc; index++){
		printf ("Non-option argument %s\n", argv[index]);
	}
	return 0;
}
