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

char	*optarg = NULL;
int		optind = 1;			/* start at 1, 'cos argv[0] is program's own name */
int		opterr = 1;

char getopt( int argc, const char *argv[], const char *optstring )
{
int current_argnum, requires_argument;
char switch_letter, *arg, *switchpos;

/* start out with optarg = NULL until we find something to set it to. */

	optarg = NULL;

/* Don't scan past end of argv[] list... */

	if( optind > argc )
	{
		printf( "Whoops!  Scanned past list of argv[] list!\n" );
		return (char)(-1);
	}

/* Get current argv[] item number & string */

	current_argnum = optind;
	arg = (char *)argv[current_argnum];

/* If not starting with a '-' then it's not a switch and we should exit. */

	if( arg[0] != '-' )
	{
		/* leave 'optind' pointing at current argument... */
		return (char)(-1);			/* Not a switch */
	}

/* It's a switch, so get letter and verify it's a recognized switch */

	switch_letter = arg[1];
	switchpos = strchr( optstring, (int)switch_letter );

/* If the switch letter is followed by a colon in 'optstring', then the */
/* argument is not optional and must be provided. */

	if( switchpos != NULL )
	{
		requires_argument = (switchpos[1] == ':') ? 1 : 0;

/* Point argument pointer at character following switch letter */
/* If the switch string has more stuff in it, then that is the argument */

		if( arg[2] )
		{
			optarg = &arg[2];
			optind++;
			return( switch_letter );
		}

/* Otherwise the next argv[] entry should be the argument */
/* So, get next argument, point 'optarg' at it. */

		else
		{

/* Move to next argument, make sure it's in range */

			if( optind <= argc && requires_argument )
			{
				optarg = (char *)argv[++optind];
				optind++;
				return( switch_letter );
			}
			else if( ! requires_argument )
			{
				optind++;
				return( switch_letter );
			}
		}

/* If optarg isn't point at anything, then argument must be missing! */

		printf( "Checking for error...\n" );
		if( requires_argument && ! optarg )
		{
			if(opterr)
			  fprintf( stderr, "Switch argument missing for -%c\n", (int)switch_letter );
		}
	}

/* If the switch wasn't in the option string, then show error */

	else
	{
		optind--;			/* back up to this argv[] item */
		if( opterr )
		  fprintf( stderr, "Unrecognized argument: -%c\n", (int)switch_letter );
		return( '?' );
	}

/* If we get all the way down here, then we don't have a clue...
   So bail out with 'show usage' code */

	optind++;
	return( '?' );
}

