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

	/* Evaluate the performance of the scale weight bite detector.
	** Reads two files:  the machine detection and the ground truth.
	** Machine detection contains 1 bite per row, fields are
	** start end weight.
	** Ground truth contains 1 bite per row, fields are
	** counter time-index hand utensil container food.
	** TPs, FPs and FNs are calculated based upon matching the ground
	** truth times within the given machine detected ranges.
	*/

#define	MAX_MD		1000	/* max number of machine detections */
#define MAX_GT		1000	/* max number of ground truth bites */

int main(int argc, char *argv[])

{
FILE		*fpt;
int		i,j;
int		TotalMD;
int		MDStart[MAX_MD],MDEnd[MAX_MD];
double		weight;
int		TotalGT,BitesInWindow;
int		GTTime[MAX_GT];
int		index;
char		hand[320],utensil[320],container[320],food[320];
int		TotalTP,TotalFN,TotalFP,TotalMulti;
int		MDClass[MAX_MD],GTClass[MAX_GT];

if (argc != 3)
  {
  printf("Usage:  perf [machine] [ground-truth]\n");
  exit(0);
  }

if ((fpt=fopen(argv[1],"r")) == NULL)
  {
  printf("Unable to open %s for reading\n",argv[1]);
  exit(0);
  }
TotalMD=0;
while (1)
  {
  i=fscanf(fpt,"%d %d %lf",&(MDStart[TotalMD]),&(MDEnd[TotalMD]),&weight);
  if (i != 3)
    break;
  TotalMD++;
  if (TotalMD >= MAX_MD)
    {
    printf("MAX_MD (%d) exceeded\n",MAX_MD);
    exit(0);
    }
  }
fclose(fpt);

if ((fpt=fopen(argv[2],"r")) == NULL)
  {
  printf("Unable to open %s for reading\n",argv[2]);
  exit(0);
  }
TotalGT=0;
while (1)
  {
  i=fscanf(fpt,"%d %d %s %s %s %s",&index,&(GTTime[TotalGT]),
	hand,utensil,container,food);
  if (i != 6)
    break;
  TotalGT++;
  if (TotalGT >= MAX_GT)
    {
    printf("MAX_GT (%d) exceeded\n",MAX_GT);
    exit(0);
    }
  }
fclose(fpt);

for (i=0; i<TotalMD; i++)
  MDClass[i]=0;		/* not classified */
for (i=0; i<TotalGT; i++)
  GTClass[i]=0;		/* not classified */

	/* Go through all MDs classifying each. */
for (i=0; i<TotalMD; i++)
  {
  BitesInWindow=0;
  for (j=0; j<TotalGT; j++)
    if (GTTime[j] >= MDStart[i]  &&  GTTime[j] <= MDEnd[i])
      BitesInWindow++;
  if (BitesInWindow == 1)
    MDClass[i]=1;	/* TP */
  else if (BitesInWindow > 1)
    MDClass[i]=3;	/* multiple bites in one MD */
  else
    MDClass[i]=2;	/* FP */
  }
	/* Now go through GTs to finish classification. */
for (i=0; i<TotalGT; i++)
  {
  for (j=0; j<TotalMD; j++)
    if (GTTime[i] >= MDStart[j]  &&  GTTime[i] <= MDEnd[j])
      break;
  if (j < TotalMD  &&  MDClass[j] == 1)
    GTClass[i]=1;	/* TP */
  else if (j < TotalMD  &&  MDClass[j] == 3)
    GTClass[i]=3;	/* multiple bites in one MD */
  else
    GTClass[i]=4;	/* FN */
  }
TotalTP=TotalFP=TotalFN=TotalMulti=0;
for (i=0; i<TotalGT; i++)
  if (GTClass[i] == 1)
    TotalTP++;
  else if (GTClass[i] == 3)
    TotalMulti++;
  else
    TotalFN++;
for (i=0; i<TotalMD; i++)
  if (MDClass[i] == 2)
    TotalFP++;

printf("%s TP %d multi %d FN %d FP %d\n",&(argv[1][6]),
	TotalTP,TotalMulti,TotalFN,TotalFP);
}

