#include <iostream.h>
#include <stdlib.h>
#include <string.h>

#include "Hash.h"

Hash::Hash(unsigned size) {
  hashsize = size;
  hashtab = new nodeptr *[hashsize];
  /* Set table to 0 (NULL) */
  memset(hashtab, 0, sizeof(nodeptr *) * hashsize);

}


Hash::~Hash(void) {
  nodeptr *np, *next;

  for( int i=0 ; i<hashsize ; i++ ) {
    for( np = hashtab[i] ; np != NULL ; np = next ) {
      next = np->next;
      //printf("Free'ing %s\n", np->word);
      free(np->word);
      delete np;
    }
  }

  delete[] hashtab;

}


/* returns a pointer to the node in hash table for word, NULL if word is
   not in the table */
nodeptr *Hash::lookup(char *word)
{
     nodeptr *np;

     for( np = hashtab[ hash(word) ] ; np != NULL ; np = np->next )
	  if( strcmp(word, np->word) == 0 )
	       return np;
     
     return NULL; /* Not found */

}


/* Installs node for word on the hash table */
nodeptr *Hash::install(char *word)
{
     nodeptr *np;
     unsigned hashval;
    
     if( (np = lookup(word)) == NULL ) { /* Not found */
	  np = new nodeptr;
	  if( np == NULL || (np->word = (char *)strdup(word)) == NULL )
	       return NULL;
	  hashval = hash(word);
	  np->next = hashtab[hashval];
	  hashtab[hashval] = np;
     }

     return np;

}
