#include        <math.h>
#include        <stdio.h>
#include        <string.h>
#include        <string.h>
#include	<time.h>

#include        "..\include\globals.h"

FILE    *fp,*openoutputfile(char *,char *);

static  int     FIRSTIME = 1, oldhour = -1;

/* open a file for read */
/* 0 = fail,  1 = success */
int init_indisk(DWELL *dwell,RADAR *radar,char *fname)   
   {
   int  type;

   if(!(fp = fopen(fname,"rb")))
      {
      printf("cannot open data file %s for reading\n",fname);   
      return(0);
      }
   
   if(read_disk(dwell,radar) != 1)       {printf("first structure not a RADAR\n"); return(0);}
   while((type = read_disk(dwell,radar)) == 1);  /* read past other RADAR structures */
   if(type != 2)       {printf("DWELL structure not found\n"); return(0);}

   return(1);   
   }

/* read either a dwell structure or a radar structure */
int read_disk(DWELL *dwell,RADAR *radar)
   {
   int  len;
   TOP  top;
   char c;

   /* if you fail to read even a little old thing like this, then rewind */
   if(!fread(&top,sizeof(TOP),1,fp))    /* if read fails */
      {
      if(feof(fp))                      /* if failed due to eof */
         {
	 fclose(fp);	/* Close the file and */
	 exit(0);	/* bail out when done */
         }
      else
        return(0);              /* if it wasn't because of end of file */
      }

   len = top.recordlen - sizeof(TOP);
   
   /* sanity check */
   if(len < 0 || len > 10000)
     return(0);  /* nothing read */
      
   if(!strncmp(top.desc,"RHDR",4))      
      {
      if(fread((char *)radar+sizeof(TOP),len,1,fp) != 1)  return(0);
      memcpy(radar,&top,sizeof(TOP));
      return(1);
      }
   
   if(!strncmp(top.desc,"DWEL",4))      
      {
      if(fread((char *)dwell+sizeof(TOP),len,1,fp) != 1)  return(0);
      memcpy(dwell,&top,sizeof(TOP));
      return(2);
      }
   
   return(0); /* unrecognized structure not read */
   }

void write_disk(int type,DWELL *dwell,RADAR *radar,char *fname)
   {
   time_t       time_of_day;
   struct       tm      *fff;
/* 
The following forces a new file to be opened every hour
to avoid creating huge files.  GRG 6/22/98 
*/
   time_of_day = time(NULL);
   fff = gmtime(&time_of_day);
   if(fff->tm_hour != oldhour)
	{
	fclose(fp);
 	oldhour = fff->tm_hour;	
	FIRSTIME = 1;
	}

   if(FIRSTIME)
      {
      FIRSTIME = 0;
      fp = openoutputfile(fname,(char *)getenv("OUT_DATA")); 
/* Modified 11/6/98 GRG
      fp = openoutputfile(fname,""); 
*/
      type = 1; /* force a radar structure to get written */
      }
   
   if(type == 1)
      fwrite(radar,radar->recordlen,1,fp);
   else
      fwrite(dwell,dwell->header.recordlen,1,fp);
   }

void rewind_disk(void)
   {rewind(fp);}

void close_disk(void)
   {
   fclose(fp);
   }

