/*
 * Purpose: to demonstrate the use of the getopt() function call
 * Note: This program WILL NOT compile with gcc -ansi!
 */

#include <stdio.h>
#include <stdlib.h>  /* for atoi() */
#include <unistd.h>  /* for getopt() */


int main(int argc, char **argv)
{
    int c;
    /*The 3rd parameter to getopt is a string.  The letters in this string
      are the commandline options you're looking for. If the letter is followed
      by a : then that option has a parameter, stored in the global variable
      optarg.  optind is another global used by getopt, it holds the index of
      the next commandline argument yet to be parsed.*/
    while ((c = getopt(argc, argv, "a:b:cg")) != EOF) {
        switch (c) {
            case 'a':
                printf("option a, arg=%s,optind=%d\n",optarg,optind);
                break;
            case 'b':
                printf("option b, arg=%s,optind=%d\n",optarg,optind);
                break;
            case 'c':
                printf("option c, arg=%s,optind=%d\n",optarg,optind);
                break;
            case 'g':
                printf("option g, arg=%s,optind=%d\n",optarg,optind);
                break;
            case '?':
                printf("unknow arg!\n");
                break;
            default:
                printf("handle error: print usage\n");
                break;
        }
    }

    if (optind >= argc) {
        printf("no further arguments.\n");
    } else {
        for (; optind < argc; optind++)
            printf("remaining args: optind=%d,%s\n", optind,argv[optind]);
	}

    return(0);
}

/*
A sample run produces the following:
getopt2 -a aarg -b barg -c -f blah
option a, arg=aarg,optind=3
option b, arg=barg,optind=5
option c, arg=(null),optind=6
getopt2: invalid option -- f
unknow arg!
remaining args: optind=7,blah

Notice:
1. when a and aarg are printed, optind points to 3, which is -b, to be parsed next.
2. when getopt() doesn't expect an option, as in -c, optarg is null.
3. when an invalid option is passed, getopt() prints out an
   error message, and returns the '?' character

Another sample run:

getopt2 -a
getopt2: option requires an argument -- a
unknow arg!
no further arguments.

Notice that when you omit a required argument, getopt() prints an error, and return '?'

One final run:

getopt2 param1 -c param2 -a aarg
option c, arg=(null),optind=3
option a, arg=aarg,optind=6
remaining args: optind=4,param1
remaining args: optind=5,param2

Notice:
1. the recognized parameters don't have to be in any particular order.
2. getopt actually modifies the argv array, so any non-option arguments
   get lumped together at the end.
*/

