1 /*
2  * getopt - get option letter from argv
3  *
4  * This is a version of the public domain getopt() implementation by
5  * Henry Spencer, changed for 4.3BSD compatibility (in addition to System V).
6  * It allows rescanning of an option list by setting optind to 0 before
7  * calling, which is why we use it even if the system has its own (in fact,
8  * this one has a unique name so as not to conflict with the system's).
9  * Thanks to Dennis Ferguson for the appropriate modifications.
10  *
11  * This file is in the Public Domain.
12  */
13 
14 /*LINTLIBRARY*/
15 
16 #include <stdio.h>
17 
18 #ifdef    lint
19 #undef    putc
20 #define    putc    fputc
21 #endif    /* lint */
22 
23 char    *ntp_optarg;    /* Global argument pointer. */
24 int    ntp_optind = 0;    /* Global argv index. */
25 int    ntp_opterr = 1;    /* for compatibility, should error be printed? */
26 int    ntp_optopt;    /* for compatibility, option character checked */
27 
28 static char    *scan = NULL;    /* Private scan pointer. */
29 static const char    *prog = "amnesia";
30 
31 /*
32  * Print message about a bad option.
33  */
34 static int
badopt(const char * mess,int ch)35 badopt(
36        const char *mess,
37        int ch
38        )
39 {
40     if (ntp_opterr) {
41         fputs(prog, stderr);
42         fputs(mess, stderr);
43         (void) putc(ch, stderr);
44         (void) putc('\n', stderr);
45     }
46     return ('?');
47 }
48 
49 int
ntp_getopt(int argc,char * argv[],const char * optstring)50 ntp_getopt(
51            int argc,
52            char *argv[],
53            const char *optstring
54            )
55 {
56     register char c;
57     register const char *place;
58 
59     prog = argv[0];
60     ntp_optarg = NULL;
61 
62     if (ntp_optind == 0) {
63         scan = NULL;
64         ntp_optind++;
65     }
66 
67     if (scan == NULL || *scan == '\0') {
68         if (ntp_optind >= argc
69             || argv[ntp_optind][0] != '-'
70             || argv[ntp_optind][1] == '\0') {
71             return (EOF);
72         }
73         if (argv[ntp_optind][1] == '-'
74             && argv[ntp_optind][2] == '\0') {
75             ntp_optind++;
76             return (EOF);
77         }
78 
79         scan = argv[ntp_optind++]+1;
80     }
81 
82     c = *scan++;
83     ntp_optopt = c & 0377;
84     for (place = optstring; place != NULL && *place != '\0'; ++place)
85         if (*place == c)
86             break;
87 
88     if (place == NULL || *place == '\0' || c == ':' || c == '?') {
89         return (badopt(": unknown option -", c));
90     }
91 
92     place++;
93     if (*place == ':') {
94         if (*scan != '\0') {
95             ntp_optarg = scan;
96             scan = NULL;
97         } else if (ntp_optind >= argc) {
98             return (badopt(": option requires argument -", c));
99         } else {
100             ntp_optarg = argv[ntp_optind++];
101         }
102     }
103 
104     return (c & 0377);
105 }
106