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

*/

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

//char *get_word();
char *get_word(char *s, char *to, int max);

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

static char *one_ordinal[] = {
	"ZEROTH", "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",
	"SIXTIETH", "SEVENTIETH", "EIGHTIETH", "NINETIETH"
};

static char *decade[] = {
  "HUNDRED", "THOUSAND"
};

char *parse_int(char *tree, int *value)
{
    char	*p, *c;
    int		i,
		valid,
		tmp, 
                digit_tmp;
    char	word[100];
    char	number_str[200];
    char	*n;



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

    tmp=0;
    valid= 0;
    n= number_str;
    for(  ; *p;  ) {

	if( !(c= get_word(p, word, 100) )) break;
	if( !strcmp(word, "OH" ) ) { strcpy(word, "ZERO"); }

	for( i=0; i < 9; i++) {
	    if( !scmp(ten[i], word) || !scmp(ten_ordinal[i], word) ) break;
	}
	if( i < 9 )  {
	    tmp += 10 * (i+1);
	    p= c;
	    valid= 1;
	    continue;
	}

	for( i=0; i < 9; i++) {
	    if( !scmp(teen[i], word) || !scmp(teen_ordinal[i], word) ) break;
	}
	if( i < 9 )  {
	    if( tmp ) {
		sprintf(n, "%d", tmp);
		n += strlen(n);
		tmp= 0;
	    }
	    tmp = 10 + (i+1);
	    sprintf(n, "%d", tmp);
	    n += strlen(n);
	    tmp= 0;
	    p= c;
	    valid= 1;
	    continue;
	}

	for( i=0; i < 10; i++) {
	    if( !scmp(one[i], word) || !scmp(one_ordinal[i], word) ) break;
	}
	if( i < 10 )  {
	    tmp += i;
	    p=c;
	    valid = 1;
	    /* check the next word if it is "hundred" or "thousand" */
	    if( !(c= get_word(p, word, 100) )) {
	      sprintf(n, "%d", tmp);
	      tmp = 0;
	      break;
	    }
	    for( i=0; i < 2; i++) {
	      if( !scmp(decade[i], word) ) break;
	    }
	    digit_tmp = tmp % 10;
	    if( i == 0 )  {
	      tmp += 100 * digit_tmp - digit_tmp;
	      continue;
	    }
	    else if(i == 1) {
	      tmp += 1000 * digit_tmp - digit_tmp;
	      continue;
	    }

	    sprintf(n, "%d", tmp);
	    n += strlen(n);
	    tmp= 0;
	    continue;
	}



	p= c;
    }
    if( tmp) sprintf(n, "%d", tmp);

    *value= atoi(number_str);
    if( valid ) return(p);
    else return( (char *)0);
}
