summaryrefslogtreecommitdiff
path: root/src/libstddjb/subgetopt.c
blob: 67cdfa11f297061a8f5bbec14315b7658c9935ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* ISC license. */

#undef SUBGETOPT_SHORT
#include <skalibs/sgetopt.h>

int subgetopt_r (int argc, char const *const *argv, char const *opts, subgetopt_t *o)
{
  o->arg = 0 ;
  if ((o->ind >= argc) || !argv[o->ind]) return -1 ;
  if (o->pos && !argv[o->ind][o->pos])
  {
    o->ind++ ;
    o->pos = 0 ;
    if ((o->ind >= argc) || !argv[o->ind]) return -1 ;
  }

  if (!o->pos)
  {
    if (argv[o->ind][0] != '-') return -1 ;
    else
    {
      char c ;
      o->pos++ ;
      c = argv[o->ind][1] ;
      if (c == '-') o->ind++ ;
      if (!c || (c == '-'))
      {
        o->pos = 0 ;
        return -1 ;
      }
    }
  }
  {
    char c = argv[o->ind][o->pos++] ;
    char const *s = opts ;
    char retnoarg = (*s == ':') ? (s++, ':') : '?' ;
    while (*s)
    {
      if (c == *s)
      {
        if (s[1] == ':')
        {
          o->arg = argv[o->ind++] + o->pos ;
          o->pos = 0 ;
          if (!*o->arg)
          {
            o->arg = argv[o->ind] ;
            if ((o->ind >= argc) || !o->arg)
            {
              o->problem = c ;
              return retnoarg ;
            }
	    o->ind++ ;
          }
        }
        return c ;
      }
      if (*++s == ':') s++ ;
    }
    o->problem = c ;
  }
  return '?' ;
}