/*
 * wordtable.c
 *
 * Implementation of routines declared in wordtable.h
 *
 * Written by R. Bjork - last revised 02/03/1993
 * Modified by J. Senning - 01/24/1998
 * Modified by J. Senning - 01/06/2000
 * 	- Initialized "direction" in insert() to avoid compiler warning.
 */

#include <stdlib.h>
#include <stdio.h>
#include "wordtable.h"

static nodeptr TheTree = NULL;

nodeptr lookup( WORD word )
{
    nodeptr p = TheTree;
    int i;

    while ( p && ( i = strcmp( word, p -> word ) ) != 0 )
    {
	if ( i < 0 ) {
	    p = p -> lchild;
	} else {
	    p = p -> rchild;
	}
    }
    return p;
}

void insert( WORD word )
{
    nodeptr prev = NULL, cur = TheTree, newnode;
    enum {left, right} direction = left;

    /* Create a new node containing the word */

    newnode = (nodeptr) malloc ( sizeof( node ) );
    strcpy( newnode -> word, word );
    newnode -> frequency = 1;
    newnode -> lchild = NULL;
    newnode -> rchild = NULL;

    /* Check for special case of an empty tree, handle it, and return. */

    if ( TheTree == NULL ) {
	TheTree = newnode;
	return;
    }

    /* Work down tree to a leaf. */

    while ( cur )
    {
	int i;
        
        prev = cur;
        i = strcmp( word, cur -> word );
	if ( i < 0 ) {
	    cur = cur -> lchild;
	    direction = left;
	} else {
	    cur = cur -> rchild;
	    direction = right;
	}
    }

    /* Attach new node as son of leaf found */

    switch ( direction )
    {
        case left:  prev -> lchild = newnode;
                    break;
        case right: prev -> rchild = newnode;
    }
}

/* The following routine is a recursive auxillary for printing the table */

static void auxprint( nodeptr p )
{
    if ( p ) {
        auxprint( p -> lchild );
        printf( "%*s    %5d\n", WORDLEN, p -> word, p -> frequency );
        auxprint( p -> rchild );
    }
}

void printwords( void )
{
    auxprint( TheTree );
}
