/*  checkup.c : program to do a validity check on an autolog data file 
 *
 *    By Joel Swank 8/30/88
 *     Version 1.1
 */

/*
   Reads a datafile of gasoline purchases of the following format:
   Individual fields separated by commas.
   * date - character format
   * odometer reading - 999999.9
   * price per gallon - $9.999
   * Total cost of purchase - $9999.99
   * gallons - 999.9
   * place and brand of gas - character
   Execute from cli.

*/

#include <stdio.h>
#include <time.h>
#include <ctype.h>

char linebuf[100];

main(argc,argv)
int argc;
char *argv[];
{
   char *pp, *tp;
   float od, previous, cost, price, atof();
   int yr, previousyr;
   FILE *fp;
   previous = 0;
   previousyr = 0;
   if (argc == 0) exit(0);
   if (argc != 2) 
      {
	  fprintf(stderr,"Usage:checkup datafile\n");
	  exit(0);
	  }
   if ((fp = fopen(argv[1],"r")) == NULL)
      {
	  fprintf(stderr,"checkup:%s:File not found\n",argv[1]);
	  exit(0);
	  }
   while (NULL != fgets(linebuf,100,fp))
      {

	  pp = linebuf;

	  while (*(++pp) != ',') badchk(*pp);	/* find end of date */
	  pp -= 4;
	  yr = atoi(pp);	/* get year */
	  if (previousyr)
	  	{
	  	if (yr != previousyr && yr != previousyr+1 )
	  		{
			fprintf(stderr,"Error - year inconsistant with  previous\n");
			fprintf(stderr,"%s\n", linebuf);
			} else previousyr = yr;
		} else previousyr = yr;

	  pp += 5;

	  od = atof(pp);	/* get odometer reading */
	  if (od < previous)
	  	{
		fprintf(stderr,"Error - odometer reading less than previous\n");
		fprintf(stderr,"%s\n", linebuf);
		} else previous = od;

	  while (*(++pp) != ',') badchk(*pp);
	  while (*(++pp) != '$') badchk(*pp);	/* get price */
	  pp++;
	  price = atof(pp);
	  if (price > 10.0)
	  	{
		fprintf(stderr,"Error - price greater than $10.00\n");
		fprintf(stderr,"%s\n", linebuf);
		} 
	  if (price <= 0.0)
	  	{
		fprintf(stderr,"Error - price less than $0.01\n");
		fprintf(stderr,"%s\n", linebuf);
		} 

	  while (*(++pp) != ',') badchk(*pp);
	  while (*(++pp) != '$') badchk(*pp);	/* get cost */
	  pp++;
	  cost = atof(pp);
	  if (cost <= 0.0)
	  	{
		fprintf(stderr,"Error - cost less than $0.01\n");
		fprintf(stderr,"%s\n", linebuf);
		} 
	  }
	  fclose(fp);
}

/*
 * badchk : check for invalid character and 
 *          terminate if found
 */

badchk(ch)
char ch;
{
	if ( isprint(ch) ) return;
	fprintf(stderr,"File Format Error - Aborting.\n");
	fprintf(stderr,"%s\n", linebuf);
	exit(2);
}
