////////////////////////////////////////////////////////////////////////
//
// Name:	Plot.C
//
// Purpose:	Encapsulates gnuplot functionality
//
////////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <fstream.h>
#include "Plot.h"



//////////////////////////////////////////////////////////////////
//
//	Plot::Startup
//		1. Creates a gnuplot batch command file
//		2. Forks a child process to run gnuplot
//
//	Input:
//		None
//
//	Output:
//		None
//
//	Returns:
//		void
//
//	Notes:
//		This one definitely deserves some explanation.
//		One major weakness with gnuplot is that is has no
//		control statements (like loops, for instance). Thus,
//		if one wishes to use gnuplot to show dynamic plots,
//		one must essentially direct gnuplot to "reread" the
//		commands in the file which it is currently processing.
//		This is very clumsy for many reasons. Since there are
//		no control statements, the "reread" results in an
//		infinite loop. Also, if the data to be plotted is
//		dynamic, how can one synchronize the update of this
//		data with the nre "reread" by gnuplot?
//
//		In my first draft, I handled this by starting the gnuplot
//		infinite loop and then iterating through crystallize,
//		with each iteration updating an input data file
//		for gnuplot. But since the two processes weren't
//		synchronized, I ran into the following problems:
//			1. Sometimes, the data file was not ready when
//			gnuplot attempted to read from it.
//			2. If the iteration occurred too quickly for
//			gnuplot, gnuplot often missed entire iterations.
//			3. While copying a temporary file into the
//			input file, there is a split second during
//			which the input file will not exist, even if
//			the input file is being copied over from. This
//			was rare, but it did occur, and the result was that
//			gnuplot would crash.
//
//		I've taken care of all of these problems with this
//		draft at the expense of a this new Plot class, which
//		uses some Unix InterProcess Control (IPC) features:
//		forks and named pipes (FIFOs).
//
//		Very briefly, a process can "fork," or spawn, a "child"
//		process which inherits a copy of all of the qualities of
//		the "parent" process. In doing so, the two processes can
//		run independently, and can be directed to do different
//		work, depending on what it is (parent or child). An example
//		of this is in how your shell works. Each time you invoke
//		a shell command, your shell process forks a child to
//		perform that command.
//
//		A FIFO is a special type of file which may be used by
//		different processes to coordinate reading and writing
//		in a first-in-first-out (FIFO) manner. If a process
//		attempts to read from a FIFO and it contains no data,
//		that process will wait (block) until data is present.
//		This is how the gnuplot process works now. This takes
//		of all of the problems I was having in the previous draft.
//
//		This is a little long-winded, but if you're not familiar
//		with IPC, it might be difficult to figure out.
//
//////////////////////////////////////////////////////////////////
void
Plot::Startup()
{
	plotPid = -1;		// If all goes well, this will
						// be set to the process ID (PID)
						// of the forked child process
						// which is running gnuplot;
						// Otherwise, it will be -1 or 0,
						// indicating some error occurred.

	//
	// Write out the commands to the command file
	//
	ofstream cmdFile(cmdFileName);

	//
	// Write out the plot settings and commands. (Note
	// the "reread;" command at the bottom.
	//
	cmdFile
		<< "set title \"Cellular Automata Simulation\"" << '\n'
		<< "set time" << '\n'
		<< "set data style point" << '\n'
		<< "set noxtics" << '\n'
		<< "set noytics" << '\n'
		<< "set nokey" << '\n'
		<< "set xrange [" << xMin << ':' << xMax << ']' << '\n'
		<< "set yrange [" << yMin << ':' << yMax << ']' << '\n'
		//<< "set term dumb" << '\n'
		//
		// Here's the tricky part - have it read from a FIFO
		// This forces synchronization between the application
		// and gnuplot
		//
		<< "plot \'< cat " << DATA_FIFO << "\'" << '\n'
		//
		// The following ("reread") results in an infinite loop
		//
		<< "reread;";
	
	cmdFile.flush();
	cmdFile.close();

	// The code below would not work for me using the Sun
	// Unix C++ compiler, although it worked fine with
	// the IBM AIX compiler. I finally had to give up on
	// it and make the FIFO outside of the application.
	// (This is done in the make file)
	//
	// Now, create the FIFO which will be written to by
	// the application and read from by gnuplot
	//
	//if (mknod(DATA_FIFO, S_IFIFO, S_IRUSR|S_IWUSR) < 0) {
		//perror(DATA_FIFO);
		//exit(2);
	if (0) {
	} else {

		//
		// fork a child to own the gnuplot process
		//
		switch((plotPid=fork())) {

		case -1:
			// The fork failed. Abort.
			// This would happen if the OS ran out of process space
			// or exceeded the max number of processes.
			// Not too likely.
			perror("fork()");
			exit(2);
			break;

		case 0:
			//
			// I'm the child process here. Run the system command
			// to execute gnuplot. Since the command file
			// results in an infinite loop, the system
			// call only ends on some erroneous condition
			// or when the gnuplot process is killed
			//
			{
				char	sysCommand[BUFSIZ];
				sprintf(sysCommand, "gnuplot %s", cmdFileName);
				system(sysCommand);
			}
			exit(2);
			break;

		default:
			//
			// I'm the parent process. Continue working
			// on other things.
			//
			break;
		}
	}
}
