/* checker.c   P. Conrad  CISC105   Fall 2004
   Checks a "costReport.txt" file for validity. */


#include <math.h>
#include <stdio.h>


#define EIGHT_TON_TRIP 14.57
#define TWELVE_TON_TRIP 16.26

#define TOLERANCE 0.001

double computeCost(int trips8, int trips12)
{
  return (trips8 * EIGHT_TON_TRIP) + (trips12 * TWELVE_TON_TRIP);

}

void checkForValidity(double tons, int trips8, int trips12, double cost)
{
  /* check whether tons are covered */

  int differenceOfMoreThanOne, 
    eightTonMoreThan60Percent,  
    twelveTonMoreThan60Percent;  

  if (tons > (trips8 * 8) + (trips12 * 12))
    {
      printf("Insufficient capacity, tons=%12.2lf trips8=%d trips12=%d\n",
	     tons, trips8, trips12);      
    }

  /* check whether rules are followed*/

  differenceOfMoreThanOne = (abs(trips8-trips12) > 1);
  eightTonMoreThan60Percent = ( trips8 > (.60 * (trips8 + trips12) ) );
  twelveTonMoreThan60Percent = ( trips12 > (.60 * (trips8 + trips12) ) );

  if ( (eightTonMoreThan60Percent || twelveTonMoreThan60Percent) && 
       differenceOfMoreThanOne )
    {
      printf("60/40 split violated and diff > 1, "
	     "tons=%12.2lf trips8=%d trips12=%d\n",
	     tons, trips8, trips12);      
    }

  /* check that cost was computed correctly.  Don't compare float or
   double for equality; check if different is less than some tolerance
   (covered in Tan and D'Orazio on page 173-174 (items 5 and 6) */

  if (fabs(computeCost(trips8,trips12) - cost) > TOLERANCE )
    {
      printf("cost is computed incorrectly, "
	     "tons=%12.2lf trips8=%d trips12=%d cost=%12.2lf\n",
	     tons, trips8, trips12, cost);      

    }

  return; /* its a void function */
}

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

  FILE *infile;

  double tons;
  int trips8, trips12;
  double cost;

  int result;
  double totalCost = 0.0;

  /* check command line arguments */

  if (argc!=2)
    {
      fprintf(stderr,"Usage: %s inputfile\n", argv[0]);
      exit(-1);
    }

  /* open input file */

  infile = fopen(argv[1],"r");

  if (infile==NULL)
    {
      fprintf(stderr,"Can't open %s\n", argv[1]);
      exit(-1);
    }
  
  /* read each line from the file and check it */

  result = fscanf(infile, "%lf %d %d %lf", 
		  &tons, &trips8, &trips12, &cost);

  while (result != EOF)
    {
      checkForValidity(tons,trips8,trips12,cost);
      totalCost += cost;
      result = fscanf(infile, "%lf %d %d %lf", 
		      &tons, &trips8, &trips12, &cost);
      
    }

  printf("Total Cost = %13.2lf\n", totalCost);

  return 0;

}

