/****************************************************************************/
/* Copyright 2006 MBARI.                                                    */
/* MBARI Proprietary Information. All rights reserved.                      */
/****************************************************************************/

#include <ctype.h>
#include <string.h>
#include "parser.h"

int prsNameMatch(char* s, char* ref)
{
    int n;
    n = 0;

    if (*s == '\0')
        return 0;

    do
    {
        /* check for match */
        if (toupper(ref[n]) != toupper(s[n]))
        {    /* search for another option in ref */
            do
            {
                ++ref;
                if (*ref == '\0')    /* end of ref = NO MATCH */
                    return 0;
            }
            while (*ref != '|');

            ++ref;
            n = 0; /* look at start of string */
        } 
        else
        {
            ++n;
            if (ref[n] == '\0' || ref[n] == '|')
            {
                /* make sure only whitespcae follows */
                if ( !prsIsValidNameChar(s[n]) )
                    return n;  
            }
        }
    }
    while ( n < 40 );    /* 40 chars max */

    return n;
}

char* prsSkip(char* s, char* ignore)
{
    int n;
    n = -1;

    while (ignore[++n] != '\0')
    {
        if (*s == ignore[n])
        {
            ++s;
            n=-1;
        }
    }

    return s;
}

int prsIsInteger(char* txt)
{
    txt = prsSkip(txt, " \t");
    if (*txt == '-' || *txt == '+')
        ++txt;
    txt = prsSkip(txt, " ");
    txt = prsSkip(txt, "0123456789");

    if ( strlen(txt) )
        return 0;
    else
        return 1;
}


int prsIsValidNameChar(char c)
{
    return(isalnum(c) || c == '_');
}

int prsParse(char* line, const CmdStruct* cmds, int err_code)
{
    int chars, i;
    i = 0;

    /* skip any leading white space */
    line = prsSkip(line, " \t");

    /* compare name against names in CmdStruct */
    while (cmds[i].name[0] != '\0')
    {
        chars = prsNameMatch(line, cmds[i].name);
        
        if (chars)
        {
            line = prsSkip(&(line[chars]), " \t");
            return cmds[i].func(line);
        }
        
        ++i;
    }

    return err_code;
}

