]> cloudbase.mooo.com Git - z180-stamp.git/blob - avr/getopt-min.c
8e5dd6c3e026070ec3270808eea1ea71d7b4e02b
[z180-stamp.git] / avr / getopt-min.c
1 #include "common.h"
2
3
4 /*
5 * Minimum getopt, original version was:
6 */
7
8 /*
9 getopt -- public domain version of standard System V routine
10
11 Strictly enforces the System V Command Syntax Standard;
12 provided by D A Gwyn of BRL for generic ANSI C implementations
13 */
14 /* $Id: getopt.c,v 1.2 1992/12/07 11:12:52 nickc Exp $ */
15
16 #include <string.h>
17
18 int optind = 1; /* next argv[] index */
19 char *optarg; /* option parameter if any */
20
21
22 int
23 getopt( /* returns letter, '?', EOF */
24 int argc, /* argument count from main */
25 char *const argv[], /* argument vector from main */
26 const FLASH char *optstring ) /* allowed args, e.g. "ab:c" */
27 {
28 static int sp = 1; /* position within argument */
29 int osp; /* saved `sp' for param test */
30 int c; /* option letter */
31 const FLASH char *cp; /* -> option in `optstring' */
32
33 optarg = NULL;
34
35 if ( sp == 1 ) /* fresh argument */
36 {
37 if ( optind >= argc /* no more arguments */
38 || argv[optind][0] != '-' /* no more options */
39 || argv[optind][1] == '\0' /* not option; stdin */
40 )
41 return -1;
42 }
43
44 c = argv[optind][sp]; /* option letter */
45 osp = sp++; /* get ready for next letter */
46
47 if ( argv[optind][sp] == '\0' ) /* end of argument */
48 {
49 ++optind; /* get ready for next try */
50 sp = 1; /* beginning of next argument */
51 }
52
53 if ( c == ':' /* optstring syntax conflict */
54 || (cp = strchr_P( optstring, c )) == NULL /* not found */
55 )
56 return '?';
57
58 if ( cp[1] == ':' ) /* option takes parameter */
59 {
60 if ( osp != 1 )
61 return '?';
62
63 if ( sp != 1 ) /* reset by end of argument */
64 return '?';
65
66 if ( optind >= argc )
67 return '?';
68
69 optarg = argv[optind]; /* make parameter available */
70 ++optind; /* skip over parameter */
71 }
72
73 return c;
74 }
75