
	/*
	** This program reads a set of .csv bite counter files and creates
	** one master .txt file of bite count data.  It determines the
	** subjectID from the .csv file name.  It writes out these fields:
	** subID mealID bites duration year month day hour minute
	** The subID can be used to obtain demographic data from the
	** DEMOGRAPHICS.txt master file.  The date/time info is the start
	** of the meal, and duration is in seconds.
	**/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int ParseField(char *line,int start,int *end)

{
int	i,j,k,a,value;
char	text[320];

i=start;
while (line[i] != ','  &&  line[i] != ':')
  i++;
i++;
j=i;
while (line[j] != ','  &&  line[j] != ':')
  j++;
k=0;
for (a=i; a<j; a++,k++)
  text[k]=line[a];
text[k]=0;
value=atoi(text);
*end=j;
return(value);
}


main()

{
char	filename[320],text[320],line[320];
FILE	*fpt,*fpt2;
int	i,j,k,a;
int	bites,duration;
int	subID,mealID;
int	year,month,day,hour,minute;


fpt=fopen("filenames.txt","r");
while (1)
  {
  i=fscanf(fpt,"%s",filename);
  if (i != 1)
    break;
  strcpy(text,filename);
  text[3]=0;
  subID=atoi(text);
  fpt2=fopen(filename,"r");
  fgets(line,320,fpt2);	/* header line */
  // printf("reading %s\n",filename);
  mealID=1;
  while (1)
    {
    if (fgets(line,320,fpt2) == NULL)
      break;
	/* find duration */
    duration=ParseField(line,0,&j);
	/* find bites */
    i=j;
    bites=ParseField(line,i,&j);
    i=j;
    year=ParseField(line,i,&j);
    i=j;
    month=ParseField(line,i,&j);
    i=j;
    day=ParseField(line,i,&j);
    i=j;
    hour=ParseField(line,i,&j);
    i=j;
    minute=ParseField(line,i,&j);
    if (bites > 0)
      {
      printf("%d %d   %d %.1lf  %d   %d %d %d  %d %d\n",subID,mealID,
		bites,0.0,duration,year,month,day,hour,minute);
      }
    mealID++;
    }
  fclose(fpt2);
  }
fclose(fpt);
}

