/////////////////////////////////////////////////////////////////////////
//
// Name:	CA_main.C
//
// Purpose:	Contains the main() for this cellular automata (CA)
//			simulation.
//
/////////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream.h>
#include "CA_errno.h"
#include "Status.h"
#include "Iteration.h"
#include "Dimension.h"

#include "CellularAutomata2D.h"
#include "Crystallization2D.h"
#include "DeterministicCrystallization.h"
#include "ProbabilisticCrystallization.h"
#include "GameOfLife.h"
#include "Plot.h"


//
// Usage macro, used by the PRINT_LINE() inline.
//
#define USAGE	\
	" [ -mhIicrsp ]\n"	\
	"\t[-h] Display this usage.\n"	\
	"\t[-i<iterations>] Number of iterations to perform.\n"	\
	"\t[-c<columns>] Number of columns in the 2D lattice.\n"	\
	"\t[-r<rows>] Number of rows in the 2D lattice.\n"	\
	"\t-m<g|d|p> Which model to use.\n"	\
	"\t\tg => Game of Life\n"	\
	"\t\tp => Probabilistic crystallization model (not fully implemented)\n"	\
	"\t\td => Deterministic crystallization model (not fully implemented)\n"	\
	"\t[-p<probability factor for Game of Life>] Higher values denote lower probability.\n"	\
	"\t[-I] Interactively prompt for input."


//
// global executable name
//
static char *exeName;

//
// Prints usage when necessary
//
inline void
PRINT_HELP() { cerr << "USAGE: " << exeName << USAGE << endl; }


//
// Prototypes...
//

Status_t getCfg(int, char **,
	Iteration_t *, Dimension_t *, Dimension_t *, char *, int *);
Status_t getCfgI(Iteration_t *, Dimension_t *, Dimension_t *, char *);



/////////////////////////////////////////////////////////////////////////////
//
// main: gets command-line parameters and processed the desired CA model.
//
/////////////////////////////////////////////////////////////////////////////
main(
int		argc,
char	*argv[])
{
	// configurable parameters...
	Iteration_t	iterations;		// Number of iterations to perform (optional)
	Dimension_t	rows, columns;	// Number of lattice rows, columns (optional)
	char		model;			// Model (required)
	int			prob;			// Probability factor for initializing cells
								// eg., 5 => 1/5 probability

	// Assign the global executable name to gobal.
	exeName = argv[0];

	// Get the configurable parameters
	switch(getCfg(argc, argv,
		&iterations, &columns, &rows, &model, &prob)) {

	case SUCCESS: break;

	case FAILURE: default:
		CA_perror("getCfg");
		PRINT_HELP();
		exit(1);
		break;
	}


	//
	// CA object: Note that CellularAutomata2D is a virtual base
	// class. By allocating it with a derived class (see allocation
	// below), the application uses polymorphism to decide how
	// to execute.
	//
	CellularAutomata2D *CA;


	//
	// Use polymorphism to figure out which model to apply
	//
	switch(model) {
	case 'g':
		CA = new GameOfLife(iterations, rows, columns, prob);
		break;

	case 'd':
		cout << "This doesn't do anything interesting right now." << '\n';
		CA = new DeterministicCrystallization(iterations, rows, columns);
		break;

	case 'p':
		cout << "This doesn't do anything interesting right now." << '\n';
		CA = new ProbabilisticCrystallization(iterations, rows, columns);
		break;

	default:
		cout << "Unknown model." << endl;
		PRINT_HELP();
		exit(1);
		break;
	}


	//
	// Create the Plot object. This shall start up gnuplot
	// and direct it to communicate with crystallize via
	// a named pipe (FIFO).
	//
	Plot gnuPlot(CA->Columns(), CA->Rows());
	gnuPlot.Startup();


	//
	// Iterate through, plotting the data after each iteration.
	//
	while (CA->Iterations() <= CA->MaxIterations()) {
		cout << "iteration = " << CA->Iterations() << endl;
		CA->Iterate();
		CA->PlotData();
	}

	delete CA;
	return 0;
}




Status_t
getCfg(
int			argc,
char		**argv,
Iteration_t	*itrs,
Dimension_t	*cols,
Dimension_t	*rows,
char		*modl,
int			*prob)
{
	Status_t	retVal = SUCCESS;
	int			c;
	static char	optString[]="hIi:c:r:m:p:";
	enum { bFALSE, bTRUE }	modelSet = bFALSE;

	extern char	*optarg;
	extern int	optind, opterr;

	// Initialize optional arguments to default values.
	*itrs = DEFAULT_ITERATIONS;
	*rows = *cols = DEFAULT_DIMENSION;
	*prob = 10;

	// Parse/process the command-line data.
	while ((c = getopt(argc, argv, optString)) != -1) {
		switch(c) {

		case 'h':
			PRINT_HELP();
			exit(0);
			break;

		case 'I':
			return getCfgI(itrs, cols, rows, modl);
			break;

		case 'i':
			*itrs = Iteration_t(atoi(optarg));
			if (*itrs <= 0) {
				CA_errno = CINVITE;
				return FAILURE;
			}
			break;

		case 'c':
			*cols = Dimension_t(atoi(optarg));
			if (*cols <= 0) {
				CA_errno = CINVCOL;
				return FAILURE;
			}
			break;

		case 'r':
			*rows = Dimension_t(atoi(optarg));
			if (*rows <= 0) {
				CA_errno = CINVROW;
				return FAILURE;
			}
			break;

		case 'p':
			*prob = atoi(optarg);
			break;

		case 'm':
			*modl = *optarg;
			switch(*modl) {
			case 'g': case 'p': case 'd':
				modelSet = bTRUE;
				break;
			default:
				CA_errno = CINVMDL;
				return FAILURE;
				break;
			}
			break;

		case '?':
			cerr << "Invalid option." << endl;
			PRINT_HELP();
			exit(0);
			break;

		default:
			break;
		}
	}

	if (!modelSet) {
		retVal = FAILURE;
		CA_errno = CNOMODL;
	}

	return retVal;
}




Status_t
getCfgI(
Iteration_t	*itrs,
Dimension_t	*cols,
Dimension_t	*rows,
char		*modl)
{
	int	userInput;

	// Get the iterations
	cout << "Enter the number of iterations to perform: ";
	while(cin >> userInput && userInput <= 0) {
		cout << "Must be a positive integer: ";
	}
	*itrs = Iteration_t(userInput);

	// Get the rows
	cout << "Enter the number of rows for the 2D lattice: ";
	while(cin >> userInput && userInput <= 0) {
		cout << "Must be a positive integer: ";
	}
	*rows = Dimension_t(userInput);

	// Get the columns
	cout << "Enter the number of columns for the 2D lattice: ";
	while(cin >> userInput && userInput <= 0) {
		cout << "Must be a positive integer: ";
	}
	*cols = Dimension_t(userInput);

	// Get the model
	cout << "Enter the model to be used (g, p, or d): ";
	while(cin >> *modl && (*modl!='g' && *modl!='p' && *modl!='d')) {
		cout << "Must be one of (g, p, or d): ";
	}

	return SUCCESS;
}

