1 /**
2  * @file attgetopt.c
3  * @ingroup wbxml2xml_tool
4  * @ingroup xml2wbxml_tool
5  *
6  * AT&T's public domain implementation of getopt.
7  *
8  * From the mod.sources newsgroup, volume 3, issue 58, with modifications
9  * to bring it up to 21st century C.
10  */
11 
12 /* Copied from: http://everything2.com/e2node/getopt%2528%2529
13  * getopt renamed to wbxml_getopt
14  */
15 
16 /* getopt.c:
17  * a public domain implementation of getopt()
18  *
19  * The following source code is an adaptation of the public domain getopt()
20  * implementation presented at the 1985 UNIFORUM conference in Dallas,
21  * Texas. Slight edits have been made to improve readability and the result
22  * is released into the public domain like that from which it was derived.
23  *
24  */
25 
26 #include <stdio.h>
27 #include <string.h>
28 
29 int optind = 1;
30 /* useless variable
31 int optopt;
32 */
33 char *optarg;
34 
35 int
wbxml_getopt(int argc,char ** argv,char * opts)36 wbxml_getopt(int argc, char **argv, char *opts)
37 {
38 	static int sp = 1;
39 	register int c;
40 	register char *cp;
41 
42 	if (sp == 1) {
43 
44 		/* If all args are processed, finish */
45 		if (optind >= argc) {
46 			return EOF;
47 		}
48 		if (argv[optind][0] != '-' || argv[optind][1] == '\0') {
49 			return EOF;
50 		}
51 
52 	} else if (!strcmp(argv[optind], "--")) {
53 
54 		/* No more options to be processed after this one */
55 		optind++;
56 		return EOF;
57 
58 	}
59 
60 	/* useless variable: optopt
61 	optopt = c = argv[optind][sp];
62 	*/
63 	c = argv[optind][sp];
64 
65 	/* Check for invalid option */
66 	if (c == ':' || (cp = strchr(opts, c)) == NULL) {
67 
68 		fprintf(stderr,
69 			"%s: illegal option -- %c\n",
70 			argv[0],
71 			c);
72 		if (argv[optind][++sp] == '\0') {
73 			optind++;
74 			sp = 1;
75 		}
76 
77 		return '?';
78 	}
79 
80 	/* Does this option require an argument? */
81 	if (*++cp == ':') {
82 
83 		/* If so, get argument; if none provided output error */
84 		if (argv[optind][sp+1] != '\0') {
85 			optarg = &argv[optind++][sp+1];
86 		} else if (++optind >= argc) {
87 			fprintf(stderr,
88 				"%s: option requires an argument -- %c\n",
89 				argv[0],
90 				c);
91 			sp = 1;
92 			return '?';
93 		} else {
94 			optarg = argv[optind++];
95 		}
96 		sp = 1;
97 
98 	} else {
99 		if (argv[optind][++sp] == '\0') {
100 			sp = 1;
101 			optind++;
102 		}
103 		optarg = NULL;
104 	}
105 
106 	return c;
107 }
108 
109