about summary refs log tree commit diff
path: root/src/libstddjb/subgetopt.c
blob: 6383a26166233b769311794ffff6fb4e8c2c6e6c (plain) (blame)
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
/* ISC license. */

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

int subgetopt_r (int argc, char const *const *argv, char const *opts, subgetopt *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)
  {
    char c ;
    if (argv[o->ind][0] != '-') return -1 ;
    o->pos++ ;
    c = argv[o->ind][1] ;
    if (c == '-')
    {
      if (argv[o->ind][2]) return o->problem = '-', '?' ;
      o->ind++ ;
      o->pos = 0 ;
      return -1 ;
    }
    if (!c || c == '-') return o->pos = 0, -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 '?' ;
}