/* makeindex */ 

#include <stdio.h>
#include <ctype.h>
#include <sys/types.h> 
#include <netinet/in.h>
#include "hash.h"

FILE *libfptr; 
FILE *indxfptr;

#define ALLOCINC 1000
#define ALLOCSIZE (libsize * 3)
Entry entries;
Entry indexed;
int alloced;
int libsize;

void *Malloc(int size) ;

main(int argc, char *argv[])
{
  
  if (argc != 3 ) {
    printf("usage: makeindex libfile indexfile");
    exit(-1);
  }
  
  libfptr = fopen(argv[1],"r");
  indxfptr = fopen(argv[2], "w+");
  
  if( !libfptr ) {
    printf("Unable to open lib file: %s\n", argv[1]);
    exit(-1);
  }

  if( !indxfptr ) {
    printf("Unable to open index file: %s\n", argv[2]);
    exit(-1);
  }

  libsize = 0;
  alloced = 10000;
  entries = (Entry)Malloc(sizeof(struct entry_s) * alloced);
  
  read_library();
  
  indexed = (Entry)Malloc(sizeof(struct entry_s) * ALLOCSIZE);
  make_hash();
  fwrite(indexed,  sizeof(struct entry_s), ALLOCSIZE, indxfptr);
  printf("Number of entries = %d ... size = %d\n", ALLOCSIZE, sizeof(struct entry_s) * ALLOCSIZE);
  
  fclose(indxfptr);
  fclose(libfptr);
}

void *Malloc(int size) 
{
  void *ret;
  
  ret = (void *)malloc(size);
  if(!ret) { 
    perror("malloc");
    exit(-1);
  }
  return ret;
}
read_library()
{
  char str[1024];
  entries[0].indx = htonl(ftell(libfptr));
  while( fgets(str, 1024, libfptr) )  {
    strtok(str, " \t\n\r");
    lower(str);
    strcpy(entries[libsize].str, str);
    libsize++; 
    if (libsize  == alloced) {
      entries = (Entry)realloc(entries, alloced+=ALLOCINC);
      if(!entries) {
	perror("malloc");
	exit(-1);
      }
    }
    entries[libsize].indx = htonl(ftell(libfptr));
  }
}

make_hash() 
{
  int limit,i, indx ;

  bzero(indexed , sizeof(struct entry_s) * ALLOCSIZE);
  limit = ALLOCSIZE;

  for(i = 0; i < libsize; i++) {

    indx = hashindex(entries[i].str, limit);
    while(*(indexed[indx].str)) {
      puts("fault");
      indx ++;
      indx %= limit;
    }
    printf("%s hashed at entry %d\n", entries[i].str, indx);
    indexed[indx] = entries[i];
    
  }
}

