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

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

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

int getnext_idx_tyc_main (FILE* fp, idx_tyc_main* entry)
{
   char buffer[idx_tyc_main_REC_LEN + 2];
   if (fgets((char *)&buffer,idx_tyc_main_REC_LEN+1,fp))
   { 
	strAsINT (buffer,entry);
	return 0;
   }
   else
	return -1;
} /* End of getnext_idx_tyc_main */


long find_idx_tyc_main (idx_tyc_main* key)
{
   static int init=0;
   static idx_tyc_main index[idx_tyc_main_entries];
   
   if (init == 0)
   {
        if (load_idx_tyc_main("tyc_main.idx",(idx_tyc_main*)&index) !=0)
             return -1;
        init=1;
   }

 /* Simlplest case of all - full index !! */
   if ( key->value >= 1 && key->value <= (idx_tyc_main_entries +1) )
      return (index[key->value -1].value); 
   else
      return (-1);
} /* End of find_idx_tyc_main */
