/*
  parse_digits(char *str, int *value);

*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "dm.h"

static char *tens_p, *ones_p;
static char number_string[500];

static char *one[] = {
	"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX",
	"SEVEN", "EIGHT", "NINE"
};

static char *one_ordinal[] = {
	"ZERO", "FIRST", "SECOND", "THIRD", "FOURTH", "FIFTH", "SIXTH",
	"SEVENTH", "EIGHTH", "NINTH"
};

static char *teen[] = {
	"ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN",
	"SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
};

static char *teen_ordinal[] = {
	"ELEVENTH", "TWELFTH", "THIRTEENTH", "FOURTEENTH", "FIFTEENTH",
	"SIXTEENTH", "SEVENTEENTH", "EIGHTEENTH", "NINETEENTH"
};

static char *ten[] = {
	"TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY",
	"SEVENTY", "EIGHTY", "NINETY"
};

static char *ten_ordinal[] = {
	"TENTH", "TWENTIETH", "THIRTIETH", "FORTIETH", "FIFTIETH"
};


char *parse_digits(char *tree, int *value, char *str)
{
    char	*p;
    int		i,
		valid,
		tmp;
    char	word[100];



    /* scan for [ */
    if ( (p= strchr(tree, '[')) ) {
        if ( !(p= strchr(p, '.')) ) return(0);
	p++;
    }
    else p= tree;

    tmp=0;
    valid= 0;
    tens_p= ones_p= number_string;
    number_string[0]= (char)0;
    word[0]= 0;

    for(  ; *p; p += strlen(word)  ) {

	/* skip whitespace */
	while( *p && isspace((int)*p) ) p++;

	if( sscanf(p, "%s", word) < 1) break;

	/* if decade */
	for( i=0; i < 5; i++) {
	    if( !scmp(ten[i], word) || !scmp(ten_ordinal[i], word) ) break;
	}
	if( i < 5 )  {
	    sprintf(tens_p, "%d", (i+1) * 10);
	    ones_p= tens_p +1;
	    tens_p= tens_p +2;
	    continue;
	}

	/* teen */
	for( i=0; i < 9; i++) {
	    if( !scmp(teen[i], word) || !scmp(teen_ordinal[i], word) ) break;
	}
	if( i < 9 )  {
	    sprintf(tens_p, "%d", i+ 11);
	    tens_p= ones_p= tens_p + strlen(tens_p);
	    continue;
	}

	/* if ones */
	if( !scmp("OH", word)  ) {
	    i= 0;
	}
	else {
	    for( i=0; i < 10; i++) {
	        if( !scmp(one[i], word) || !scmp(one_ordinal[i], word) ) break;
	    }
	}
	if( i < 10 )  {
	    sprintf(ones_p, "%d", i );
	    tens_p= ones_p= ones_p + strlen(ones_p);
	    continue;
	}

    }

    if( ones_p > number_string ) valid= 1;
    if( str ) strcpy(str, number_string);
    if( value ) *value= atoi(number_string);
    if( valid ) return(p);
    else return( (char *)0);
}
