/*
    BinTree
*/
#include    <stdio.h>
#include    <string.h>
#include    <ctype.h>

#define HASH_MAX	16
#define	HASH(c)		((c)&15)

#define TRUE    1
#define FALSE   0
#define ERR     (-1)

typedef struct _DP {
    struct _DP  *left;
    struct _DP  *right;
    int         len;
    char        *str;
    char        *snd;
} DATA;

static DATA    *top[HASH_MAX];

extern	char   *strdup(char *str);

static DATA *serch(str)
char    *str;
{
    int     cd,len;
    DATA    *dp,*bp;

    bp = NULL;
    len = 0;
    dp = top[HASH(*str)];
    while ( dp != NULL ) {
        if ( (cd = strncmp(str,dp->str,dp->len)) == 0 && dp->len > len ) {
	    len = dp->len;
	    bp = dp;
        } else if ( cd > 0 )
            dp = dp->left;
        else
            dp = dp->right;
    }
    return bp;
}
void	TALK_str(str)
char	*str;
{
    int     n;
    DATA    *dp;

    while ( *str != '\0' ) {
	if ( (dp = serch(str)) != NULL ) {
	    PLAY_snd(dp->snd);
	    n = dp->len;
	} else if ( iskan(str) )
	    n = 2;
	else
	    n = 1;
	str += n;
    }
}
DATA    *TALK_new(str,snd)
char    *str,*snd;
{
    int     cd;
    DATA    *tp;
    DATA    tmp;
    register DATA *dp;

    cd = 1;
    tmp.left = top[HASH(*str)];
    dp = &tmp;
    for ( ; ; ) {
        if ( cd > 0 ) {
            if ( dp->left == NULL )
                break;
            dp = dp->left;
        } else {
            if ( dp->right == NULL )
                break;
            dp = dp->right;
        }
        if ( (cd = strcmp(str,dp->str)) == 0 )
            return dp;
    }
    if ( (tp = (DATA *)malloc(sizeof(DATA))) == NULL )
        return NULL;

    tp->left = tp->right = NULL;
    tp->len = strlen(str);
    tp->str = strdup(str);
    tp->snd = strdup(snd);

    if ( cd > 0 )
        dp->left = tp;
    else
        dp->right = tp;

    top[HASH(*str)] = tmp.left;

    return tp;
}
int     TALK_init(file)
char    *file;
{
    FILE    *fp;
    char    *str,*snd;
    char    buf[BUFSIZ];
    register char *p;

    sprintf(buf,"%s%s",macget("HOME"),file);
    if ( (fp = fopen(buf,"r")) == NULL )
        return ERR;

    while ( fgets(buf,BUFSIZ,fp) != NULL ) {
        if ( buf[0] == '#' || buf[0] == '\n' )
            continue;
        if ( (p = strchr(buf,'\n')) != NULL )
            *p = '\0';
        p = buf;
        while ( isspace(*p) ) p++;
        str = p;
        while ( !isspace(*p) && *p != '\0' ) p++;
        if ( *p != '\0' )
            *(p++) = '\0';
        while ( isspace(*p) ) p++;
        snd = p;
        if ( *str != '\0' && *snd != '\0' &&
             TALK_new(str,snd) == NULL ) {
            fclose(fp);
            return ERR;
        }
    }
    fclose(fp);
    return FALSE;
}
