#include "prog_util.h"
tchar *toptarg;
int toptind = 1, topterr = 1, toptopt;
int
tgetopt(int argc, tchar *argv[], const tchar *optstring)
{
static tchar empty[1];
static tchar *nextchar;
static bool done;
if (toptind == 1) {
nextchar = NULL;
done = false;
}
while (!done && (nextchar != NULL || toptind < argc)) {
if (nextchar == NULL) {
tchar *arg = argv[toptind++];
if (arg[0] == '-' && arg[1] != '\0') {
if (arg[1] == '-' && arg[2] == '\0') {
argv[toptind - 1] = NULL;
done = true;
} else {
nextchar = &arg[1];
}
}
} else {
tchar opt = *nextchar;
const tchar *p = tstrchr(optstring, opt);
if (p == NULL) {
if (topterr)
msg("invalid option -- '%"TC"'", opt);
toptopt = opt;
return '?';
}
nextchar++;
toptarg = NULL;
if (*(p + 1) == ':') {
if (*nextchar != '\0') {
toptarg = nextchar;
nextchar = empty;
} else if (toptind < argc && *(p + 2) != ':') {
argv[toptind - 1] = NULL;
toptarg = argv[toptind++];
} else if (*(p + 2) != ':') {
if (topterr && *optstring != ':') {
msg("option requires an "
"argument -- '%"TC"'", opt);
}
toptopt = opt;
opt = (*optstring == ':') ? ':' : '?';
}
}
if (*nextchar == '\0') {
argv[toptind - 1] = NULL;
nextchar = NULL;
}
return opt;
}
}
toptind = argc;
while (--argc > 0)
if (argv[argc] != NULL)
argv[--toptind] = argv[argc];
done = true;
return -1;
}