#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/file.h>
#include "btree.h"

main()
{
  BT_INDEX *kw_index;
  FILE *kw_text;
  char buf[BUFSIZ],label[BUFSIZ];
  char *p;
  long where;
  int is_menu;

  kw_text = fopen("/usr/tmp/new_kw","r+");
  kw_index = bt_open("/usr/tmp/new_kw.dat",O_CREAT,0644);

  while(fgets(buf,BUFSIZ,kw_text) != NULL) {
    p = index(buf,'\n');
    if (p != NULL) *p = '\0';
    if (fgets(label,BUFSIZ,kw_text) == NULL) {
      fprintf(stderr,"unexpected end of file\n");
      exit(1);
    }
    if (strncmp(label,"menu",4) == 0)
      is_menu = 1;
    else
      is_menu = 0;

    where = ftell(kw_text);
    if (is_menu)
      where = -where;

    /* Insert in database */
    if (bt_insert(kw_index,(bt_chrp)buf,strlen(buf),(off_t)where,0)
	!= BT_OK) {
      fprintf(stderr,"Error inserting %s at %d\n",buf,where);
    }

    /* Skip actual node id/menu file */
    if (fgets(buf,BUFSIZ,kw_text) == NULL) {
      fprintf(stderr,"unexpected end of file\n");
      exit(1);
    }
    
    /* Skip blank line */
    if (fgets(buf,BUFSIZ,kw_text) == NULL) {
      fprintf(stderr,"unexpected end of file\n");
      exit(1);
    }
  }

  fclose(kw_text);
  bt_close(kw_index);
}
