/* do binary search on a set of strings to find matching string */

enum token_t { Auto, Break, Case, Char, Const, Continue, Default, Do, Double,
       Else, Enum, Extern, Float, For, Goto, If, Int, Long, Register,
       Return, Short, Signed, Sizeof, Static, Struct, Switch, Typedef,
       Union, Unsigned, Void_Kw, Volatile, While };

static int find_keyword( char * );
static enum token_t do_nothing(enum token_t type);
    
struct cdb_kwd_token
{
	const char * const keyword;
	const enum token_t token;
};

/* the following keywords MUST remain in alphabetical order */
static struct cdb_kwd_token key_toks[] = { 
	{ "auto", Auto },
	{ "break", Break },
	{ "case", Case },
	{ "char", Char },
	{ "const", Const },
	{ "continue", Continue },
	{ "default", Default },
	{ "do", Do },
	{ "double", Double },
	{ "else", Else },
	{ "enum", Enum },
	{ "extern", Extern },
	{ "float", Float },
	{ "for", For },
	{ "goto", Goto },
	{ "if", If },
	{ "int", Int },
	{ "long", Long },
	{ "register", Register },
	{ "return", Return },
	{ "short", Short },
	{ "signed", Signed },
	{ "sizeof", Sizeof },
	{ "static", Static },
	{ "struct", Struct },
	{ "switch", Switch },
	{ "typedef", Typedef },
	{ "union", Union },
	{ "unsigned", Unsigned },
	{ "void", Void_Kw },
	{ "volatile", Volatile },
	{ "while", While }
};

/* binary search for keywords */
static int
find_keyword( char *name )
{
    int low, med, high, cmp;

    low = 0;
    high = sizeof( key_toks ) / sizeof( key_toks[0] );

    while ( low < high )
    {
	med = (low+high)/2;
	cmp = strcmp( name, key_toks[ med ].keyword );
	if ( cmp < 0 )
	    high = high - 1;
	else if ( cmp > 0 )
	    low = med + 1;
	else
	    return med;
    }

    return -1;
}

static enum token_t
do_nothing(enum token_t type)
{
    /* do nothing but return the token type sent to us */
    return type;
}

main()
{
    int indx;
    enum token_t t;
    
    indx = find_keyword("typedef");
    t = key_toks[indx].token;
    do_nothing(t);

    indx = find_keyword("while");
    t = key_toks[indx].token;
    do_nothing(t);

    indx = find_keyword("case");
    t = key_toks[indx].token;
    do_nothing(t);
}
