struct {
    int id;
    char opt;
    const char *lopt;
    const char *desc;
} opt_tbl[] = {
    {OPT_SIZE, 's', "size", "set image size (format: XxY)"},
    {OPT_SAMP, 'u', "sub", "set subsampling (default: 8)"},
    {OPT_BRUT, 'b',    "brute-force", "disable precalculations\n"},
    {OPT_HELP, 'h', "help", "this help screen"},
    {-1, 0, 0, 0}
};

static int get_option(const char *str) {
    int i = -1;
    while(*str == '-') str++;
    while(opt_tbl[++i].id >= 0) {
        if(str[0] == opt_tbl[i].opt && str[1] == 0) break;
        if(strcmp(opt_tbl[i].lopt, str) == 0) break;
    }
    return opt_tbl[i].id;
}

int main(int argc, char **argv) {
    extern int use_brute_force;
    const char *scene_fname = 0;
    struct scene *scene;
    uint32_t *fb;
    int i;
    int xsz = 640, ysz = 480;
    int sub = 8;

    for(i=1; i<argc; i++) {
        if(argv[i][0] == '-') {
            int opt;
            if((opt = get_option(argv[i])) != -1) {
                switch(opt) {
                case OPT_SIZE:
                    {
                        char *x = strchr(argv[++i], 'x');
                        if(!x || !isdigit(argv[i][0]) || !isdigit(*++x)) {
                            fprintf(stderr, "malformed size argument: %s\n", argv[i]);
                            return EXIT_FAILURE;
                        }
                        xsz = atoi(argv[i]);
                        ysz = atoi(x);
                    }
                    break;

                case OPT_SAMP:
                    if(!isdigit(argv[++i][0])) {
                        fprintf(stderr, "malformed sampling argument: %s\n", argv[i]);
                        return EXIT_FAILURE;
                    }
                    sub = atoi(argv[i]);
                    break;

                case OPT_BRUT:
                    use_brute_force = 1;
                    break;

                case OPT_HELP:
                    {
                        int i = -1;
                        printf("usage: %s [options] <scene file>\noptions:\n", argv[0]);
                        while(opt_tbl[++i].id >= 0) {
                            printf("%8s, %c: %s\n", opt_tbl[i].lopt, opt_tbl[i].opt, opt_tbl[i].desc);
                        }
                        putchar('\n');
                    }
                    return 0;
                }
            } else {
                fprintf(stderr, "unrecognized option: %s\n", argv[i]);
                return EXIT_FAILURE;
            }
        } else {
            if(scene_fname) {
                fprintf(stderr, "unexpected argument: %s\nAlready specified a scene file (%s)\n", argv[i], scene_fname);
                return EXIT_FAILURE;
            }
            scene_fname = argv[i];
        }
    }