/* Index access routines */ 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "utils.h"
#include "hg_notes.h"
#include "ihgnotes.h" 

int load_idx_hg_notes (char* ifile,idx_hg_notes* index) 
{
/* Routine to load an index from a file. The structure for the index must
 * already exist as must the file of course
 */
   idx_hg_notes idx;
   FILE *fp;
   int i;

   if ( (fp=fopen(ifile,"r"))==NULL)
   {
	fprintf(stderr,"load_idx_hg_notes unable to open %s \n",ifile);
	return (-1);
   }
   if (index == NULL) 
   {
      fprintf (stderr,"load_idx_hg_notes NULL pointer for index\n");
      return (-1);
   }
   /*printf("Loading index idx_hg_notes from %s.. ",ifile);*/
   for (i=0;i<idx_hg_notes_entries;i++)
   {
	if ( (getnext_idx_hg_notes (fp,&index[i])) != 0)
   	{
	   fprintf(stderr,"load_idx_hg_notes problem with entry %d \n",i);
	   break;
	}
   /*     if  ( (i % 5000) == 0) printf("#");*/
   }
   if ( i < idx_hg_notes_entries) 
   {
	fprintf(stderr,"Premature end of index file \n");
   	return -1;
   }
   /* printf(" done \n"); */
   return 0;
} /* End of load_idx_hg_notes*/

int getnext_idx_hg_notes (FILE* fp, idx_hg_notes* entry)
{
   char buffer[idx_hg_notes_REC_LEN + 2];
   if (fgets((char *)&buffer,idx_hg_notes_REC_LEN+1,fp))
   { 
	char delimiter[3]="|\r\0";
	char *token=strtok((char *)&buffer,(char *)&delimiter); 
	strAsINT(token,&entry->HIPID);
	token=strtok(NULL,delimiter);
	strAsINT(token,&entry->RECNO);
   return 0;
   }
   else
        return -1;
} /* End of getnext_idx_hg_notes */

long find_idx_hg_notes (INT* key)
{
   static int init=0;
   static idx_hg_notes index[idx_hg_notes_entries];
   int mid,lpos,rpos,found;
   if (init == 0)
   {
        if (load_idx_hg_notes("../notes/hg_notes.idx",(idx_hg_notes*)&index) !=0)
             return -1;
        init=1;
   }

   /*  Binary search */ 
   rpos = key->value; 
   lpos = 0;
   if (rpos > idx_hg_notes_entries) rpos = idx_hg_notes_entries;
   found = 0;
   while (!found && !(lpos==mid && rpos==mid || lpos > rpos))
   {
	mid =  (rpos + lpos) /2;
        found = index[mid].HIPID.value == key->value;
     	if (key->value > index[mid].HIPID.value )
	   lpos = mid+1;
	else
	   if (key->value < index[mid].HIPID.value)
	      rpos = mid;
	/*printf (" %d,%d Betweeen %d,%d and %d,%d Key = %d\n",mid,index[mid].HIPID.value,lpos,index[lpos].HIPID.value,rpos,index[rpos].HIPID.value,key->value);*/
   }
   if (found)
	return index[mid].RECNO.value;
   else
   {
      return -1;
   }
   
} /* End of find_idx_hg_notes */


