// main6.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "eval6b.h"

FILE		*f;
static char	line[1000];

static bool GetLine (FILE *f, char *line, int MaxLineLen) {
	bool success;	// 'success' is always assigned a value, so it doesn't need initializing.

	if (f == stdin) {
		printf (":");	// Prompt for input.
	}

	if (!fgets (line, MaxLineLen, f)) {
		if (!feof (f)) {
			perror ("GetLine");
		}
		success = false;
	} else {
		success = line[strlen (line) - 1] == '\n';
	}
	return success;
}

static bool more (void) {
	return GetLine (f, line, sizeof (line));
}

static void pause (void) {
	printf ("Press 'enter' to continue\n");
	while (getchar() != '\n') ;
}

int main (int argc, char *argv[]) {
	int			ReturnStatus = 0;			// main() return status.
	char		*filename = "eval6b.dat";	// Default file name.
	bool		done = false;
	proglet_t	prog;

	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);
		prog.reinit(more);
		while (!done) {
			if (more()) {
				const int			MaxArgs = 3;
				proglet_t::value_t	args[MaxArgs];
				int					NumArgs = MaxArgs;	// NOTE: used for both input and output.

				if (prog.ParseBlock (line, &NumArgs, args) == proglet_t::run_e) {
					proglet_t::value_t	t,
										StartTime,
										StepTime,
										StopTime;

					switch (NumArgs) {
						case 0: StartTime = 0.0;		StepTime = 1.0;		StopTime = 1.0;		break;
						case 1: StartTime = 0.0;		StepTime = 1.0;		StopTime = args[0];	break;
						case 2: StartTime = args[0];	StepTime = 1.0;		StopTime = args[1];	break;
						case 3: StartTime = args[0];	StepTime = args[1];	StopTime = args[2];	break;
					}
					for (int i = 0 ; i < NumArgs ; ++i) {
						printf ("Args[%d] = %g\n", i, args[i]);
					}
					pause ();
					printf ("--Dump--------------\n");
					prog.dump();
					pause ();
					StopTime += StepTime/2.0;	// Compensate for rounding errors in the control variable.
					for (t = StartTime ; t < StopTime ; t += StepTime) {
						printf ("--Run %4g-----------\n", t);
						prog.run (t);
						pause ();
					}
					printf ("--------------------\n");
				}
			} else {
				if (!feof (f)) {
					printf ("Error reading from file\n");
				}
				done = true;	// Whether we are at the end of the file or not, we have to stop now.
			}
		}

		if (f != stdin) {
			fclose (f);
		}
	}

	return ReturnStatus;
}