#ifndef __PLOT_H
#define __PLOT_H

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

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <iostream.h>
#include <string.h>
#include "Dimension.h"

#define CMD_FILE	"plotcmds"		// gnuplot command file

#define DATA_FIFO	"PLOTFIFO"		// FIFO from which raw data
									// for gnuplot shall be read
									// NOTE: This is presently
									// created by the make file.

class Plot {

public:

	//
	// Default constructor
	//
	Plot() : cmdFileName(0), plotPid(-1)
	{ xMin = xMax = yMin = yMax = 0; }


	//
	// Copy constructor
	//
	Plot(const Plot& P) :
		cmdFileName(strdup(P.cmdFileName)), plotPid(-1),
		xMin(P.xMin), xMax(P.xMax), yMin(P.yMin), yMax(P.yMax)
		{}


	//
	// Fully-defining constructor
	//
	Plot(
	const Dimension_t& xMx,
	const Dimension_t& yMx,
	const Dimension_t& xMn=0,
	const Dimension_t& yMn=0,
	const char *const c=CMD_FILE) :
		cmdFileName(strdup(c)),
		xMin(xMn), xMax(xMx), yMin(yMn), yMax(yMx),
		plotPid(-1)
		{}


	//
	// Overloaded assignment operator
	//
	Plot&
	operator=(
	const Plot&	C)
		{
			if (this != &C) {
				delete this;
				cmdFileName = strdup(C.cmdFileName);
				plotPid = C.plotPid;
				xMin = C.xMin;
				xMax = C.xMax;
				yMin = C.yMin;
				yMax = C.yMax;
			}
			return *this;
		}


	//
	// Destructor
	//
	~Plot()
		{
			//
			// Delete file(s) used by this class
			//
			if (cmdFileName && !access(cmdFileName, F_OK)) {
				remove(cmdFileName);
			}
			// I'm no longer creating/deleting the FIFO
			// within the application since I couldn't
			// get this to work on the Sun C++ compiler.
			//if (!access(DATA_FIFO, F_OK)) {
				//remove(DATA_FIFO);
			//}

			//
			// Kill the system process which ran
			// gnuplot. This probably won't do much
			// with just a SIGTERM signal, bit it
			// may be helpful if something goes wrong
			// with the "system" call.
			//
			if (plotPid>0 && kill(plotPid, SIGTERM)<0) {
				perror("kill()");
			}

			delete[] cmdFileName;
		}


	//
	// See the function header in Plot.C for information
	//
	void
	Startup();

private:
	char		*cmdFileName;	// Name of the gnuplot command file
	Dimension_t xMin, xMax, 	// Ranges for the plot
				yMin, yMax;

	pid_t		plotPid;		// process ID (PID) of the
								// process running gnuplot

};


#endif // __PLOT_H
