// main4.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "eval4.h"

// This should be a reasonably bullet-proof line input routine.
// Even if you know input is coming from standard input, don't use gets().
// It doesn't check that the input fits in the space available!
// Always use fgets(), and I suggest wrapping it in something like this.
bool GetLine (FILE *f, char *line, int MaxLineLen) {
   bool success;  // 'success' is always assigned a value, so it doesn't need initializing.

   if (!fgets (line, MaxLineLen, f)) {
      if (feof (f)) {
         // Not actually an error, so don't print an error message.
      } else {
         perror ("GetLine");
      }
      success = false;
   } else {
      // We got something, but was it a complete line or only part of one?
      // The last character of a complete line is always a '\n'.
       success = line[strlen (line) - 1] == '\n';
   }
   return success;
}

int main (int argc, char *argv[]) {
   int   ReturnStatus = 0;          // main() return status.
   char  *filename = "eval4.dat";   // Default file name.
   FILE  *f;
   char  line[100];
   bool  ok;

   if (argc > 1) {
      filename = argv[1];
   }
   if (strcmp ("-", filename) == 0) {
      f = stdin;
   } else {
      f = fopen (filename, "r");
   }
   if (f == 0) {
      printf ("Couldn't open '%s'.\n", filename);
      ReturnStatus = 1;
   } else {
      srand (1234);
      do {
         if (GetLine (f, line, sizeof (line))) {
            value_t	val;

            ok = ParseProglet (line, &val);
            if (ok) printf ("    %g\n", val);
         } else {
            ok = false;
         }
      } while (ok);
      fclose (f);
   }

   return ReturnStatus;
}