/**
 * Generic command line option handler
 *
 * @copyright 2008, Research In Motion Ltd.
 *
 * @version $Id: //depot/rel/dsp/ecall/2/c/testlab/option.c#1 $
 */

#include <stdlib.h>
#include <stdarg.h>
#include "option.h"

int option(char *argv, char *options[], ...) {
    int k = 0;

    /* Try each option until we find one that matches*/
    while (*options != NULL) {
        char *i = argv;
        char *o = *options;
        char *pv;
        int state = 0;
        int match = 0;
        va_list args;
        va_start(args, options);

        /* Try to match */
        while (1) {
            if (state == 0) {
                if ((*o == '\0') || (*i == '\0')) {
                    match = (*o == '\0') && (*i == '\0');
                    break;
                }

                if (*o == '%') {
                    pv = va_arg(args, char *);
                    state = 1;
                    o++;
                }
                else if (*o != *i) {
                    break;
                }
                else {
                    o++;
                    i++;
                }
            }
            else {
                if (*o == 's') {
                    if ((*i == '\0') || (o[1] == *i)) {
                        state = 0;
                        *pv = '\0';
                        o++;
                    }
                    else {
                        *pv++ = *i++;
                    }
                }
                else {
                    break;
                }
            }
        }
        va_end(args);

        if (match) return k;
        k++;
        options++;
    }
    return -1;
}
