Works with letters, added trimmed Lovecraft
[name-generation.git] / element-lists / names-2.0.1 / src / getopt.c
1 #include <stdio.h>
2 #include <string.h> /* strchr */
3 #include "getopt.h"
4
5 #define ERROR '?'
6 #define FINISHED -1
7
8 #define NIL 0
9 #define SWI 1
10 #define OPT 2
11 #define ARG 3
12 #define DONE 4
13
14 int optind = 1;
15 int opterr = 0;
16 char *optarg = "";
17
18 int getopt(int argc, char **argv, char *str)
19 {
20 static int a=0; /* index into argv[optind] */
21 char *s; /* index into str */
22 static int opt=0; /* are we currently looking at an option? */
23 static int state=NIL; /* current state */
24
25 opterr=0;
26
27 /* are we done? */
28 if (optind >= argc) return FINISHED;
29
30 /* end of current arg? */
31 if (argv[optind][a]==0)
32 {
33 optind++; /* move on to next arg */
34 if (optind >= argc) return FINISHED; /* nothing more to do */
35 a=0;
36 state=NIL;
37 }
38
39 optarg = argv[optind]; /* give it a default value */
40
41 /* look for next option */
42 /* starting a new argument? */
43 if (a==0)
44 {
45 /* is it a switch? */
46 if (argv[optind][a]=='-' || argv[optind][a]=='/')
47 {
48 a++; /* next char */
49
50 /* if optarg is a single "-", finished */
51 if (argv[optind][a]==0)
52 {
53 optind++;
54 return FINISHED;
55 }
56 state = OPT; /* now processing an opt */
57 }
58 /* not switched, must be an arg */
59 else return FINISHED;
60 }
61 else /* not a new argument */
62 {
63 if (state != OPT) { printf("state!=OPT\n"); return '?'; }
64 }
65
66 /* find the opt */
67 s = strchr(str, argv[optind][a]);
68 if (s == 0)
69 {
70 fprintf(stderr,"unknown option '%c'\n", argv[optind][a]);
71 opterr=1;
72 return ERROR;
73 }
74 a++;
75
76 if (s[1]==':')
77 {
78 if (argv[optind][a]==':') /* allow -o:str */
79 a++;
80
81 if (argv[optind][a]==0) /* handle -o str */
82 {
83 optind++;
84 if (optind >= argc) /* oops, no optarg */
85 {
86 fprintf(stderr,"option '%c' requires an argument\n", *s);
87 opterr=1;
88 return ERROR;
89 }
90 a=0;
91 }
92
93 optarg = argv[optind]+a; /* no longer in arg */
94 optind++; /* advance to next arg */
95 a=0;
96 state = NIL; /* reset state */
97 return *s;
98 }
99 else return *s; /* got valid option */
100 }
101