/* getopt -- process command line arguments for shell scripts */

#include <limits.h>
#ifndef ARG_MAX
#define ARG_MAX		5120
#endif
#include <stdio.h>
#include <string.h>

usage()
{ 
	fprintf(stderr, "usage: getopt <arg-description> $*\n");
	exit(2);
}

struct { int opt; char *arg; } args[ARG_MAX];
int nargs = 0;

add(int c, char *p)
{
	if (nargs >= ARG_MAX)
		return;
	args[nargs].opt = c;
	args[nargs].arg = p;	/* should this be strdup(p) instead ? */
	nargs++;
}

main(argc, argv)
	char **argv;
{
	int i, c;
	char *p;
	char *opts;

	extern int optind;	/* maybe get these from <unistd.h> if	  */
	extern char *optarg;	/* _POSIX_SOURCE  defined? naa won't work */

	if (argc < 2)
		usage();

	opts = argv[1];
	argv[1] = argv[0];

	while ((c = getopt(argc - 1, argv + 1, opts)) != EOF) {
		if (c == '?')
			exit(1);
		if ((p = index(opts, c))  && p[1] == ':')
			add(c, optarg);
		else
			add(c, (char *)0);
	}

	for (i = 0; i < nargs; i++)
		printf(args[i].arg ? "-%c %s " : "-%c ",
			args[i].opt, args[i].arg);
	printf("--");
	for (; optind < argc - 1; optind++)
		printf(" %s", argv[optind + 1]);
	putchar('\n');
	exit(0);
}
