// Word lookup with Hash table.
#include<stdlib.h>
#include<stdio.h>
#include<strings.h>

#define MAX_WL 256
#define MAX_H 10

struct HashCell { 
  char word[MAX_WL]; int pos; struct HashCell *next;} Hash[MAX_H];

int h(char *s) {
  int sum=0,i,len=strlen(s);
  for(i=0;i<len;i++) sum+=tolower(s[i]);
  sum = sum % MAX_H;
  return sum;
}

struct HashCell *NewCell(char *s, unsigned int pos) {
  struct HashCell *HC = (struct HashCell *)malloc(sizeof(struct HashCell));
  strcpy(HC->word,s); HC->pos=pos; HC->next=NULL; 
  printf("Insert:%s:%d\n",s,pos);
  return HC;
}

void insert(struct HashCell *HC, char *s, unsigned int pos) {
  // We leave the first cell empty und use it as list head.
  if(!HC->next) { HC->next = NewCell(s,pos); // Insert new element.
  } else { //Check if word is already in list, if not add it.
    while(HC->next) { if(!strcmp(HC->next->word,s)) return; HC=HC->next; }
     HC->next = NewCell(s,pos); 
  }
}

unsigned int LookUp(char *s) {
  struct HashCell *HC =  &Hash[h(s)];
  while(HC->next) { 
    if(!strcmp(HC->next->word,s)) return HC->next->pos; HC=HC->next; }
  return 0;
}

main(int argc, char *argv[]) {
  FILE *f; char s[MAX_WL]; 
  int key,i;
  unsigned int count=0;
  for(i=0;i<MAX_H;i++) Hash[i].next=NULL; //Init Hash table.
  if(argc!=2) { printf("usage: a.out file2\n"); exit(1); }
  if(!(f=fopen(argv[1],"r"))) { printf("open in-file1 error!\n"); exit(1); }
  while(!feof(f)) { // Insert words.
    strcpy(s,"");
    if(fscanf(f,"%s",s) && strlen(s)) {
      count++;
      key = h(s);
      printf("%s->%d:%d\n",s,key,count);
      insert(&Hash[key],s,count);
    }
  } 
  close(f);
  // Lookup words.
  do { 
    scanf("%s",s); count = LookUp(s);  
    if(count) printf("%s at pos %d\n",s,count); else printf("-Not found-\n");
  } while(!feof(stdin)); // Stop with Ctrl-D.
}



