#include <stddef.h>
#include <string.h>

/*
  getopt.c by “s’n—CŽ÷
*/

static	int	ac = 0;
static	char	**av = NULL;

int	setopt(int argc, char **argv)
{
    ac = argc;
    av = argv;
    return 0;
}

#define NEXT_LINE()	{line++; pos = 0;}

int	getopt(char c, char *optstr, char **opt1)
{
    static	int	line = 1, pos = 0;
    int		i, ret;
    
START:
    if(av[line][pos] == '\0')
	NEXT_LINE();

    if(line >= ac) return -1;
    
    if(pos == 0) {
	if(av[line][pos] != '-') {
	    *opt1 = av[line];
	    ret = 0;
	    NEXT_LINE();
	    goto END;
	}
	pos++;
    }
    
    for(i = 0; optstr[i] != '\0'; i++) {
	if(av[line][pos] == optstr[i]) {
	    if(optstr[i + 1] == ':') {
		if(av[line][pos + 1] == '\0') {
		    *opt1 = ((line + 1) < ac ? av[++line] : NULL);
		} else {
		    *opt1 = &av[line][pos + 1];
		}
		NEXT_LINE();
	    } else pos++;
	    ret = optstr[i];
	    goto END;
	}
    }
    
    if((i = av[line][pos]) == '\0') goto START;
    pos++;
    return i;
    
END:
    return ret;
}
