
#define _CRT_SECURE_NO_WARNINGS	  /* disable compiler warnings for standard C functions like strcpy() */

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <winuser.h>
#include <math.h>

#include "globals.h"


int ReadFiles()

{
FILE	*fpt;
int		i,j;
double	reading;
char	CellsFilename[320];

		/* read master file, determine filenames for data and video, and sync offset */
if ((fpt=fopen(MasterFilename,"rb")) == NULL)
  return(0);
fscanf(fpt,"%s",DataFilename);
fscanf(fpt,"%s",VideoFilename);
fscanf(fpt,"%d",&VideoSyncOffset);
fscanf(fpt,"%s",CellsFilename);

		/* read grid scale data */
DataLoaded=0;
if ((fpt=fopen(DataFilename,"r")) == NULL)
  return(0);
TotalData=0;
while (1)
  {
  i=fscanf(fpt,"%lf",&reading);
  if (i != 1)
	break;
  Data[(TotalData*GRID_ROWS*GRID_COLS)+0]=reading;
  for (i=1; i<GRID_ROWS*GRID_COLS; i++)
	fscanf(fpt,"%lf",&(Data[(TotalData*GRID_ROWS*GRID_COLS)+i]));
  i=fscanf(fpt,"%lf",&reading);	  /* delta ms between frames */
  i=fscanf(fpt,"%lf",&reading);	  /* frame count index */
  TotalData++;
  }
fclose(fpt);
DataLoaded=1;

		/* read cells calibration file */
if ((fpt=fopen(CellsFilename,"r")) == NULL)
  return(0);
for (i=0; i<GRID_ROWS*GRID_COLS; i++)
  fscanf(fpt,"%lf",&(GridFactor[i]));
fclose(fpt);

		/* Calculate A/D value for zero grams for each cell.
		** It is assumed grid is empty for first 3 seconds of recording. */
for (i=0; i<GRID_ROWS*GRID_COLS; i++)
  GridZero[i]=0.0;
for (i=0; i<45; i++)
  for (j=0; j<GRID_ROWS*GRID_COLS; j++)
	GridZero[j]+=Data[(i*GRID_ROWS*GRID_COLS)+j];
for (i=0; i<GRID_ROWS*GRID_COLS; i++)
  GridZero[i]/=45.0;

		/* Convert data voltages to grams.  grams = (A/D - Zero) / Factor */
for (i=0; i<TotalData; i++)
  for (j=0; j<GRID_ROWS*GRID_COLS; j++)
	{
	Data[(i*GRID_ROWS*GRID_COLS)+j]=(Data[(i*GRID_ROWS*GRID_COLS)+j]-GridZero[j])/GridFactor[j];
			/* round numbers just below zero up to zero, to prevent +/- flicker around zero-point */
	if (Data[(i*GRID_ROWS*GRID_COLS)+j] < 0.0  &&  Data[(i*GRID_ROWS*GRID_COLS)+j] > -0.1)
	  Data[(i*GRID_ROWS*GRID_COLS)+j]=0.0;
	}


		/* smooth the data (to be done later if needed) */

		/* open video file and prepare */
VideoLoaded=0;
VideoLoaded=OpenVideoFile(VideoFilename,&DISPLAY_ROWS,&DISPLAY_COLS);
if (VideoLoaded)
  disp_image=(unsigned char *)calloc(DISPLAY_ROWS*DISPLAY_COLS*3,1);

return(1);
}


