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

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

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

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


long find_idx_hip_j (idx_hip_j* key)
{
   static int init=0;
   static idx_hip_j index[idx_hip_j_entries];
   
   if (init == 0)
   {
        if (load_idx_hip_j("hip_j.idx",(idx_hip_j*)&index) !=0)
             return -1;
        init=1;
   }

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