#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>

#include "GraphWin.h"
#include "Label.h"
#include "Graph.h"
#include "Legend.h"
#include "FxDataset.h"
#include "FxyDataset.h"
#include "Column.h"
#include "binio.h"
#include "gw.h"
#include "gwInit.h"

#if defined(__INTEL_COMPILER)
/* icc doesn't like GNU __extension__ functions */
/* this has to happen AFTER !!*/
#undef htons
#undef ntohs
#undef htonl
#undef ntohl
#define htons(x) __bswap_constant_16(x)
#define ntohs(x) __bswap_constant_16(x)
#define htonl(x) __bswap_constant_32(x)
#define ntohl(x) __bswap_constant_32(x)
#endif
/* defined(_ICC) */

struct GraphWindow *firstGW, *lastGW;
struct Graph *firstGraph, *lastGraph;
struct FxDataset *firstFxDataset, *lastFxDataset;
struct FxyDataset *firstFxyDataset, *lastFxyDataset;
struct Column *firstColumn, *lastColumn;
struct Label *firstLabel, *lastLabel;

char *application, *user, *host, *id;
int registered = 0;
int initialized = 0;
int collector = 0;
int transpMonitor = 0;
char xmlS[250];

/*ELVIS_SERVER list implementation variables*/
int numpaths = 0;
FILE* fileList[MAX_PATHS];
char serverList[MAX_PATHS][MAX_SERV_STRLEN];
int portList[MAX_PATHS];
char elvis_server_str[MAX_ENV_STRLEN];
int GWFileCreated = 0;

/*************************************************************
B.Bariteau - 6/27/08 - I added the ability for ELVIS_SERVER to
  be a semicolon-delimited list. The actual delimiting characters
  are in gwInit.h as a string under SERV_DELIM. As of this writing
  those characters are ' ' and ';'. Also, the port used is
  DEF_PORT, currently 7654, unless a port is specified by the
  hostname in the form hostname:port. This also led to changes
  in e_socket_initialize(), but should not affect any older usage of the
  API, except when using e_graphWindowCreateFile(), as the
  concatention no longer works with a list of files.
**************************************************************/
int e_initialize() {
        char servOld[MAX_SERV_STRLEN], *serv, *host;
	char *portptr, *liststrptr, *portstr;
	char elvisServTemp[MAX_ENV_STRLEN];
	size_t n;
	int i = 0, j = 0, pt;
	int port = DEF_PORT;
	FILE* test;

        firstGW = NULL;
	lastGW = NULL;
	firstGraph = NULL;
	lastGraph = NULL;
	firstFxDataset = NULL;
	lastFxDataset = NULL;
	firstFxyDataset = NULL;
	lastFxyDataset = NULL;
	firstLabel = NULL;
	lastLabel = NULL;
	firstColumn = NULL;
	lastColumn = NULL;

	liststrptr = getenv("ELVIS_SERVER");
	    /* printf("e_initialize  %s\n", liststrptr); */

	if(liststrptr == NULL || *liststrptr == '\0'){
	 	printf("ELVIS_SERVER is not set.\nUsing local host.\n");
	 	serverList[0][0] = 'l';
		serverList[0][1] = 'o';
		serverList[0][2] = 'c';
		serverList[0][3] = 'a';
		serverList[0][4] = 'l';
		serverList[0][5] = 'h';
		serverList[0][6] = 'o';
		serverList[0][7] = 's';
		serverList[0][8] = 't';
		serverList[0][9] = '\0';
		numpaths = 1;
	  	return(E_SUCCESS);
	}else if(strlen(liststrptr) >= MAX_ENV_STRLEN){
		printf("ELVIS_SERVER is too long (>= %d chars)\n", MAX_ENV_STRLEN);
		return(E_FAIL);
	}

	strcpy(elvis_server_str, liststrptr);

	strcpy(elvisServTemp, elvis_server_str);

	portstr = getenv("ELVIS_PORT");

	if(portstr != NULL){
	        port = atoi(portstr);
	}else{
	        port = DEF_PORT;
	}

	for(i = 0; i < MAX_PATHS; i++){
	        serverList[i][0] = '\0';
		/* fileList[i] = NULL; */  /* not needed for elvis_transmit */
		portList[i] = port;
	}

	i = 0;

	  /* fill ELVIS_SERVER list implementation variables*/
	serv = strtok(elvisServTemp, SERV_DELIM);
	
	if (serv == NULL) {
	  serv = (char*) &elvisServTemp;
	}

		 /* printf("   serv = %s GWFileCreated = %d\n", serv, GWFileCreated); */
	do {
		if (serv[0] == '.' || serv[0] == '/') {  /* A file */
			  /* printf("  It's a file!\n");  */
		   if (GWFileCreated == 0) {  /*rename if file not yet opened by elvis_transmit */
		        test = fopen(serv, "r");
		        if(test != NULL){/*If file exists, rename to filename~*/
			        printf("File %s already exists, renamed to %s~\n", serv, serv);
			        fclose(test);
				strcpy(servOld, serv);
				strcat(servOld, "~");
				test = fopen(servOld, "r");
				if(test != NULL){/*If filename~ already exists, delete it*/
				        printf("File %s already exists, deleted.\n", servOld);
					fclose(test);
					remove(servOld);
				}
				rename(serv, servOld);
			}
			fileList[i] = fopen(serv, "w");
		    }
  		}else if(strcmp(serv, "stdout") == 0){/*Standard Out*/
		        fileList[i] = stdout;
		}else if(strcmp(serv, "stderr") == 0){/*Standard Error*/
		        fileList[i] = stderr;
		}else if(strcmp(serv, "filegen") == 0){
			serverList[i][0] = 'f';
			serverList[i][1] = 'i';
			serverList[i][2] = 'l';
			serverList[i][3] = 'e';
			serverList[i][4] = 'g';
			serverList[i][5] = 'e';
			serverList[i][6] = 'n';
			serverList[i][7] = '\0';
		}else{ /*A server*/
			  /* printf("  It's a server!\n"); */
		        portptr = strchr(serv, ':');
			if(portptr != NULL){/*Server that specifies a port*/
				n = portptr - serv;
				strncpy(host, serv, n);
				pt = atoi(portptr+1);
			        if(pt == 0){
				  printf("Port in %s could not be parsed.\n", serv);
				  return(E_FAIL);
				}
				portList[i] = pt;
				for(j = 0; j < strlen(host); j++){
				  if(j = strlen(host)){
				    serverList[i][j] = '\0';
				  }else{
				    serverList[i][j] = *(host+j);
				  }
				}
			}else{/*Server that does not specify a port, uses default or ELVIS_PORT value*/
			        portList[i] = port;
				for(j = 0; j <= strlen(serv); j++){
				  if(j == strlen(serv)){
				    serverList[i][j] = '\0';
				  }else{
				    serverList[i][j] = *(serv+j);
				  }
			       	}
			}
		}
      	     	numpaths++;
		i++;
		serv = strtok(NULL, SERV_DELIM);
	}while (serv != NULL && i < MAX_PATHS);

	if(i >= MAX_PATHS){
	  printf("Number of paths is greater than %d\n", MAX_PATHS);
	  return(E_FAIL);
	}
	  /* printf("fileList[0] = %d\n", fileList[0]); */
	  /* printf("e_initialize done\n\n"); */
	return(E_SUCCESS);
}

int e_transpMonitor(int state) {
	transpMonitor = state;
}

int e_free() {
	E_FreeLabels();
	E_FreeColumns();
	E_FreeFxDatasets();
	E_FreeFxyDatasets();
	E_FreeGraphs();
	E_FreeGraphWindows();
	return(E_SUCCESS);
}

int e_register(char *inApplication, char *inUser, char *inHost, char *inId, int collect) {
	application = malloc(strlen(inApplication) + 1);
	strcpy(application, inApplication);

	user = malloc(strlen(inUser) + 1);
	strcpy(user, inUser);

	host = malloc(strlen(inHost) + 1);
	strcpy(host, inHost);

	id = malloc(strlen(inId) + 1);
	strcpy(id, inId);

	collector = collect;
	  /* printf("e_register:  %d\n", collector); */

	if (transpMonitor == 1) {
	  int sockfd;
	  int command = 2;
	  int handle = -1;
	  int length;

   	  sockfd = e_socket_initialize(0);
   	  if (sockfd == -1)
     		return(E_FAIL);

   	  write_int4(sockfd, command);
   	  write_int4(sockfd, handle);
  
   	  length = strlen(application);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, application, length);
  
   	  length = strlen(user);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, user, length);

   	  length = strlen(host);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, host, length);

   	  length = strlen(id);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, id, length);

	  registered = 1;
   	  e_close(sockfd);
	  return(E_SUCCESS);
	}
}

int e_end() {
#ifdef NOT
	int status = 1;
  	int sockfd;
   	int command = COMMAND_END;
   	int   handle = -1;

   	sockfd = e_socket_initialize(0);
   	if (sockfd == -1)
     		return(E_FAIL);

   	/* send command, fake handle (port) */
   	write_int4(sockfd, command);
   	write_int4(sockfd, handle);

	E_writeHandle(sockfd);		/* send the real handle info */

   	e_close(sockfd);
	return(E_SUCCESS);
#endif
	e_free();
}

int e_Graph(char *label[], double x[], double y[], double time[], int nPoints[], int nTime) {
        int i;
        int graphType;
        int loc = 0;
        char *datasetName;
        char numberString[10];
        int id;
	float location[2];
	struct GraphWindow *gw;
	struct GraphWindow *E_GetGraphWindow();
                                                                                
        /* for (i=0; i<6; i++) {
                printf("%s\n", label[i]);
        } */
                                                                               
        e_initialize();
        e_register("app", "user", "host", "id", 0);
                                                                                
        e_GraphWindowCreate(label[0], 1, 1);

	gw = E_GetGraphWindow(label[0]);
	gw->type = E_TIME_INDEXED_ADD_POINTS;
                                                                                
        if (nTime == 0) {
                graphType = E_NO_INDEX;
        }
        else {
                graphType = E_TIME_INDEXED_ADD_POINTS;
        }
                                                                                
        e_GraphCreate(label[1], graphType);
        e_GraphSetXLabel(label[1], label[2]);
        e_GraphSetYLabel(label[1], label[3]);
	e_GraphShowLegend(label[1], 0);
	location[0] = .12;
	location[1] = .14;
	e_GraphSetPlotArea(label[1], location, .84, .78);

        datasetName = malloc(strlen(label[3] + 10));
                                                                                
        if (datasetName == NULL) {
                printf("Could not allocate memory for %s\n", label[3]);
                return(E_FAIL);
        }
                                                                                
        strcpy(datasetName, label[3]);
                  /* printf("%s\n", datasetName); */
                                                                                
        if (nTime == 0) {
                e_FxDatasetCreate(datasetName, nPoints[0], &x[loc], &y[loc]);
                e_GraphAddFxDataset(label[1], datasetName);
	} else {
                e_GraphSetIndexLabel(label[1], label[4]);
	}

        for (i=0; i<nTime; i++) {
                id = e_FxtDatasetCreate(datasetName, nPoints[i], &x[loc], &y[loc], time[i]);
                e_GraphAddFxDatasetID(label[1], id);
                          /* printf("%f %f %f\n", x[loc], y[loc], time[i]); */

                loc += nPoints[i];
        }

        e_GraphWindowAddGraph(label[0], label[1], 0, 0);
                                                                                
        e_GraphWindowDisplay(label[0]);
                                                                                
        e_end();
	e_free();
                                                                                
        return(E_SUCCESS);
}

int e_GraphWindowCreate(windowName, nRows, nColumns)
   char *windowName;
{
   struct GraphWindow *graphWindow;
   int space;

	 /*  printf("GraphWindowCreate = %s\n", windowName); */
   graphWindow = malloc(sizeof(struct GraphWindow));
   if (!graphWindow) {
	return(E_FAIL);
   }

   graphWindow->windowName = malloc(strlen(windowName) + 1);
   if (!(graphWindow->windowName)) {
	return(E_FAIL);
   }

   strcpy(graphWindow->windowName, windowName);
   graphWindow->isShowing = 0;
   graphWindow->nGraphsInList = 0;
   graphWindow->next = NULL;

   graphWindow->nRows = nRows;
   graphWindow->nColumns = nColumns;

   space = nRows * nColumns * sizeof(struct Graph *);
     /* printf("allocating graphList  %d\n", space); */

   graphWindow->graphList = malloc(space);

   if (graphWindow->graphList == NULL) {
	return(E_FAIL);
    }

   E_AddGraphWindow(graphWindow);

    /* E_PrintGraphWindow(graphWindow); printf("\n");  */

   return(E_SUCCESS);
}

/**************************
int e_GraphWindowSetLayout(windowName, nRows, nColumns)
   char *windowName;
   int nRows;
   int nColumns;
{
	struct GraphWindow *gw;
	struct GraphWindow *E_GetGraphWindow();

	gw = E_GetGraphWindow(windowName);

	if (!gw) {
		return(E_FAIL);
	}

	gw->nRows = nRows;
	gw->nColumns = nColumns;

	gw->graphList = malloc(nRows * nColumns * sizeof(struct GraphWindow *));

	if (gw->graphList == NULL) {
		return(E_FAIL);
	}
	else {
		return(E_SUCCESS);
	}
}
******************************/

/*********************************************************************************
 * B. Bariteau 7/14/08
 * This function is an alias for e_GraphWindowAddGraph, in order to create a
 * DATA_TABLE type graph by keeping Tables and Graphs separate in concept from the
 * user's perspective.
 *********************************************************************************/
int e_GraphWindowAddTable(char *windowName, char *tableName, int row, int column){
	int status;
	
	status = e_GraphWindowAddGraph(windowName, tableName, row, column);
	
	if(status == E_GRAPH_NOT_FOUND){
		status = E_TABLE_NOT_FOUND;
	}
	
	return(status);
}

int e_GraphWindowAddGraph(windowName, graphName, row, column)
   char *windowName;
   char *graphName;
   int   row;
   int   column;
{
	struct GraphWindow *gw;
	struct GraphWindow *E_GetGraphWindow();
	struct Graph *E_GetGraph();
   	struct Graph *graph;
	int i;

	   /* printf("GraphWindowAddGraph  %d %d\n", row, column); */

	gw = E_GetGraphWindow(windowName);
          /* E_PrintGraphWindow(gw); printf("\n");  */

	if (!gw) {
		return(E_FAIL);
	}

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_GRAPH_NOT_FOUND);
	}
/*
	   printf("  graph->name = %s\n", graph->name);
	   printf("  gw->graphList = %d\n", gw->graphList);
	   printf("  gw->nGraphsInList = %d\n", gw->nGraphsInList);

	for (i=0; i<gw->nGraphsInList; i++) {
		printf("graphList before:  %d\n", gw->graphList[i]);
	}
*/
	gw->type = graph->type;
	gw->graphList[gw->nGraphsInList] = graph;

	(gw->nGraphsInList)++;
/*
	for (i=0; i<gw->nGraphsInList; i++) {
		printf("graphList after:  %d\n", gw->graphList[i]);
	}
*/
	graph->row = row;
	graph->column = column;

          /* E_PrintGraphWindow(gw); printf("\n"); */
	return(E_SUCCESS);
}


int e_GraphWindowAddSurface(windowName, graphName, row, column)
   char *windowName;
   char *graphName;
   int   row;
   int   column;
{
	int status;

	status = e_GraphWindowAddGraph(windowName, graphName, row, column);
	return(status);
}

/*********************************************************************************
 * B. Bariteau 7/14/08
 * Added intialization of variables for a Table, including columns, toptext, and
 * bottomtext.
 *********************************************************************************/
int e_GraphCreate(name, type)
   char *name;
   int   type;
{
   struct Graph *graph;
   int i;
   int space;

   space = sizeof(struct Graph);
	  /* printf("e_GraphCreate  %s  %d\n", name, type); */

   graph = malloc(space);

   if (!graph) {
	return(E_FAIL);
   }
   
   space = strlen(name) + 1;

   graph->name = malloc(space);
   if (!(graph->name)) {
	return(E_FAIL);
   }

   strcpy(graph->name, name);
   graph->type = type;
   graph->nLabels = 0;
   graph->labelListSize = 0;
   graph->labelList = malloc(sizeof(struct Label *));
   graph->listSize = 10;
   graph->xRangeFlag = 0;
   graph->xRange[0] = 0.;
   graph->xRange[1] = 0.;
   graph->yRangeFlag = 0;
   graph->yRange[0] = 0.;
   graph->yRange[1] = 0.;
   graph->zRangeFlag = 0;
   graph->zRange[0] = 0.;
   graph->zRange[1] = 0.;
   graph->xGridFlag = 0;
   graph->yGridFlag = 0;
   graph->zGridFlag = 0;
   graph->xNumberStyle = E_LINEAR;
   graph->yNumberStyle = E_LINEAR;
   graph->zNumberStyle = E_LINEAR;
   graph->fxDatasetList = malloc(sizeof(struct FxDataset *) * graph->listSize);
   graph->columnList = malloc(sizeof(struct Column *) * graph->listSize);

   if (graph->fxDatasetList == NULL || graph->columnList == NULL) {
	printf("e_GraphCreate malloc failed\n");
	return(E_FAIL);
   }

   graph->nDatasets = 0;
   graph->nColumns = 0;

	 /* printf("e_GraphCreate type = %d\n",graph->type); */
   if (graph->type == FX) {
	graph->showLegend = 1;
   	graph->originX = .12;
   	graph->originY = .14;
   	graph->width = .66;
   	graph->height = .78;
   } else if (graph->type == FXT || graph->type == FXI) {
	graph->showLegend = 0;
   	graph->originX = .12;
   	graph->originY = .14;
   	graph->width = .84;
   	graph->height = .78;
   } else if (graph->type == SURFACE) {
	graph->showLegend = 0;
   	graph->originX = 0.;
   	graph->originY = 0.;
   	graph->width = 1.;
   	graph->height = 1.;
   } else if (graph->type == XY) {
	graph->showLegend = 0;
   	graph->originX = .12;
   	graph->originY = .14;
   	graph->width = .84;
   	graph->height = .78;
   } else if (graph->type == DATA_TABLE) {
   	graph->showLegend = 1;
   	graph->originX = 0.12;
   	graph->originY = 0.14;
   	graph->width = 0.66;
   	graph->height = 0.74;
   }

   graph->next = NULL;

   graph->topTextList = malloc(sizeof(struct Label *));
   graph->bottomTextList = malloc(sizeof(struct Label *));
   if(!(graph->topTextList) || !(graph->bottomTextList)){
	return E_ALLOCATE_FAIL;
   }

   graph->nTopText = 0;
   graph->nBottomText = 0;

   graph->xAxisLabel = malloc(sizeof(struct Label));
   graph->yAxisLabel = malloc(sizeof(struct Label));
   graph->titleLabel = malloc(sizeof(struct Label));
   graph->shortTitle = malloc(sizeof(char *) * 10);
   strcpy(graph->shortTitle, "");
   graph->indexLabel = malloc(sizeof(struct Label));
   graph->legend = malloc(sizeof(struct Legend));
   graph->legend->title = malloc(sizeof(char *) * 10);

   if (graph->legend->title == NULL) {
	printf("e_GraphCreate legend malloc failed\n");
	return(E_FAIL);
   }
	/* printf("e_GraphCreate legend malloc %d\n", graph->legend->title); */

   graph->xAxisLabel->text = "";
   graph->xAxisLabel->x = .2;
   graph->xAxisLabel->y = .074;
   graph->xAxisLabel->height = .03;
   graph->xAxisLabel->fontName = "Serif";
   graph->xAxisLabel->fontStyle = "Bold";
   graph->xAxisLabel->fontColor = "name: black";
   graph->xAxisLabel->bgColor = "";
   graph->xAxisLabel->rotation = 0.;

   graph->yAxisLabel->text = "";
   graph->yAxisLabel->x = .04;
   graph->yAxisLabel->y = .2;
   graph->yAxisLabel->height = .03;
   graph->yAxisLabel->fontName = "Serif";
   graph->yAxisLabel->fontStyle = "Bold";
   graph->yAxisLabel->fontColor = "name: black";
   graph->yAxisLabel->bgColor = "";
   graph->yAxisLabel->rotation = -1.570796326794897;

   graph->titleLabel->text = "";
   graph->titleLabel->x = .5;
   graph->titleLabel->y = .05;
   graph->titleLabel->height = .04;
   graph->titleLabel->fontName = "Serif";
   graph->titleLabel->fontStyle = "Bold";
   graph->titleLabel->fontColor = "rgb: 0.0 1.0 0.0";
   graph->titleLabel->bgColor = "";
   graph->titleLabel->rotation = 0.;

   graph->indexLabel->text = "";
   graph->indexLabel->x = .14;
   graph->indexLabel->y = .94;
   graph->indexLabel->height = .03;
   graph->indexLabel->fontName = "Serif";
   graph->indexLabel->fontStyle = "Bold";
   graph->indexLabel->fontColor = "name: black";
   graph->indexLabel->bgColor = "";
   graph->indexLabel->rotation = 0.;

   graph->legend->nTitles = 0;
	/* printf("GraphCreate %d\n", graph->legend); */
	/* printf("GraphCreate %d\n", graph->legend->nTitles); */

     /* printf("GraphCreate name = %d %s\n", graph, graph->name); */
   E_AddGraph(graph);

   return(E_SUCCESS);
}

/*********************************************************************************
 * B. Bariteau 7/14/08
 * This function sets the background color for the cells in a column.
 *********************************************************************************/
int e_ColumnSetBGColor(char *colName, char *color){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);
	if(!col){
		return(E_FAIL);
	}

	col->bgcolor = malloc(sizeof(char) * (strlen(color) + 1));
	if(!(col->bgcolor)){
		return E_ALLOCATE_FAIL;
	}

	strcpy(col->bgcolor, color);

	return(E_SUCCESS);
}

int e_ColumnSetFontColor(char *colName, char *color){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);
	if(!col){
		return(E_FAIL);
	}

	col->fontColor = malloc(sizeof(char) * (strlen(color) + 1));
	if(!(col->fontColor)){
		return E_ALLOCATE_FAIL;
	}

	strcpy(col->fontColor, color);

	return(E_SUCCESS);
}

int *E_ColorParse(char *text){
	int *out;
	int red, green, blue, i, temp;
	char *parse;

	parse = malloc(sizeof(char) * 3);

	out = malloc(sizeof(int) * 3);

	if(text[0] == '#'){
		parse[0] = text[1];
		parse[1] = text[2];
		parse[2] = '\n';
		temp = (int) strtol(parse, NULL, 16);
		if(temp == 0){
			out[0] = -1;
			out[1] = -1;
			out[2] = -1;
			return out;
		}
		out[0] = temp;

		parse[0] = text[3];
		parse[1] = text[4];
		parse[2] = '\n';
		temp = (int) strtol(parse, NULL, 16);
		if(temp == 0){
			out[0] = -1;
			out[1] = -1;
			out[2] = -1;
			return out;
		}
		out[1] = temp;

		parse[0] = text[5];
		parse[1] = text[6];
		parse[2] = '\n';
		temp = (int) strtol(parse, NULL, 16);
		if(temp == 0){
			out[0] = -1;
			out[1] = -1;
			out[2] = -1;
			return out;
		}
		out[2] = temp;
	}else if(text[0] == 'r' && text[1] == 'g' & text[2] == 'b'){
		i = 0;
		for(parse = strtok(text, "(), rgb"); parse != NULL; parse = strtok(NULL, "(), rgb"), i++){
			if(strcmp(parse, "0") == 0){
				out[i] = 0;
				continue;
			}
			temp = (int) strtol(parse, NULL, 10);
			if(temp == 0){
				out[0] = -1;
				out[1] = -1;
				out[2] = -1;
				return out;
			}
			out[i] = temp;
		}
	}else{
		if(strcasecmp(text, "white") == 0){
			out = E_ColorParse("#FFFFFF");
		}else if(strcasecmp(text, "black") == 0){
			out = E_ColorParse("#000000");
		}else if(strcasecmp(text, "aliceblue") == 0){
			out = E_ColorParse("#F0F8FF");
		}else if(strcasecmp(text, "antiquewhite") == 0){
			out = E_ColorParse("#FAEBD7");
		}else if(strcasecmp(text, "aquamarine") == 0){
			out = E_ColorParse("#7FFFD4");
		}else if(strcasecmp(text, "azure") == 0){
			out = E_ColorParse("#F0FFFF");
		}else if(strcasecmp(text, "beige") == 0){
			out = E_ColorParse("#F5F5DC");
		}else if(strcasecmp(text, "aqua") == 0){
			out = E_ColorParse("#00FFFF");
		}else if(strcasecmp(text, "bisque") == 0){
			out = E_ColorParse("#FFE4C4");
		}else if(strcasecmp(text, "blanchedalmond") == 0){
			out = E_ColorParse("#FFEBCD");
		}else if(strcasecmp(text, "blue") == 0){
			out = E_ColorParse("#0000FF");
		}else if(strcasecmp(text, "blueviolet") == 0){
			out = E_ColorParse("#8A2BE2");
		}else if(strcasecmp(text, "brown") == 0){
			out = E_ColorParse("#A52A2A");
		}else if(strcasecmp(text, "burlywood") == 0){
			out = E_ColorParse("#DEB887");
		}else if(strcasecmp(text, "cadetblue") == 0){
			out = E_ColorParse("#5F9EA0");
		}else if(strcasecmp(text, "chartreuse") == 0){
			out = E_ColorParse("#7FFF00");
		}else if(strcasecmp(text, "chocolate") == 0){
			out = E_ColorParse("#D2691E");
		}else if(strcasecmp(text, "coral") == 0){
			out = E_ColorParse("#FF7F50");
		}else if(strcasecmp(text, "cornflowerblue") == 0){
			out = E_ColorParse("#6495ED");
		}else if(strcasecmp(text, "cornsilk") == 0){
			out = E_ColorParse("#FFF8DC");
		}else if(strcasecmp(text, "crimson") == 0){
			out = E_ColorParse("#DC143C");
		}else if(strcasecmp(text, "cyan") == 0){
			out = E_ColorParse("#00FFFF");
		}else if(strcasecmp(text, "darkblue") == 0){
			out = E_ColorParse("#00008B");
		}else if(strcasecmp(text, "darkcyan") == 0){
			out = E_ColorParse("#008B8B");
		}else if(strcasecmp(text, "darkgoldenrod") == 0){
			out = E_ColorParse("#B8860B");
		}else if(strcasecmp(text, "darkgray") == 0 || strcasecmp(text, "darkgrey") == 0){
			out = E_ColorParse("#A9A9A9");
		}else if(strcasecmp(text, "darkgreen") == 0){
			out = E_ColorParse("#006400");
		}else if(strcasecmp(text, "darkkhaki") == 0){
			out = E_ColorParse("#BDB76B");
		}else if(strcasecmp(text, "darkmagenta") == 0){
			out = E_ColorParse("#8B008B");
		}else if(strcasecmp(text, "darkolivegreen") == 0){
			out = E_ColorParse("#556B2F");
		}else if(strcasecmp(text, "darkorange") == 0){
			out = E_ColorParse("FF8C00");
		}else if(strcasecmp(text, "darkorchid") == 0){
			out = E_ColorParse("#9932CC");
		}else if(strcasecmp(text, "darkred") == 0){
			out = E_ColorParse("#8B0000");
		}else if(strcasecmp(text, "darksalmon") == 0){
			out = E_ColorParse("#E9967A");
		}else if(strcasecmp(text, "darkseagreen") == 0){
			out = E_ColorParse("#8FBC8F");
		}else if(strcasecmp(text, "darkslateblue") == 0){
			out = E_ColorParse("#483B8B");
		}else if(strcasecmp(text, "darkslategray") == 0 || strcasecmp(text, "darkslategrey") == 0){
			out = E_ColorParse("#2F4F4F");
		}else if(strcasecmp(text, "darkturquoise") == 0){
			out = E_ColorParse("#00CED1");
		}else if(strcasecmp(text, "darkviolet") == 0){
			out = E_ColorParse("#9400D3");
		}else if(strcasecmp(text, "deeppink") == 0){
			out = E_ColorParse("#FF1493");
		}else if(strcasecmp(text, "deepskyblue") == 0){
			out = E_ColorParse("#00BFFF");
		}else if(strcasecmp(text, "dimgray") == 0 || strcasecmp(text, "dimgrey") == 0){
			out = E_ColorParse("#696969");
		}else if(strcasecmp(text, "1E90FF") == 0){
			out = E_ColorParse("#00BFFF");
		}else if(strcasecmp(text, "firebrick") == 0){
			out = E_ColorParse("#B22222");
		}else if(strcasecmp(text, "floralwhite") == 0){
			out = E_ColorParse("#FFFAF0");
		}else if(strcasecmp(text, "forestgreen") == 0){
			out = E_ColorParse("#228B22");
		}else if(strcasecmp(text, "fuchsia") == 0){
			out = E_ColorParse("#FF00FF");
		}else if(strcasecmp(text, "gainsboro") == 0){
			out = E_ColorParse("#DCDCDC");
		}else if(strcasecmp(text, "ghostwhite") == 0){
			out = E_ColorParse("#F8F8FF");
		}else if(strcasecmp(text, "gold") == 0){
			out = E_ColorParse("#FFD700");
		}else if(strcasecmp(text, "goldenrod") == 0){
			out = E_ColorParse("#DAA520");
		}else if(strcasecmp(text, "gray") == 0 || strcasecmp(text, "grey") == 0){
			out = E_ColorParse("#808080");
		}else if(strcasecmp(text, "green") == 0){
			out = E_ColorParse("#008000");
		}else if(strcasecmp(text, "greenyellow") == 0){
			out = E_ColorParse("#ADFF2F");
		}else if(strcasecmp(text, "honeydew") == 0){
			out = E_ColorParse("#F0FFF0");
		}else if(strcasecmp(text, "hotpink") == 0){
			out = E_ColorParse("#FF69B4");
		}else if(strcasecmp(text, "indianred") == 0){
			out = E_ColorParse("#CD5C5C");
		}else if(strcasecmp(text, "indigo") == 0){
			out = E_ColorParse("#4B0082");
		}else if(strcasecmp(text, "ivory") == 0){
			out = E_ColorParse("#FFFFF0");
		}else if(strcasecmp(text, "khaki") == 0){
			out = E_ColorParse("#F0E68C");
		}else if(strcasecmp(text, "lavender") == 0){
			out = E_ColorParse("#E6E6FA");
		}else if(strcasecmp(text, "lavenderblush") == 0){
			out = E_ColorParse("#FFF0F5");
		}else if(strcasecmp(text, "lawngreen") == 0){
			out = E_ColorParse("#7CFC00");
		}else if(strcasecmp(text, "lemonchiffon") == 0){
			out = E_ColorParse("#FFFACD");
		}else if(strcasecmp(text, "lightblue") == 0){
			out = E_ColorParse("#ADD8E6");
		}else if(strcasecmp(text, "lightcoral") == 0){
			out = E_ColorParse("#F08080");
		}else if(strcasecmp(text, "lightcyan") == 0){
			out = E_ColorParse("#E0FFFF");
		}else if(strcasecmp(text, "lightgoldenrodyellow") == 0){
			out = E_ColorParse("#FAFAD2");
		}else if(strcasecmp(text, "lightgray") == 0 || strcasecmp(text, "lightgrey") == 0){
			out = E_ColorParse("#D3D3D3");
		}else if(strcasecmp(text, "lightgreen") == 0){
			out = E_ColorParse("#90EE90");
		}else if(strcasecmp(text, "lightpink") == 0){
			out = E_ColorParse("#FFB6C1");
		}else if(strcasecmp(text, "lightsalmon") == 0){
			out = E_ColorParse("#FFA07A");
		}else if(strcasecmp(text, "lightseagreen") == 0){
			out = E_ColorParse("#20B2AA");
		}else if(strcasecmp(text, "lightskyblue") == 0){
			out = E_ColorParse("#87CEFA");
		}else if(strcasecmp(text, "lightslategray") == 0 || strcasecmp(text, "lightslategrey") == 0){
			out = E_ColorParse("#778899");
		}else if(strcasecmp(text, "lightsteelblue") == 0){
			out = E_ColorParse("#B0C4DE");
		}else if(strcasecmp(text, "lightyellow") == 0){
			out = E_ColorParse("#FFFFE0");
		}else if(strcasecmp(text, "lime") == 0){
			out = E_ColorParse("00FF00");
		}else if(strcasecmp(text, "limegreen") == 0){
			out = E_ColorParse("#32CD32");
		}else if(strcasecmp(text, "linen") == 0){
			out = E_ColorParse("#FAF0E6");
		}else if(strcasecmp(text, "magenta") == 0){
			out = E_ColorParse("#FF00FF");
		}else if(strcasecmp(text, "maroon") == 0){
			out = E_ColorParse("#800000");
		}else if(strcasecmp(text, "mediumaquamarine") == 0){
			out = E_ColorParse("#66CDAA");
		}else if(strcasecmp(text, "mediumblue") == 0){
			out = E_ColorParse("#0000CD");
		}else if(strcasecmp(text, "mediumorchid") == 0){
			out = E_ColorParse("#BA55D3");
		}else if(strcasecmp(text, "mediumpurple") == 0){
			out = E_ColorParse("#9370D8");
		}else if(strcasecmp(text, "mediumseagreen") == 0){
			out = E_ColorParse("#3CB371");
		}else if(strcasecmp(text, "mediumslateblue") == 0){
			out = E_ColorParse("#7B68EE");
		}else if(strcasecmp(text, "mediumspringreen") == 0){
			out = E_ColorParse("#00FA9A");
		}else if(strcasecmp(text, "mediumturquoise") == 0){
			out = E_ColorParse("#48D1CC");
		}else if(strcasecmp(text, "mediumvioletred") == 0){
			out = E_ColorParse("#C71585");
		}else if(strcasecmp(text, "midnightblue") == 0){
			out = E_ColorParse("#191970");
		}else if(strcasecmp(text, "mintcream") == 0){
			out = E_ColorParse("#F5FFFA");
		}else if(strcasecmp(text, "mistyrose") == 0){
			out = E_ColorParse("#FFE4E1");
		}else if(strcasecmp(text, "moccasin") == 0){
			out = E_ColorParse("#FFE4B5");
		}else if(strcasecmp(text, "navajowhite") == 0){
			out = E_ColorParse("#FFDEAD");
		}else if(strcasecmp(text, "navy") == 0){
			out = E_ColorParse("#000080");
		}else if(strcasecmp(text, "oldlace") == 0){
			out = E_ColorParse("#FDF5E6");
		}else if(strcasecmp(text, "olive") == 0){
			out = E_ColorParse("#808000");
		}else if(strcasecmp(text, "olivedrab") == 0){
			out = E_ColorParse("#6B8E23");
		}else if(strcasecmp(text, "orange") == 0){
			out = E_ColorParse("#FFA500");
		}else if(strcasecmp(text, "orangered") == 0){
			out = E_ColorParse("#FF4500");
		}else if(strcasecmp(text, "orchid") == 0){
			out = E_ColorParse("#DA70D6");
		}else if(strcasecmp(text, "palegoldenrod") == 0){
			out = E_ColorParse("#EEE8AA");
		}else if(strcasecmp(text, "palegreen") == 0){
			out = E_ColorParse("#98FB98");
		}else if(strcasecmp(text, "paleturquoise") == 0){
			out = E_ColorParse("#AFEEEE");
		}else if(strcasecmp(text, "palevioletred") == 0){
			out = E_ColorParse("#D87093");
		}else if(strcasecmp(text, "papayawhip") == 0){
			out = E_ColorParse("#FFEFD5");
		}else if(strcasecmp(text, "peachpuff") == 0){
			out = E_ColorParse("#FFDAB9");
		}else if(strcasecmp(text, "peru") == 0){
			out = E_ColorParse("#CD853F");
		}else if(strcasecmp(text, "pink") == 0){
			out = E_ColorParse("#FFC0CB");
		}else if(strcasecmp(text, "plum") == 0){
			out = E_ColorParse("#DDA0DD");
		}else if(strcasecmp(text, "powderblue") == 0){
			out = E_ColorParse("#B0E0E6");
		}else if(strcasecmp(text, "purple") == 0){
			out = E_ColorParse("#800080");
		}else if(strcasecmp(text, "red") == 0){
			out = E_ColorParse("#FF0000");
		}else if(strcasecmp(text, "rosybrown") == 0){
			out = E_ColorParse("#BC8F8F");
		}else if(strcasecmp(text, "royalblue") == 0){
			out = E_ColorParse("#4169E1");
		}else if(strcasecmp(text, "saddlebrown") == 0){
			out = E_ColorParse("#8B4513");
		}else if(strcasecmp(text, "salmon") == 0){
			out = E_ColorParse("#FA8072");
		}else if(strcasecmp(text, "sandybrown") == 0){
			out = E_ColorParse("#F4A460");
		}else if(strcasecmp(text, "seagreen") == 0){
			out = E_ColorParse("#2E8B57");
		}else if(strcasecmp(text, "seashell") == 0){
			out = E_ColorParse("#FFF5EE");
		}else if(strcasecmp(text, "sienna") == 0){
			out = E_ColorParse("#A0522D");
		}else if(strcasecmp(text, "silver") == 0){
			out = E_ColorParse("#C0C0C0");
		}else if(strcasecmp(text, "skyblue") == 0){
			out = E_ColorParse("#87CEEB");
		}else if(strcasecmp(text, "slateblue") == 0){
			out = E_ColorParse("#6A5ACD");
		}else if(strcasecmp(text, "slategray") == 0 || strcasecmp(text, "slategrey") == 0){
			out = E_ColorParse("#708090");
		}else if(strcasecmp(text, "snow") == 0){
			out = E_ColorParse("#FFFAFA");
		}else if(strcasecmp(text, "springgreen") == 0){
			out = E_ColorParse("#00FF7F");
		}else if(strcasecmp(text, "steelblue") == 0){
			out = E_ColorParse("#4682B4");
		}else if(strcasecmp(text, "tan") == 0){
			out = E_ColorParse("#D2B48C");
		}else if(strcasecmp(text, "teal") == 0){
			out = E_ColorParse("#008080");
		}else if(strcasecmp(text, "thistle") == 0){
			out = E_ColorParse("#D8BFD8");
		}else if(strcasecmp(text, "tomato") == 0){
			out = E_ColorParse("#FF6347");
		}else if(strcasecmp(text, "turquoise") == 0){
			out = E_ColorParse("#40E0D0");
		}else if(strcasecmp(text, "violet") == 0){
			out = E_ColorParse("#EE82EE");
		}else if(strcasecmp(text, "wheat") == 0){
			out = E_ColorParse("#F5DEB3");
		}else if(strcasecmp(text, "whitesmoke") == 0){
			out = E_ColorParse("#F5F5F5");
		}else if(strcasecmp(text, "yellow") == 0){
			out = E_ColorParse("#FFFF00");
		}else if(strcasecmp(text, "yellowgreen") == 0){
			out = E_ColorParse("#9ACD32");
		}else{
			out[0] = -1;
			out[1] = -1;
			out[2] = -1;
		}
	}

	return out;
}

int e_TableCreate(char *name){
	int status;

	status = e_GraphCreate(name, E_DATA_TABLE);

	return(status);
}

/****************************
int e_GraphSetLocation(graphName, row, column)
   char *graphName;
   int row;
   int column;
{
	struct Graph *graph;
	struct Graph *E_GetGraph();

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	graph->row = row;
	graph->column = column;
	return(E_SUCCESS);
}
*****************************/

/*****************************************************
 * B.Bariteau - 4/1/08 - This function gets an EML file
 * that was printed and sends it to an ElVis server.
 *****************************************************/
int e_SendFile(char *filename){
        FILE* fd;
	char *fileOld;
	int status = 0, i, j = 0, sockfd, k, need_init;
	char c;
	char s[1000];
	int firstline = 0, cmp;

	fd = fopen(filename, "r");
	if(fd == NULL){
		printf("File %s could not be opened.\n", filename);
		return(E_FAIL);
	}

	for(i = 0; i < 1000; i++){
	  s[i] = '\0';
	}

	for(i = 0; i < numpaths; i++){
		if(serverList[i] != '\0'){
		        need_init = 1;
		}else{
		        continue;
		}

		status = fscanf(fd, "%c", &c);
		while(status != EOF){
		        if(c == '\n'){
				s[j] = '\0';
				if(need_init == 1){
                  			sockfd = e_socket_initialize(i);
					need_init = 0;
				}
				write_line(sockfd, s);

                                /* if at end of EML block, close socket. */
				/* it will be reopened if another follows. */

				cmp = strcmp(s,"</visualstate>\n");
				if(cmp == 0){
				        e_close(sockfd);
					need_init = 1;
				}

				for(k = 0; k <= j; k++){
					s[k] = '\0';
				}
				j = 0;
				status = fscanf(fd, "%c", &c);
				if(status == EOF){continue;}
			}

			s[j] = c;
			j++;

			status = fscanf(fd, "%c", &c);
		}
		e_close(sockfd);
		rewind(fd);
	}
	fclose(fd);
	return(E_SUCCESS);
}

int e_GraphAddLabel(graphName, inText, location, font, style, h, c)
   char *graphName;
   char *inText;
   float location[];
   char *font;
   char *style;
   float h;
   char *c;
{
	struct Label *label;
	int i;
	void E_AddLabel();
	struct Graph *E_GetGraph();
	struct Graph *graph;
/*
   printf("e_GraphAddLabel\n");
   printf(" %s %s %s %s\n", graphName, inText, font, style);
   printf(" %d %d\n", strlen(font), strlen(style));
   printf(" %f %f\n", location[0], location[1]);
   printf(" %f\n", h);
   printf(" %f %f %f\n", c[0], c[1], c[2]);

   printf(" %d, %d %d %d\n", sizeof(h), sizeof(c[0]), sizeof(c[1]), sizeof(c[2]));
*/
	label = malloc(sizeof(struct Label));

	if (!label) {
		return(E_FAIL);
	}

	label->text = malloc(strlen(inText) + 1);	/*  add 1 for null terminator */
	if (!(label->text)) {
		return(E_FAIL);
	}

	strcpy(label->text, inText);

	label->x = location[0];
	label->y = location[1];
	label->rotation = 0.;

	label->fontName = malloc(strlen(font) + 1);
	if (!(label->fontName)) {
		return(E_FAIL);
	}

	strcpy(label->fontName, font);

	label->fontStyle = malloc(strlen(style) + 1);
	if (!(label->fontStyle)) {
		return(E_FAIL);
	}

	strcpy(label->fontStyle, style);

	label->height = h;

	label->fontColor = malloc(sizeof(char *) * (strlen(c) + 1));
	if(!(label->fontColor)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(label->fontColor, c);

	label->next = NULL;

	E_AddLabel(label);

	graph = E_GetGraph(graphName);

	if(!graph){
		return(E_FAIL);
   	}

   	if (graph->labelListSize <= graph->nLabels) {
		graph->labelListSize += 10;

		graph->labelList = realloc(graph->labelList, sizeof(struct Label *) * graph->labelListSize);

		if (graph->labelList == NULL) {
			return(E_FAIL);
		}
	}

	graph->labelList[graph->nLabels] = label;
	graph->nLabels++;

	return(E_SUCCESS);
}

int e_TableAddTopText(char *tableName, char *text, char *font, char *style, int fontSize, char *color, char *bgcolor){
	struct Graph *table;
	struct Graph *E_GetGraph();
	struct Label *ttext;
	void E_AddLabel();

	table = E_GetGraph(tableName);
	if(!table || table->type != DATA_TABLE){
		return E_TABLE_NOT_FOUND;
	}

	table->topTextList = realloc(table->topTextList, (sizeof(struct Label *) * (table->nTopText + 1)));
	ttext = malloc(sizeof(struct Label));
	if(!(table->topTextList) || !(ttext)){
		return E_ALLOCATE_FAIL;
	}

	ttext->text = malloc(sizeof(char) * (strlen(text) + 1));
	if(!(ttext->text)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(ttext->text, text);

	ttext->fontName = malloc(sizeof(char) * (strlen(font) + 1));
	if(!(ttext->fontName)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(ttext->fontName, font);

	ttext->fontStyle = malloc(sizeof(char) * (strlen(style) + 1));
	if(!(ttext->fontStyle)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(ttext->fontStyle, style);

	ttext->fontColor = malloc(sizeof(char) * (strlen(color) + 1));
	if(!(ttext->fontColor)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(ttext->fontColor, color);

	ttext->bgColor = malloc(sizeof(char) * (strlen(bgcolor) + 1));
	if(!(ttext->bgColor)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(ttext->bgColor, bgcolor);

	ttext->fontSize = fontSize;

	ttext->next = NULL;

	table->topTextList[table->nTopText] = ttext;
	table->nTopText++;

	E_AddLabel(ttext);

	return E_SUCCESS;
}

int e_TableAddBottomText(char *tableName, char *text, char *font, char *style, int fontSize, char *color, char *bgcolor){
	struct Graph *table;
	struct Graph *E_GetGraph();
	struct Label *btext;
	void E_AddLabel();

	table = E_GetGraph(tableName);
	if(!table || table->type != DATA_TABLE){
		return E_TABLE_NOT_FOUND;
	}

	table->bottomTextList = realloc(table->bottomTextList, (sizeof(struct Label *) * (table->nBottomText + 1)));
	btext = malloc(sizeof(struct Label));
	if(!(table->bottomTextList) || !(btext)){
		return E_ALLOCATE_FAIL;
	}

	btext->text = malloc(sizeof(char) * (strlen(text) + 1));
	if(!(btext->text)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(btext->text, text);

	btext->fontName = malloc(sizeof(char) * (strlen(font) + 1));
	if(!(btext->fontName)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(btext->fontName, font);

	btext->fontStyle = malloc(sizeof(char) * (strlen(style) + 1));
	if(!(btext->fontStyle)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(btext->fontStyle, style);

	btext->fontColor = malloc(sizeof(char) * (strlen(color) + 1));
	if(!(btext->fontColor)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(btext->fontColor, color);

	btext->bgColor = malloc(sizeof(char) * (strlen(bgcolor) + 1));
	if(!(btext->bgColor)){
		return E_ALLOCATE_FAIL;
	}
	strcpy(btext->bgColor, bgcolor);

	btext->fontSize = fontSize;

	btext->next = NULL;

	table->bottomTextList[table->nBottomText] = btext;
	table->nBottomText++;

	E_AddLabel(btext);

	return E_SUCCESS;
}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Adds a column to a table.
 ********************************************************************************/
int e_TableAddColumn(char *tableName, char *colName){
	struct Graph *table;
	struct Column *col;
	struct Graph *E_GetGraph();
	struct Column *E_GetColumn();

	table = E_GetGraph(tableName);
	col = E_GetColumn(colName);

	if(!table || !col){
		return(E_FAIL);
	}
	
	if(table->listSize <= table->nColumns){
		table->listSize += 10;
		
		table->columnList = realloc(table->columnList, sizeof(struct Column *) * table->listSize);
		
		if(table->columnList == NULL){
			return(E_FAIL);
		}
	}

	table->columnList[table->nColumns] = col;
	table->nColumns++;
	
	return(E_SUCCESS);
}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Adds at column to a table using the column's ID.
 ********************************************************************************/
int e_TableAddColumnID(char *tableName, int id){
	struct Graph *table;
	struct Column *col;
	struct Graph *E_GetGraph();
	struct Column *E_GetColumnID();
	
	table = E_GetGraph(tableName);
	col = E_GetColumnID(id);
	
	if(!table || !col){
		return(E_FAIL);
	}
	
	if(table->listSize <= table->nColumns){
		table->listSize += 10;
		
		table->columnList = realloc(table->columnList, sizeof(struct Column *) * table->listSize);
		
		if(table->columnList == NULL){
			return(E_FAIL);
		}
	}
	
	table->columnList[table->nColumns] = col;
	table->nColumns;
	
	return(E_SUCCESS);
}

int e_GraphAddFxDataset(graphName, datasetName)
   char *graphName;
   char *datasetName;
{
	struct Graph *E_GetGraph();
   	struct Graph *graph;
	struct FxDataset *dataset;
	struct FxDataset *E_GetFxDataset();
	int i;

	  /* printf("e_GraphAddFxDataset\n"); */

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	dataset = E_GetFxDataset(datasetName);

	if (!dataset) {
		return(E_FAIL);
	}

	if (graph->listSize <= graph->nDatasets) {
		graph->listSize += 10;

		graph->fxDatasetList = realloc(graph->fxDatasetList, sizeof(struct FxDataset *) * graph->listSize);

		if (graph->fxDatasetList == NULL) {
			printf("realloc failed\n");
			return(E_FAIL);
		}

		/* printf("   listSize = %d\n",graph->listSize); */
	}

	graph->fxDatasetList[graph->nDatasets] = dataset;
	graph->nDatasets++;
/*
	printf("   e_GraphAddFxDataset:  nDatasets = %d\n",graph->nDatasets);

	for (i=0; i<graph->nDatasets; i++) {
		printf("   fxDatasetList[%d] = %d\n",i, graph->fxDatasetList[i]);
	}
*/
	/* E_PrintFxDatasets(); printf("\n"); */

	return(E_SUCCESS);
}


int e_GraphAddFxDatasetID(graphName, id)
   char *graphName;
   int  id;
{
	struct Graph *E_GetGraph();
   	struct Graph *graph;
	struct FxDataset *dataset;
	struct FxDataset *E_GetFxDataset();
	int i;

	   /* printf("e_GraphAddFxDatasetID\n"); */

	graph = E_GetGraph(graphName);

	if (!graph) {
	   	  printf("!graph\n");
		return(E_FAIL);
	}

	dataset = E_GetFxDatasetID(id);

	if (!dataset) {
	   	  printf("!dataset\n");
		return(E_FAIL);
	}

	if (graph->listSize <= graph->nDatasets) {
		graph->listSize += 10;

		graph->fxDatasetList = realloc(graph->fxDatasetList, sizeof(struct FxDataset *) * graph->listSize);

		if (graph->fxDatasetList == NULL) {
			printf("realloc failed\n");
			return(E_FAIL);
		}

		/* printf("   listSize = %d\n",graph->listSize); */
	}
	
	graph->fxDatasetList[graph->nDatasets] = dataset;
	graph->nDatasets++;

	  /* printf("   e_GraphAddFxDatasetID:  nDatasets = %d\n",graph->nDatasets); */
/*
	for (i=0; i<graph->nDatasets; i++) {
		printf("   fxDatasetList[%d] = %d\n",i, graph->fxDatasetList[i]);
	}
*/
	/* E_PrintFxDatasets(); printf("\n"); */

	return(E_SUCCESS);
}

int e_ShowLines(datasetName, show)
   char *datasetName;
   int show;
{
        struct FxDataset *dataset;
        struct FxDataset *E_GetFxDataset();
                                                                                                
        dataset = E_GetFxDataset(datasetName);
                                                                                                
        if (!dataset) {
                return(E_FAIL);
        }
                                                                                                
        if (show == 1) {
                dataset->showLine = -1;
        } else {
                dataset->showLine = -2;
        }
                                                                                            
        return(E_SUCCESS);
}

int e_ShowMarkers(datasetName, interval)
   char *datasetName;
   int interval;
{
        struct FxDataset *dataset;
        struct FxDataset *E_GetFxDataset();
                                                                                                
        dataset = E_GetFxDataset(datasetName);
                                                                                                
        if (!dataset) {
                return(E_FAIL);
        }
                                                                                                
          /* interval:  0 = don't show;  1 = show all;  >=2 means show every nth marker
*/
        dataset->showMarker = interval;
                                                                                                
        return(E_SUCCESS);
}


int e_GraphAddFxy(graphName, datasetName)
   char *graphName;
   char *datasetName;
{
	struct Graph *E_GetGraph();
   	struct Graph *graph;
	struct FxyDataset *dataset;
	struct FxyDataset *E_GetFxyDataset();
	int i;

	/* printf("e_GraphAddFxDataset\n"); */

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	dataset = E_GetFxyDataset(datasetName);

	if (!dataset) {
		return(E_FAIL);
	}

	graph->fxy = dataset;
/*getenv("ELVIS_PORT")
	if (graph->listSize <= graph->nDatasets) {
		graph->listSize += 10;

		graph->fxDatasetList = realloc(graph->fxDatasetList, sizeof(struct FxDataset *) * graph->listSize);

		if (graph->fxDatasetList == NULL) {
			printf("realloc failed\n");
			return(E_FAIL);
		}
	}

	graph->fxDatasetList[graph->nDatasets] = dataset;
	graph->nDatasets++;
*/
/*
	printf("   e_GraphAddFxDataset:  nDatasets = %d\n",graph->nDatasets);
	for (i=0; i<graph->nDatasets; i++) {
		printf("   fxDatasetList[%d] = %d\n",i, graph->fxDatasetList[i]);
	}
*/
	/* E_PrintFxDatasets(); printf("\n"); */

	return(E_SUCCESS);
}

int e_GraphSetXLabel(graphName, label)
   char *graphName;
   char *label;
{
	struct Graph *E_GetGraph();
   	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	graph->xAxisLabel->text = malloc(strlen(label) + 1);
	strcpy(graph->xAxisLabel->text, label);

	return(E_SUCCESS);
}


int e_GraphSetYLabel(graphName, label)
   char *graphName;
   char *label;
{
	struct Graph *E_GetGraph();
   	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	graph->yAxisLabel->text = malloc(strlen(label) + 1);
	strcpy(graph->yAxisLabel->text, label);

	return(E_SUCCESS);

}

int e_GraphSetXAxis(graphName, loglin)
   char *graphName;
   int loglin;
{
        struct Graph *E_GetGraph();
        struct Graph *graph;
                                                                                                
        graph = E_GetGraph(graphName);
                                                                                                
        if (!graph) {
                return(E_FAIL);
        }
                                                                                                
        graph->xNumberStyle = loglin;
                                                                                                
        return(E_SUCCESS);
}

                                                                                                
int e_GraphSetYAxis(graphName, loglin)
   char *graphName;
   int loglin;
{
        struct Graph *E_GetGraph();
        struct Graph *graph;
                                                                                                
        graph = E_GetGraph(graphName);
                                                                                                
        if (!graph) {
                return(E_FAIL);
        }
                                                                                                
        graph->yNumberStyle = loglin;
                                                                                                
        return(E_SUCCESS);
}

int e_GraphSetZAxis(char *graphName, int loglin){
	struct Graph *E_GetGraph();
	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if(!graph){
		return E_SURFACE_NOT_FOUND;
	}else if(graph->type != SURFACE){
		return E_SURFACE_NOT_FOUND;
	}

	graph->zNumberStyle = loglin;

	return E_SUCCESS;
}

int e_GraphSetXRange(graphName, xmin, xmax)
   char *graphName;
   double xmin, xmax;
{
	struct Graph *E_GetGraph();
	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	graph->xRange[0] = xmin;
	graph->xRange[1] = xmax;
	graph->xRangeFlag = 1;

	return(E_SUCCESS);
}
                                                                                              

int e_GraphSetYRange(graphName, ymin, ymax)
   char *graphName;
   double ymin, ymax;
{
        struct Graph *E_GetGraph();
        struct Graph *graph;
                                                                                                
        graph = E_GetGraph(graphName);
                                                                                                
        if (!graph) {
                return(E_FAIL);
        }
                                                                                                
        graph->yRange[0] = ymin;
        graph->yRange[1] = ymax;
	graph->yRangeFlag = 1;
                                                                                                
        return(E_SUCCESS);
}

int e_GraphSetXGrid(char *graphName, int grid){
	struct Graph *E_GetGraph();
	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if(!graph){
		return(E_GRAPH_NOT_FOUND);
	}

	graph->xGridFlag = grid;

	return(E_SUCCESS);
}

int e_GraphSetYGrid(char *graphName, int grid){
	struct Graph *E_GetGraph();
	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if(!graph){
		return(E_GRAPH_NOT_FOUND);
	}

	graph->yGridFlag = grid;

	return(E_SUCCESS);
}

int e_GraphSetTitle(graphName, title, shortTitle)
   char *graphName;
   char *title;
   char *shortTitle;
{
	struct Graph *E_GetGraph();
   	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	graph->titleLabel->text = malloc(strlen(title) + 1);
	strcpy(graph->titleLabel->text, title);

	graph->shortTitle = malloc(strlen(shortTitle) + 1);
	strcpy(graph->shortTitle, shortTitle);
	
	return(E_SUCCESS);

}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Sets the header of the column to different text than the column's name. By
 * default, it will be the Column's name.
 ********************************************************************************/
int e_ColumnSetHeader(char *colName, char *header){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);

	if(!col){
		return(E_FAIL);
	}

	col->header = malloc(sizeof(char *) * (strlen(header) + 1));
	strcpy(col->header, header);

	return(E_SUCCESS);
}

int e_ColumnSetFontName(char *colName, char *fontName){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);

	if(!col){
		return(E_FAIL);
	}

	col->fontName = malloc(sizeof(char *) * (strlen(fontName) + 1));
	strcpy(col->fontName, fontName);

	return(E_SUCCESS);
}

int e_ColumnSetFontStyle(char *colName, char *fontStyle){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);

	if(!col){
		return(E_FAIL);
	}

	col->fontStyle = malloc(sizeof(char *) * (strlen(fontStyle) + 1));
	strcpy(col->fontStyle, fontStyle);

	return(E_SUCCESS);
}

int e_ColumnSetFontSize(char *colName, int fontSize){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);

	if(!col){
		return(E_FAIL);
	}

	col->fontSize = fontSize;

	return(E_SUCCESS);
}

int e_GraphSetIndexLabel(graphName, label)
   char *graphName;
   char *label;
{
	struct Graph *E_GetGraph();
	struct Graph *graph;

	graph = E_GetGraph(graphName);

	if (!graph) {
		return(E_FAIL);
	}

	graph->indexLabel->text = malloc(strlen(label) + 1);
	strcpy(graph->indexLabel->text, label);

	return(E_SUCCESS);
}

int e_GraphSetPlotArea(graphName, location, width, height)
   char *graphName;
   float location[];
   float width;
   float height;
{
   struct Graph *E_GetGraph();
   struct Graph *graph;

   graph = E_GetGraph(graphName);

   if (!graph) {
	return(E_FAIL);
   }

   /* printf("e_GraphSetPlotArea:  location = %f %f\n", location[0], location[1]); */

   graph->originX = location[0];
   graph->originY = location[1];
   graph->width = width;
   graph->height = height;
   return(E_SUCCESS);
}


int e_GraphShowLegend(graphName, show)
   char *graphName;
   int show;
{
   struct Graph *E_GetGraph();
   struct Graph *graph;

   graph = E_GetGraph(graphName);

   if (!graph) {
	return(E_FAIL);
   }

   graph->showLegend = show;
   return(E_SUCCESS);
}


int e_GraphAddLegendTitle(graphName, title)
   char *graphName;
   char *title;
{
   struct Graph *E_GetGraph();
   struct Graph *graph;

	/* printf("e_GraphAddLegendTitle\n"); */
   graph = E_GetGraph(graphName);

   if (!graph) {
	return(E_FAIL);
   }

	/* printf("  e_GraphAddLegendTitle %d\n", graph->legend);
	printf("%s\n",  title);
	printf("%d\n", graph->legend->nTitles); */
   graph->legend->title[graph->legend->nTitles] = malloc(strlen(title));
	/* printf("    e_GraphAddLegendTitle malloced\n"); */
   strcpy(graph->legend->title[graph->legend->nTitles], title);

   (graph->legend->nTitles)++;

	/* printf("%d %s\n", graph->legend->nTitles, title); */
   return(E_SUCCESS);
}

int e_FxDatasetCreate(setName, nPoints, x, fx)
   char *setName;
   int   nPoints;
   double x[];
   double fx[];
{
   struct FxDataset *dataset;
   int i;
/*
       	printf("e_FxDatasetCreate - creating = %s, nPoints = %d \n", setName, nPoints);

	if (firstFxDataset != NULL) {
   		printf("   firstFxDataset name = %s\n",firstFxDataset->name);
	}
       	E_PrintFxDatasets();
*/

   dataset = malloc(sizeof(struct FxDataset));

   if (!dataset) {
	return(E_FAIL);
   }

   dataset->name = malloc(strlen(setName) + 1);
   if (!(dataset->name)) {
	return(E_FAIL);
   }

   strcpy(dataset->name, setName);
   dataset->nPoints = nPoints;
   dataset->next = NULL;

   dataset->x = malloc(sizeof(double) * dataset->nPoints);
   dataset->fx = malloc(sizeof(double) * dataset->nPoints);

   if (dataset->x == NULL || dataset->fx == NULL) {
	return(E_FAIL);
   }

   dataset->showLine = -1;
   dataset->showMarker = -2;

   for (i=0; i<nPoints; i++) {
	dataset->x[i] = x[i];
	dataset->fx[i] = fx[i];

	/* printf("dataset: %lf %lf\n",x[i], fx[i]); */
   }

   E_CreateFxDataset(dataset);

/*
   E_PrintFxDatasets();
   printf("   e_FxDatasetCreate - created dataset:\n\n");
*/

   return(E_SUCCESS);
}


int e_FxtDatasetCreate(setName, nPoints, x, fx, time)
   char *setName;
   int   nPoints;
   double x[];
   double fx[];
   double time;
{
   struct FxDataset *dataset;
   int i;
   static int id = 0;


      /* printf("e_FxtDatasetCreate - creating = %s, nPoints = %d %f \n", setName, nPoints, time); */
	/* if (firstFxDataset != NULL) {
   		printf("   firstFxDataset name = %s\n",firstFxDataset->name);
	} */
   /* E_PrintFxDatasets(); */


   dataset = malloc(sizeof(struct FxDataset));

   if (!dataset) {
	return(E_FAIL);
   }

   dataset->name = malloc(strlen(setName) + 1);
   if (!(dataset->name)) {
	return(E_FAIL);
   }

   strcpy(dataset->name, setName);
   dataset->nPoints = nPoints;
   dataset->index = time;
   dataset->next = NULL;

   dataset->x = malloc(sizeof(double) * dataset->nPoints);
   dataset->fx = malloc(sizeof(double) * dataset->nPoints);

   if (dataset->x == NULL || dataset->fx == NULL) {
	return(E_FAIL);
   }

   dataset->showLine = -1;
   dataset->showMarker = -2;

   id++;
   dataset->id = id;
	 /* printf("  dataset->id = %d\n", dataset->id); */

   for (i=0; i<nPoints; i++) {
	dataset->x[i] = x[i];
	dataset->fx[i] = fx[i];

	/* printf("dataset: %lf %lf\n",x[i], fx[i]); */
   }

   E_CreateFxDataset(dataset);

/*
   E_PrintFxDatasets(); 
   printf("   e_FxDatasetCreate - created dataset:\n\n");
*/

   return(dataset->id);
}


int e_FxyCreate(setName, nx, ny, xy, xcoords, ycoords)
   char *setName;
   int   nx, ny;
   double *xy;
   double xcoords[], ycoords[];
{
   struct FxyDataset *dataset;
   int i, j, loc = 0;

   dataset = (struct FxyDataset *) malloc(sizeof(struct FxyDataset));

   if (!dataset) {
	return(E_FAIL);
   }

   dataset->name = (char *) malloc(strlen(setName) + 1);
   if (!(dataset->name)) {
	return(E_FAIL);
   }

   strcpy(dataset->name, setName);
   dataset->nx = nx;
   dataset->ny = ny;
   dataset->next = NULL;

   dataset->xcoords = (double *) malloc(sizeof(double) * dataset->nx);
   dataset->ycoords = (double *) malloc(sizeof(double) * dataset->ny);

   for (i=0; i<nx; i++) {
	dataset->xcoords[i] = xcoords[i];
   }

   for (i=0; i<ny; i++) {
	dataset->ycoords[i] = ycoords[i];
   }

   if (dataset->xcoords == NULL || dataset->ycoords == NULL) {
	return(E_FAIL);
   }
     /* printf("e_FxyCreate - allocated and set ycoords\n"); */

   dataset->fxy = (double *) malloc(sizeof(double) * dataset->nx * dataset->ny);

   if (dataset->fxy == NULL) {
	return(0);
   }

     /* printf("%d %d\n", dataset->nx, dataset->ny); */

   for (i=0; i<nx; i++) {
   	for (j=0; j<ny; j++) {
		  /* printf("%d %d   %lf\n", i, j, xy[i*ny + j]); */
		dataset->fxy[loc] = xy[i*ny + j];
		loc++;
	}
   }

   E_CreateFxyDataset(dataset);

   return(E_SUCCESS);
}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Creates a column with no cells in it.
 ********************************************************************************/
int e_ColumnCreateBlank(char *name){
	struct Column *col;
	
	col = (struct Column *) malloc(sizeof(struct Column));

	if(!col){
		return(E_FAIL);	
	}

	col->name = (char *) malloc(sizeof(char *) * (strlen(name) + 1));
	col->header = (char *) malloc(sizeof(char *) * (strlen(name) + 1));
	col->fontName = (char *) malloc(sizeof(char *) * 50);
	col->fontStyle = (char *) malloc(sizeof(char *) * 15);
	if(!(col->name) || !(col->header) || !(col->fontName) || !(col->fontStyle)){
		return(E_FAIL);
	}

	strcpy(col->name, name);
	strcpy(col->header, name);
	strcpy(col->fontName, "SansSerif");
	strcpy(col->fontStyle, "Plain");

	col->nCells = 0;
	col->fontSize = 12;
	col->rowLabelsFlag = E_FALSE;
	col->next = NULL;

	col->bgcolor = malloc(sizeof(char *) * 100);
	col->fontColor = malloc(sizeof(char *) *100);
	if(!(col->bgcolor) || !(col->fontColor)){
		return E_ALLOCATE_FAIL;
	}

	strcpy(col->bgcolor, "");
	strcpy(col->fontColor, "");

	col->cells = (char *(*)) malloc(sizeof(char *) * 100);
	if(col->cells == NULL){
		return(E_ALLOCATE_FAIL);
	}

	E_CreateColumn(col);

	return(E_SUCCESS);
}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Adds a list of values to a column.
 ********************************************************************************/
int e_ColumnAddRows(char *colName, int nCells, char *(*cells)){
	int i, status;

	for(i = 0; i < nCells; i++){
		status = e_ColumnAddRow(colName, cells[i]);
		if(status != E_SUCCESS){
			return(status);
		}
	}
	return(E_SUCCESS);
}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Adds a single value to a column.
 ********************************************************************************/
int e_ColumnAddRow(char *colName, char *cell){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);

	if(!col){
		return(E_TABLE_NOT_FOUND);
	}

	col->nCells++;

	col->cells = (char*(*)) realloc(col->cells, sizeof(char *) * col->nCells * 100);
	if(col->cells == NULL){
		return(E_ALLOCATE_FAIL);
	}

	col->cells[col->nCells - 1] = malloc(sizeof(char *) * 100);
	strcpy(col->cells[col->nCells - 1], cell);

	return(E_SUCCESS);
}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Sets a column to have row labels or not.
 ********************************************************************************/
int e_ColumnSetRowLabels(char *colName, int labels){
	struct Column *col;
	struct Column *E_GetColumn();

	col = E_GetColumn(colName);

	if(!col){
		return(E_FAIL);
	}

	col->rowLabelsFlag = labels;

	return(E_SUCCESS);
}

/********************************************************************************
 * B.Bariteau 7/15/08
 * Creates a column with a list of values.
 ********************************************************************************/
int e_ColumnCreate(char *name, int nCells, char *(*cells)){
	struct Column *col;
	int i;
	
	col = (struct Column *) malloc(sizeof(struct Column));
	
	if(!col){
		return(E_FAIL);
	}
	
	col->name = (char *) malloc(sizeof(strlen(name) + 1));
	col->header = (char *) malloc(sizeof(strlen(name) + 1));
	col->fontName = (char *) malloc(sizeof(char) * 50);
	col->fontStyle = (char *) malloc(sizeof(char) * 15);
	col->fontSize = 12;
	if(!(col->name) || !(col->header) || !(col->fontName) || !(col->fontStyle)){
		return(E_FAIL);
	}
	
	strcpy(col->name, name);
	strcpy(col->header, name);
	
	col->nCells = nCells;
	col->rowLabelsFlag = E_FALSE;
	col->next = NULL;

	col->cells = (char *(*)) malloc(sizeof(char *) * nCells * 50);
	if(col->cells == NULL){
		return(E_ALLOCATE_FAIL);
	}

	col->bgcolor = malloc(sizeof(char *) * 100);
	col->fontColor = malloc(sizeof(char *) *100);
	if(!(col->bgcolor) || !(col->fontColor)){
		return E_ALLOCATE_FAIL;
	}

	strcpy(col->bgcolor, "");
	strcpy(col->fontColor, "");
	
	for(i = 0; i < nCells; i++){
		col->cells[i] = cells[i];
	}
	
	E_CreateColumn(col);
	
	return(E_SUCCESS);
}

int e_FxySetContour(name, ncontours, contours)
   char *name;
   int ncontours;
   double contours[];
{
   struct FxyDataset *dataset;
   int i;

   dataset = E_GetFxyDataset(name);

   if (!dataset) {
	return(E_FAIL);
   }

   dataset->ncontours = ncontours;

   dataset->contours = malloc(sizeof(double) * ncontours);

   for (i=0; i<ncontours; i++) {
	dataset->contours[i] = contours[i];
   }

   return(E_SUCCESS);
}


int e_SurfaceCreate(surfaceName, graphName)
   char *surfaceName;
   char *graphName;
{
   struct Graph *E_GetGraph();
   struct Graph *graph;

	/* printf("e_SurfaceCreate:  %s %s\n", surfaceName, graphName); */
   e_GraphCreate(surfaceName, SURFACE);

   graph = E_GetGraph(surfaceName);
	/* printf("  graph = %d\n", graph); */

   if (!graph) {
	return(E_FAIL);
   }

   graph->surfaceGraphName = malloc(strlen(graphName) + 1);
   if (!(graph->surfaceGraphName)) {
	return(E_FAIL);
   }
   else {
   	strcpy(graph->surfaceGraphName, graphName);
   }

   return(E_SUCCESS);
}


int e_SurfaceSetTitle(surfaceName, label)
   char *surfaceName;
   char *label;
{
   int status;

   status = e_GraphSetTitle(surfaceName, label);
   return(status);
}

int e_GraphWindowDisplay(windowName)
   char *windowName;
{
	int command = 55;

	if (transpMonitor == 1) {
		E_GraphWindowSendGW(windowName, command);
	} else {
		E_GraphWindowSendEML(windowName, command);
	}
}

int e_GraphWindowUpdate(windowName)
   char *windowName;
{
	int command = 58;
	   /* printf("GraphWindowUpdate = %s\n", windowName); */
	E_GraphWindowSendGW(windowName, command);
}
/*************************************************************
 * B.Bariteau - 6/27/08 - This function now loops through each
 * output in the ELVIS_SERVER list and prints to all of them.
 * Also, it now prints a comment at the top of a file output.
 *
 * B.Bariteau 7/15/08
 * This function now handles tables.
 *************************************************************/
int E_GraphWindowSendEML(windowName, command)
   char *windowName;
   int command;
{
	struct GraphWindow *gw;
	struct GraphWindow *E_GetGraphWindow();
	int status;
	int sockfd;
	char s[256];
	char tf[10];
	int name_length;
	struct Graph *graph;
	struct FxDataset *fxDataset;
	struct Label *label;
	int i, j, k, p, q, m;
	void E_writeLabel();
	int written;
	int handle = -1;
	time_t timestamp;
	struct tm *timeinf;
	int hour;
	char ampm[] = "AM";
	int maxlen = 0;
	int r, g, b;

	gw = E_GetGraphWindow(windowName);
	   /* printf("....E_GraphWindowSend type = %d\n", gw->type); */

	if (!gw) {
		return(E_FAIL);
	}

	  /* E_PrintGraphWindow(gw); */
	for(m = 0; m < numpaths; m++){
	   	sockfd = e_socket_initialize(m);
	   	if (sockfd == -1)
			return(E_FAIL);
			/* Eliot - determine type of gw */
		
		strcpy(s, "<?xml version='1.0' encoding='utf-8'?>"); write_line(sockfd, s, strlen(s));
		
		if(sockfd == -2){
		  time(&timestamp);
		  timeinf = localtime(&timestamp);
		  if((*timeinf).tm_hour > 12){
		    hour = (*timeinf).tm_hour - 12;
		    ampm[0] = 'P';
		  }else{
		    hour = (*timeinf).tm_hour;
		  }
		  sprintf(s, "<!-- Date: %d-%d-%d  Time: %d:%d:%2d %s -->", (*timeinf).tm_mon, (*timeinf).tm_mday, (*timeinf).tm_year+1900, hour, (*timeinf).tm_min, (*timeinf).tm_sec, ampm);
		  write_line(sockfd, s, strlen(s));
		}

		sprintf(s,"<visualstate>"); 			write_line(sockfd, s);
		sprintf(s,"<graphwindow"); 			write_line(sockfd, s);
		sprintf(s," command=\"%d\"", command); 		write_line(sockfd, s);
		sprintf(s," appname=\"%s\"", application); 		write_line(sockfd, s);
		sprintf(s," user=\"%s\"", user); 		write_line(sockfd, s);
		sprintf(s," host=\"%s\"", host); 		write_line(sockfd, s);
		sprintf(s," id=\"%s\"", id); 		write_line(sockfd, s);
		sprintf(s," rows=\"%d\"", gw->nRows); 		write_line(sockfd, s);
		sprintf(s," columns=\"%d\"", gw->nColumns); 	write_line(sockfd, s);
	
		if (gw->type == 1) {
			sprintf(s, " graphtype=\"fx\""); 	write_line(sockfd, s);
		} else if (gw->type == 2 || gw->type == 3 || gw->type == 5 || gw->type == 6) {
			sprintf(s, " graphtype=\"fxi\""); 	write_line(sockfd, s);
		}else if(gw->type == 8){
			sprintf(s, " graphtype=\"table\"");	write_line(sockfd, s);
		}

		if (command == 58) {
			sprintf(s," update=\"true\""); 			write_line(sockfd, s);
		} else {
			sprintf(s," update=\"false\""); 		write_line(sockfd, s);
		}
	
		xmlFixString(windowName);
		sprintf(s," name=\"%s\"", xmlS); 		write_line(sockfd, s);
	
		if (collector == 1) {
			sprintf(s," collector=\"true\""); 		write_line(sockfd, s);
		} else {
			sprintf(s," collector=\"false\""); 		write_line(sockfd, s);
		}
		   /* sprintf(s," Version=\"1.0\""); 			write_line(sockfd, s); */
		sprintf(s," >"); 				write_line(sockfd, s);

		for (i=0; i<gw->nGraphsInList; i++) {
	   		graph = gw->graphList[i];
			  	/* printf(">>>graph->type = %d\n", graph->type); */

			for(k = 0; k<graph->nColumns; k++){
				if(maxlen < graph->columnList[k]->nCells){
					maxlen = graph->columnList[k]->nCells;
				}
			}

			sprintf(s, " <graph"); 				write_line(sockfd, s);
			sprintf(s, "  row=\"%d\"", graph->row); 	write_line(sockfd, s);
			sprintf(s, "  column=\"%d\"", graph->column); 	write_line(sockfd, s);
	
			if (graph->type == FX) {
				sprintf(s, "  graphtype=\"fx\""); 	write_line(sockfd, s);
			} else if (graph->type == FXI || gw->type == FXT) {
				sprintf(s, "  graphtype=\"fxi\""); 	write_line(sockfd, s);
				sprintf(s, "  indexText=\"%s\"", graph->indexLabel->text); 	write_line(sockfd, s);
			} else if (graph->type == XY) {
			  	   /* printf("graph->type XY = %d\n", graph->type); */
				sprintf(s, "  graphtype=\"contour\""); 	write_line(sockfd, s);
				sprintf(s, "  indexText=\"%s\"", graph->indexLabel->text); 	write_line(sockfd, s);
				if (graph->legend->nTitles > 0) {
				   sprintf(s, "  legendTitle=\"%s\"", graph->legend->title[0]);	write_line(sockfd, s);
				}
			} else if (graph->type == SURFACE) {
			  	  /* printf("graph->type SURFACE = %d\n", graph->type); */
				sprintf(s, "  graphtype=\"surface\""); 	write_line(sockfd, s);
				sprintf(s, "  indexText=\"%s\"", graph->indexLabel->text); 	write_line(sockfd, s);
			} else if (graph->type == DATA_TABLE){
				sprintf(s, "  graphtype=\"table\"");		write_line(sockfd, s);
				sprintf(s, "  rows=\"%d\"", (maxlen + 1));		write_line(sockfd, s);
				sprintf(s, "  columns=\"%d\"", graph->nColumns);write_line(sockfd, s);
			}
	
			sprintf(s, "  originx=\"%f\"", graph->originX); write_line(sockfd, s);
			sprintf(s, "  originy=\"%f\"", graph->originY); write_line(sockfd, s);
			sprintf(s, "  width=\"%f\"", graph->width); 	write_line(sockfd, s);
			sprintf(s, "  height=\"%f\"", graph->height); 	write_line(sockfd, s);
			xmlFixString(graph->titleLabel->text);
			sprintf(s, "  title=\"%s\"", xmlS); 	write_line(sockfd, s);
			xmlFixString(graph->shortTitle);
			sprintf(s, "  shortTitle=\"%s\"", xmlS); 	write_line(sockfd, s);
	
			if (graph->showLegend == 1) {
				strcpy(tf, "true");
			} else {
				strcpy(tf, "false");
			}
	
			sprintf(s, "  showlegend=\"%s\"", tf); 		write_line(sockfd, s);
			xmlFixString(graph->name);
			sprintf(s, "  text=\"%s\"", xmlS); 	write_line(sockfd, s);
			sprintf(s,"  >"); 				write_line(sockfd, s);
	
			sprintf(s, "  <axis"); 			write_line(sockfd, s);
			sprintf(s, "   direction=\"x\"");	write_line(sockfd, s);
			sprintf(s, "   numberstyle=\"%d\"", graph->xNumberStyle);	write_line(sockfd, s);
			if (graph->xRangeFlag == 1) {
			   sprintf(s, "   min=\"%32.24f\"", graph->xRange[0]);	write_line(sockfd, s);
			   sprintf(s, "   max=\"%32.24f\"", graph->xRange[1]);	write_line(sockfd, s);
			}

			if(graph->xGridFlag == E_TRUE){
				strcpy(tf, "true");
			}else{
				strcpy(tf, "false");
			}

			sprintf(s, "   showGridlines=\"%s\"", tf);	write_line(sockfd, s);
			xmlFixString(graph->xAxisLabel->text);
			sprintf(s, "   text=\"%s\"", xmlS); 		write_line(sockfd, s);
			sprintf(s, "   />"); 				write_line(sockfd, s);

			sprintf(s, "  <axis"); 			write_line(sockfd, s);
			sprintf(s, "   direction=\"y\"");	write_line(sockfd, s);
			sprintf(s, "   numberstyle=\"%d\"", graph->yNumberStyle);	write_line(sockfd, s);
			if (graph->yRangeFlag == 1) {
			   sprintf(s, "   min=\"%32.24f\"", graph->yRange[0]);	write_line(sockfd, s);
			   sprintf(s, "   max=\"%32.24f\"", graph->yRange[1]);	write_line(sockfd, s);
			}

			if(graph->yGridFlag == E_TRUE){
				strcpy(tf, "true");
			}else{
				strcpy(tf, "false");
			}

			sprintf(s, "   showGridlines=\"%s\"", tf);	write_line(sockfd, s);

			xmlFixString(graph->yAxisLabel->text);
			sprintf(s, "   text=\"%s\"", xmlS); write_line(sockfd, s);
			sprintf(s, "   />"); 				write_line(sockfd, s);

			if(graph->type == SURFACE){
				sprintf(s, "  <axis"); 			write_line(sockfd, s);
				sprintf(s, "   direction=\"z\"");	write_line(sockfd, s);
				sprintf(s, "   numberstyle=\"%d\"", graph->zNumberStyle);	write_line(sockfd, s);
				if (graph->zRangeFlag == 1) {
					sprintf(s, "   min=\"%32.24f\"", graph->zRange[0]);	write_line(sockfd, s);
					sprintf(s, "   max=\"%32.24f\"", graph->zRange[1]);	write_line(sockfd, s);
				}

				if(graph->zGridFlag == E_TRUE){
					strcpy(tf, "true");
				}else{
					strcpy(tf, "false");
				}

				sprintf(s, "   showGridlines=\"%s\"", tf);	write_line(sockfd, s);

				xmlFixString(graph->indexLabel->text);
				sprintf(s, "   text=\"%s\"", xmlS); write_line(sockfd, s);
				sprintf(s, "   />"); 				write_line(sockfd, s);
			}

			for(j = 0; j < graph->nTopText; j++){
				sprintf(s, "  <toptext");			write_line(sockfd, s);
				xmlFixString(graph->topTextList[j]->text);
				sprintf(s, "   text=\"%s\"", xmlS);		write_line(sockfd, s);
				xmlFixString(graph->topTextList[j]->fontName);
				sprintf(s, "   font=\"%s\"", xmlS);		write_line(sockfd, s);
				xmlFixString(graph->topTextList[j]->fontStyle);
				sprintf(s, "   fontStyle=\"%s\"", xmlS);	write_line(sockfd, s);
				xmlFixString(graph->topTextList[j]->fontColor);
				sprintf(s, "   fontColor=\"%s\"", xmlS);	write_line(sockfd, s);
				sprintf(s, "   fontSize=\"%d\"", graph->topTextList[j]->fontSize);
				write_line(sockfd, s);
				xmlFixString(graph->topTextList[j]->bgColor);
				sprintf(s, "   color=\"%s\"", xmlS);	write_line(sockfd, s);
				sprintf(s, "   />");	write_line(sockfd, s);
			}

			for (j=0; j<graph->nLabels; j++) {
				label = graph->labelList[j];

				sprintf(s, "  <label"); 			write_line(sockfd, s);
				xmlFixString(label->text);
				sprintf(s, "   text=\"%s\"", xmlS); 	write_line(sockfd, s);
				sprintf(s, "   font=\"%s\"", label->fontName); 	write_line(sockfd, s);
				sprintf(s, "   style=\"%s\"", label->fontStyle); 	write_line(sockfd, s);
				xmlFixString(label->fontColor);
				sprintf(s, "   colorrgb=\"%s\"", xmlS);	write_line(sockfd, s);
				sprintf(s, "   size=\"%f\"", label->height); 	write_line(sockfd, s);
				sprintf(s, "   x=\"%f\"", label->x); 	write_line(sockfd, s);
				sprintf(s, "   y=\"%f\"", label->y); 	write_line(sockfd, s);
				sprintf(s, "   />"); 				write_line(sockfd, s);
			}
	/*
			for (j=0; j<graph->legend->nTitles; j++) {
				printf("%s\n", graph->legend->title[j]);
			}
	*/
			if (graph->type == XY) {
				    /* printf("XY dataset\n"); */
				sprintf(s, "  <xlist>");	write_line(sockfd, s);

				   /* printf("  nx = %d\n", graph->fxy->nx); */
				   /* printf("  ny = %d\n", graph->fxy->ny); */
				for (p=0; p<graph->fxy->nx; p++) {
	   				/* status = write_float4(sockfd, graph->fxy->xcoords[p]); */
					sprintf(s, "   <value p=\"%32.24f\"/>", graph->fxy->xcoords[p]); 	write_line(sockfd, s);
				}
				sprintf(s, "  </xlist>");	write_line(sockfd, s);

				sprintf(s, "  <indexlist>");	write_line(sockfd, s);

				for (q=0; q<graph->fxy->ny; q++) {
	   				/* status = write_float4(sockfd, graph->fxy->ycoords[q]); */
					sprintf(s, "   <value p=\"%32.24f\"/>", graph->fxy->ycoords[q]); 	write_line(sockfd, s);
				}

				sprintf(s, "  </indexlist>");	write_line(sockfd, s);

				sprintf(s, "  <contourlist>");	write_line(sockfd, s);

				for (k=0; k<graph->fxy->ncontours; k++) {
	   				/* status = write_float4(sockfd, graph->fxy->contours[k]); */
					sprintf(s, "   <value p=\"%32.24f\"/>", graph->fxy->contours[k]); 	write_line(sockfd, s);
				}
	
				sprintf(s, "  </contourlist>");	write_line(sockfd, s);

				sprintf(s, "  <postlist>");	write_line(sockfd, s);
				for (p=0; p<graph->fxy->nx; p++) {
				   for (q=0; q<graph->fxy->ny; q++) {
	   				/* status = write_float4(sockfd, graph->fxy->fxy[p*graph->fxy->ny + q]); */
					sprintf(s, "   <value p=\"%32.24f\"/>", graph->fxy->fxy[p*graph->fxy->ny + q]); 	write_line(sockfd, s);
				   }
				}
				sprintf(s, "  </postlist>");	write_line(sockfd, s);
			}
	
			for (j=0; j<graph->nDatasets; j++) {
				fxDataset = graph->fxDatasetList[j];
				   /* printf("   fxDataset = %d\n",fxDataset); */
	
				sprintf(s, "  <data1d");	write_line(sockfd, s);

				if (graph->type == FXI || graph->type == FXT || graph->type == E_TIME_INDEXED_ADD_POINTS || graph->type == SURFACE) {
					   /* printf("writing index %32.24f\n", fxDataset->index); */
					sprintf(s, "   index=\"%32.24f\"", fxDataset->index); 	write_line(sockfd, s);
				}
	
				xmlFixString(fxDataset->name);
				sprintf(s, "   name=\"%s\"", xmlS); 	write_line(sockfd, s);
	
				if (fxDataset->showLine == -1) {
					strcpy(tf, "true");
				} else {
					strcpy(tf, "false");
				}
	
				sprintf(s, "   showline=\"%s\"", tf); 	write_line(sockfd, s);
	
				if (fxDataset->showMarker >= 1) {
					strcpy(tf, "true");
				} else {
					strcpy(tf, "false");
				}

				sprintf(s, "   showmarker=\"%s\"", tf); 	write_line(sockfd, s);

				if(fxDataset->showMarker >= 1){
					sprintf(s, "   markerSkipCount=\"%d\"", fxDataset->showMarker);
					write_line(sockfd, s);
				}

				/* sprintf(s, "   Points=\"%d\"", fxDataset->nPoints); write_line(sockfd, s); */
				sprintf(s, "   >"); 				write_line(sockfd, s);

				for (k=0; k<fxDataset->nPoints; k++) {
					sprintf(s, "   <point x=\"%32.24f\" y=\"%32.24f\"/>", fxDataset->x[k], fxDataset->fx[k]); 	write_line(sockfd, s);
				}

				sprintf(s, "  </data1d>");	write_line(sockfd, s);
			}

			for(j = 0; j<graph->nColumns; j++){
				if(graph->columnList[j]->rowLabelsFlag == E_TRUE){
					strcpy(tf, "true");
				}else{
					strcpy(tf, "false");
				}
				sprintf(s, "  <column");				write_line(sockfd, s);
				sprintf(s, "   num=\"%d\"", j);				write_line(sockfd, s);
				xmlFixString(graph->columnList[j]->header);
				sprintf(s, "   name=\"%s\"", xmlS);			write_line(sockfd, s);
				sprintf(s, "   hasRowLabels=\"%s\"", tf);		write_line(sockfd, s);
				sprintf(s, "   fontName=\"%s\"", graph->columnList[j]->fontName);
				write_line(sockfd, s);
				sprintf(s, "   fontStyle=\"%s\"", graph->columnList[j]->fontStyle);
				write_line(sockfd, s);
				sprintf(s, "   fontSize=\"%d\"", graph->columnList[j]->fontSize);
				write_line(sockfd, s);
				sprintf(s, "   color=\"%s\"", graph->columnList[j]->bgcolor);
				write_line(sockfd, s);
				sprintf(s, "   fontColor=\"%s\"", graph->columnList[j]->fontColor);
				write_line(sockfd, s);
				sprintf(s, "   >");					write_line(sockfd, s);
				for(k = 0; k<graph->columnList[j]->nCells; k++){
					xmlFixString(graph->columnList[j]->cells[k]);
					sprintf(s, "   <cell value=\"%s\" />", xmlS);	write_line(sockfd, s);
				}

				sprintf(s, "  </column>");				write_line(sockfd, s);
			}
			
			for(j = 0; j < graph->nBottomText; j++){
				sprintf(s, "  <bottomtext");			write_line(sockfd, s);
				xmlFixString(graph->bottomTextList[j]->text);
				sprintf(s, "   text=\"%s\"", xmlS);		write_line(sockfd, s);
				xmlFixString(graph->bottomTextList[j]->fontName);
				sprintf(s, "   font=\"%s\"", xmlS);		write_line(sockfd, s);
				xmlFixString(graph->bottomTextList[j]->fontStyle);
				sprintf(s, "   fontStyle=\"%s\"", xmlS);	write_line(sockfd, s);
				xmlFixString(graph->bottomTextList[j]->fontColor);
				sprintf(s, "   fontColor=\"%s\"", xmlS);	write_line(sockfd, s);
				sprintf(s, "   fontSize=\"%d\"", graph->bottomTextList[j]->fontSize);
				write_line(sockfd, s);
				xmlFixString(graph->bottomTextList[j]->bgColor);
				sprintf(s, "   color=\"%s\"", xmlS);	write_line(sockfd, s);
				sprintf(s, "   />");	write_line(sockfd, s);
			}
			sprintf(s, " </graph>"); 	write_line(sockfd, s);
	   	}
	
		sprintf(s, "</graphwindow>"); 		write_line(sockfd, s);
		sprintf(s,"</visualstate>"); 			write_line(sockfd, s);
	
			/* printf("sockfd = %d\n", sockfd); */
	   	e_close(sockfd);
        }
	/* if return status from ElVis is OK then */
	/* gw->isShowing = 1; */

	return(E_SUCCESS);
}


int E_GraphWindowSendGW(windowName, command)
   char *windowName;
   int command;
{
	struct GraphWindow *gw;
	struct GraphWindow *E_GetGraphWindow();
	int status;
  	int sockfd;
   	int name_length;
	struct Graph *graph;
	struct FxDataset *fxDataset;
	struct Label *label;
	int i, j, k, p, q;
	void E_writeLabel();
	int written;
	int handle = -1;

	gw = E_GetGraphWindow(windowName);

	if (!gw) {
		return(E_FAIL);
	}

   	  /* E_PrintGraphWindow(gw); */

   	sockfd = e_socket_initialize(0);
   	if (sockfd == -1)
		return(E_FAIL);

	  /* printf("E_GraphWindowSendGW  %d\n", command); */
   	   /* send command, handle */
   	write_int4(sockfd, command);
   	write_int4(sockfd, handle);

	E_writeHandle(sockfd);

   	   /* send window name */
   	name_length = strlen(windowName);
   	write_int4(sockfd, name_length);
   	write_char(sockfd, windowName, name_length);

	/* Eliot - determine type of gw */

   	write_int4(sockfd, gw->type);
   	write_int4(sockfd, gw->nRows);
   	write_int4(sockfd, gw->nColumns);
   	write_int4(sockfd, gw->nGraphsInList);

	for (i=0; i<gw->nGraphsInList; i++) {
   		graph = gw->graphList[i];

   		write_int4(sockfd, graph->type);

   		   /* send graph name */
   		name_length = strlen(graph->name);

   		write_int4(sockfd, name_length);
   		write_char(sockfd, graph->name, name_length);

   		write_int4(sockfd, graph->row);
   		write_int4(sockfd, graph->column);

		E_writeLabel(sockfd, graph->xAxisLabel);
		E_writeLabel(sockfd, graph->yAxisLabel);
		E_writeLabel(sockfd, graph->titleLabel);

   		write_int4(sockfd, graph->nLabels);

		for (j=0; j<graph->nLabels; j++) {
			label = graph->labelList[j];
			E_writeLabel(sockfd, label);
		}
/*
		for (j=0; j<graph->legend->nTitles; j++) {
			printf("%s\n", graph->legend->title[j]);
		}
*/
   		write_float4(sockfd, graph->originX);
   		write_float4(sockfd, graph->originY);
   		write_float4(sockfd, graph->width);
   		write_float4(sockfd, graph->height);
		    /* printf("plotarea: %f %f\n",graph->width, graph->height);  */

   		write_int4(sockfd, graph->showLegend);

   		write_int4(sockfd, graph->nDatasets);
		   /*  printf("nDatasets = %d\n", graph->nDatasets); */
		   /* E_PrintFxDatasets(); */

		if (graph->type == FXI || graph->type == FXT || graph->type == E_TIME_INDEXED_ADD_POINTS) {
			    /* printf("writing index label\n"); */
			E_writeLabel(sockfd, graph->indexLabel);
		}

		if (graph->type == SURFACE) {
			    /* printf("GraphWindowDisplay:  graph->surfaceGraphName = %s\n", graph->surfaceGraphName); */
   			name_length = strlen(graph->surfaceGraphName);
   			write_int4(sockfd, name_length);
   			write_char(sockfd, graph->surfaceGraphName, name_length);
		}
		else if (graph->type == XY) {
			   /* printf("XY dataset\n"); */
   			name_length = strlen(graph->fxy->name);
   			written = write_int4(sockfd, name_length);
   			write_char(sockfd, graph->fxy->name, name_length);

   			write_int4(sockfd, graph->fxy->nx);
   			write_int4(sockfd, graph->fxy->ny);

			for (p=0; p<graph->fxy->nx; p++) {
   				status = write_float4(sockfd, graph->fxy->xcoords[p]);
			}

			for (q=0; q<graph->fxy->ny; q++) {
   				status = write_float4(sockfd, graph->fxy->ycoords[q]);
			}

			for (p=0; p<graph->fxy->nx; p++) {
			   for (q=0; q<graph->fxy->ny; q++) {
   				status = write_float4(sockfd, graph->fxy->fxy[p*graph->fxy->ny + q]);
				/* if (status != 4) { 
					 printf("write_float error = %d\n", status);
				} */
			   }
			}

   			write_int4(sockfd, graph->fxy->ncontours);

			for (k=0; k<graph->fxy->ncontours; k++) {
   				status = write_float4(sockfd, graph->fxy->contours[k]);
			}
		}

		for (j=0; j<graph->nDatasets; j++) {
			fxDataset = graph->fxDatasetList[j];
			   /* printf("   fxDataset = %d\n",fxDataset); */

			if (graph->type == FXI || graph->type == FXT || graph->type == E_TIME_INDEXED_ADD_POINTS) {
				/* printf("writing index %lf\n", fxDataset->index); */
   				write_float4(sockfd, fxDataset->index);
			}

   			name_length = strlen(fxDataset->name);
   			written = write_int4(sockfd, name_length);
   			write_char(sockfd, fxDataset->name, name_length);

   			write_int4(sockfd, fxDataset->showLine);
   			write_int4(sockfd, fxDataset->showMarker);

   			write_int4(sockfd, fxDataset->nPoints);
			    /* printf("nPoints = %d\n", fxDataset->nPoints); */

			for (k=0; k<fxDataset->nPoints; k++) {
   				status = write_float4(sockfd, fxDataset->x[k]);
				/* if (status != 4) { 
					 printf("write_float error = %d\n", status);
				} */
			}
			for (k=0; k<fxDataset->nPoints; k++) {
   				status = write_float4(sockfd, fxDataset->fx[k]);
				/* if (status != 4) {
					printf("write_float error\n");
				} */
			}
		}

   		write_int4(sockfd, graph->xRangeFlag);
   		write_float4(sockfd, graph->xRange[0]);
   		write_float4(sockfd, graph->xRange[1]);

   		write_int4(sockfd, graph->yRangeFlag);
   		write_float4(sockfd, graph->yRange[0]);
   		write_float4(sockfd, graph->yRange[1]);

   		write_int4(sockfd, graph->xNumberStyle);
   		write_int4(sockfd, graph->yNumberStyle);
   	}

		/* printf("sockfd = %d\n", sockfd); */
   	e_close(sockfd);

	/* if return status from ElVis is OK then */
	/* gw->isShowing = 1; */

	return(E_SUCCESS);
}



int e_FxtDatasetDisplay(windowName, graphName, datasetName)
   char *windowName;
   char *graphName;
   char *datasetName;
{
	struct FxDataset *fxDataset;
	struct FxDataset *E_GetFxDataset();

	fxDataset = E_GetFxDataset(datasetName);
	E_FxtDatasetDisplay(windowName, graphName, fxDataset);
}


int e_FxtDatasetDisplayID(windowName, graphName, id)
   char *windowName;
   char *graphName;
   int id;
{
	struct FxDataset *fxDataset;
	struct FxDataset *E_GetFxDatasetID();

	     /* printf("e_FxtDatasetDisplayID: %s %s %d \n", windowName, graphName, id); */
	fxDataset = E_GetFxDatasetID(id);
	     /* printf("  e_FxtDatasetDisplayID: %d \n", fxDataset); */
	     /* printf("    e_FxtDatasetDisplayID: name=%s \n", fxDataset->name); */
	E_FxtDatasetDisplay(windowName, graphName, fxDataset);
}


int E_FxtDatasetDisplay(windowName, graphName, fxDataset)
   char *windowName;
   char *graphName;
   struct FxDataset *fxDataset;
{
	struct GraphWindow *gw;
	struct GraphWindow *E_GetGraphWindow();
	int status;
  	int sockfd;
   	int command = 61;
   	int name_length;
	struct Graph *graph;
	int k;
	int written;
	int handle = -1;

	/* Don't check for existing gw because incoming data could be from new invocation */

	    /* printf("E_FxtDatasetDisplay: %s %s %d \n", windowName, graphName, fxDataset); */
	    /* printf("   fxDataset->name = %s\n",fxDataset->name); */
	    /* printf("   fxDataset->showLine = %d\n",fxDataset->showLine); */
   	sockfd = e_socket_initialize(0);
   	if (sockfd == -1)
     		return(E_FAIL);

   	   /* send command, handle */
   	write_int4(sockfd, command);
   	write_int4(sockfd, handle);

	E_writeHandle(sockfd);

   	   /* send window name */
   	name_length = strlen(windowName);
   	write_int4(sockfd, name_length);
   	status = write_char(sockfd, windowName, name_length);
	     /* printf("   E_FxtDatasetDisplay: wrote %d\n",status); */

   	   /* send graph name */
   	name_length = strlen(graphName);

   	write_int4(sockfd, name_length);
   	write_char(sockfd, graphName, name_length);

   	write_float4(sockfd, fxDataset->index);
	    /* printf("   fxDataset->index = %f\n",fxDataset->index); */

	    /* printf("   fxDataset->name = %s\n",fxDataset->name); */
 	name_length = strlen(fxDataset->name);
   	written = write_int4(sockfd, name_length);
   	write_char(sockfd, fxDataset->name, name_length);

   	write_int4(sockfd, fxDataset->showLine);
   	write_int4(sockfd, fxDataset->showMarker);

   	write_int4(sockfd, fxDataset->nPoints);
	     /* printf("nPoints = %d\n", fxDataset->nPoints); */

	for (k=0; k<fxDataset->nPoints; k++) {
   		status = write_float4(sockfd, fxDataset->x[k]);
		/* if (status != 4) { 
			 printf("write_float error = %d\n", status);
		} */
	}
	for (k=0; k<fxDataset->nPoints; k++) {
   		status = write_float4(sockfd, fxDataset->fx[k]);
		/* if (status != 4) {
			printf("write_float error\n");
		} */
	}

   	e_close(sockfd);

	   /* if return status from ElVis is OK then */
	/* gw->isShowing = 1; */

	   /* printf("Done with FxtDatasetDisplay\n"); */
	return(E_SUCCESS);
}


int e_DatasetAddPoints(windowName, graphName, datasetName, nPoints, x, fx)
   char *windowName;
   char *graphName;
   char *datasetName;
   int  nPoints;
   double x[];
   double fx[];
{
	/* struct GraphWindow *gw;
	struct GraphWindow *E_GetGraphWindow();
	struct FxDataset *E_GetFxDataset();
	struct Graph *graph;
	struct FxDataset *fxDataset; */
	int status;
  	int sockfd;
   	int command = DATASET_ADD_POINTS;
   	int name_length;
	int k;
	int written;
	int handle = -1;

	/* Don't check for existing gw because incoming data could be from new invocation */

	if (initialized == 0) {
		e_initialize();
	}

   	sockfd = e_socket_initialize(0);
   	if (sockfd == -1)
     		return(E_FAIL);

   	   /* send command, handle */
   	write_int4(sockfd, command);
   	write_int4(sockfd, handle);

	E_writeHandle(sockfd);

   	   /* send window name */
   	name_length = strlen(windowName);
   	write_int4(sockfd, name_length);
   	write_char(sockfd, windowName, name_length);

   	   /* send graph name */
   	name_length = strlen(graphName);
   	write_int4(sockfd, name_length);
   	write_char(sockfd, graphName, name_length);

   	   /* send dataset name */
 	name_length = strlen(datasetName);
   	written = write_int4(sockfd, name_length);
   	write_char(sockfd, datasetName, name_length);

   	write_int4(sockfd, -1);
   	write_int4(sockfd, -2);

   	write_int4(sockfd, nPoints);
	   /* printf("nPoints = %d\n", nPoints); */

	for (k=0; k<nPoints; k++) {
   		status = write_float4(sockfd, x[k]);
		/* if (status != 4) { 
			 printf("write_float error = %d\n", status);
		} */
	}
	for (k=0; k<nPoints; k++) {
   		status = write_float4(sockfd, fx[k]);
		/* if (status != 4) {
			printf("write_float error\n");
		} */
	}

   	e_close(sockfd);

	   /* if return status from ElVis is OK then */
	/* gw->isShowing = 1; */

	return(E_SUCCESS);
}

int e_GraphWindowPrint(windowName, row, column, fileName)
   char *windowName;
   int row;
   int column;
   char *fileName;
{
	int status;
  	int sockfd;
   	int command = 57;
   	int name_length;
	int handle = -1;

   	sockfd = e_socket_initialize(0);
   	if (sockfd == -1)
     		return 1;

   	/* send command, handle */
   	write_int4(sockfd, command);
   	write_int4(sockfd, handle);

	E_writeHandle(sockfd);

   	/* send window name */
   	name_length = strlen(windowName);
   	write_int4(sockfd, name_length);
   	write_char(sockfd, windowName, name_length);

   	write_int4(sockfd, row);
   	write_int4(sockfd, column);

   	/* send file name */
   	name_length = strlen(fileName);
   	write_int4(sockfd, name_length);
   	write_char(sockfd, fileName, name_length);

   	e_close(sockfd);

	return(status);
}


int e_CloseWindows()
{
	int status;
  	int sockfd;
   	int command = 54;
   	int name_length;
   	int   handle = -1;

   	sockfd = e_socket_initialize(0);
   	if (sockfd == -1)
     		return(E_FAIL);

   	/* send command, handle */
   	write_int4(sockfd, command);
   	write_int4(sockfd, handle);

	E_writeHandle(sockfd);

   	e_close(sockfd);

	return(E_SUCCESS);
}


int e_GraphWindowCreateFile(char *filename)
{
	FILE *file;
   	char *hostname;
	char *catName;

	  printf("e_GraphWindowCreateFile %s\n", filename);

   	hostname = getenv("ELVIS_SERVER");

	if (hostname == NULL) {
		file = fileCreate(filename);
		fileList[0] = file;
		GWFileCreated = 1;
	}
   	else if (strncmp(hostname, ".", 1) == 0 || strncmp(hostname, "/", 1) == 0) {
		E_Strcat(hostname, filename, &catName);
		file = fileCreate(catName);
		fileList[0] = file;
		GWFileCreated = 1;
	  		printf("  e_GraphWindowCreateFile %d\n", fileList[0]);

		free(catName);

		if (file == NULL) {
			return(E_FAIL);
		}
		else {
			return(E_SUCCESS);
		}
	}
}

int e_GraphWindowAppendFile(char *filename)
{
	FILE *file;
   	char *hostname;
	char *catName;

	  /* printf("append File\n"); */
   	hostname = getenv("ELVIS_SERVER");

	if (hostname == NULL) {
		file = fileOpen(filename);
		fileList[0] = file;
		GWFileCreated = 1;
	}
   	else if (strncmp(hostname, ".", 1) == 0 || strncmp(hostname, "/", 1) == 0) {
		E_Strcat(hostname, filename, &catName);
		file = fileOpen(catName);  /* only difference between CreateFile */
		fileList[0] = file;
		GWFileCreated = 1;
	  		printf("  e_GraphWindowAppendFile %d\n", fileList[0]);

		free(catName);

		if (file == NULL) {
			return(E_FAIL);
		}
		else {
			return(E_SUCCESS);
		}
	}

}

int e_GraphWindowCloseFile(char *filename, int poll)
{
   	char *hostname;
	int status;
	char *catName;
  	int sockfd;
   	int command = 80;
   	int   handle = -1;

   	hostname = getenv("ELVIS_SERVER");

	  /* printf("e_GraphWindowCloseFile poll =  %d\n", poll); */

	if (poll == 0) {
   		sockfd = e_socket_initialize(0);
   		if (sockfd == -1)
     			return(E_FAIL);

		   /* printf("e_GraphWindowCloseFile command = %d\n", command); */

   		   /* send command, handle */
   		write_int4(sockfd, command);
   		write_int4(sockfd, handle);

   		e_close(sockfd);
	}

	if (hostname == NULL) {
		status = fileClose(filename);
		return(status);
	}
   	else if (strncmp(hostname, ".", 1) == 0 || strncmp(hostname, "/", 1) == 0) {
		E_Strcat(hostname, filename, &catName);
		status = fileClose(catName);

		free(catName);
		return(status);
	}
}

/*-----------------------------internal E_ routines ----------------------------------------*/

void E_writeHandle(sockfd)
   int sockfd;
{   
	int length;

	if (transpMonitor == 1) {
	  if (registered == 0) {
		e_register("app", "user", "host", "id", 0);
	  }

   	  length = strlen(application);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, application, length);
  
   	  length = strlen(user);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, user, length);

   	  length = strlen(host);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, host, length);

   	  length = strlen(id);
   	  write_int4(sockfd, length);
   	  write_char(sockfd, id, length);
	}
}

void E_writeLabel(sockfd, label)
   int sockfd;
   struct Label *label;
{
	int nameLength;
	int i;
	float color[3];

	color[0] = 0.;
	color[1] = 0.;
	color[2] = 0.;

	  printf("E_writeLabel:  %s\n", label->text);
	  printf("  E_writeLabel:  %d\n", strlen(label->text));
	nameLength = strlen(label->text);
	write_int4 (sockfd, nameLength);
	write_char(sockfd, label->text, nameLength);

	   printf("   %f %f %f\n", label->x, label->y, label->height); 
	write_float4(sockfd, label->x);
	write_float4(sockfd, label->y);
	write_float4(sockfd, label->height);

	nameLength = strlen(label->fontName);
	write_int4 (sockfd, nameLength);
	write_char(sockfd, label->fontName, nameLength);

	nameLength = strlen(label->fontStyle);
	write_int4 (sockfd, nameLength);
	write_char(sockfd, label->fontStyle, nameLength);

	/*  for (i=0; i<3; i++) {
		write_float4(sockfd, label->color[i]);
	}  */

	  /* printf("   E_writeLabel:  %s\n", label->fontColor); */
	  /* only check for colors the elvis_transmit sends */
	if (strcmp("name: black", label->fontColor) == 0) {
		color[0] = 0.;
		color[1] = 0.;
		color[2] = 0.;
	} else if (strcmp("name: blue", label->fontColor) == 0) {
		color[0] = 0.;
		color[1] = 0.;
		color[2] = 1.;
	}

	for (i=0; i<3; i++) {
		write_float4(sockfd, color[i]);
	}

	write_float4(sockfd, label->rotation);
}


int E_AddGraphWindow(gw)
	struct GraphWindow *gw;
{
	if (firstGW == NULL) {
		firstGW = gw;
	}
	else {
		lastGW->next = gw;
	}

	lastGW = gw;
}


void E_PrintGraphWindows()
{
	struct GraphWindow *gw;

	gw = firstGW;

	while (gw != NULL) {
		E_PrintGraphWindow(gw);

		gw = gw->next;		
	}
}


void E_PrintGraphWindow(gw)
   struct GraphWindow *gw;
{
	int i;

	printf("GraphWindow %d\n",gw);
	printf("   %s\n",gw->windowName);
	printf("   nRows = %d\n",gw->nRows);
	printf("   nColumns = %d\n",gw->nColumns);
	printf("   nGraphs = %d\n",gw->nGraphsInList);

	for (i=0; i<gw->nGraphsInList; i++) {
		printf("      %d\n",gw->graphList[i]);
		printf("        title:   %s\n", gw->graphList[i]->titleLabel->text);/*add shortTitle?*/
		printf("        xLabel:  %s\n", gw->graphList[i]->xAxisLabel->text);
		printf("        yLabel:  %s\n", gw->graphList[i]->yAxisLabel->text);
	}

	printf("   next = %d\n",gw->next);
}


int E_AddGraph(graph)
	struct Graph *graph;
{
	struct Graph *g;

	if (firstGraph == NULL) {
		firstGraph = graph;
		  /* printf("firstGraph = %d\n",firstGraph); */
	}
	else {
		lastGraph->next = graph;
		  /* printf("lastGraph->next = %d\n",lastGraph->next); */
	}

	lastGraph = graph;

	  /* printf("E_AddGraph\n"); */
/*
	g = firstGraph;

	while (g != NULL) {
		printf("E_AddGraph:  %d %s\n", g, g->name);

		g = g->next;
	}
*/
}


struct Graph *E_GetGraph(name)
   char *name;
{
	struct Graph *graph;

	graph = firstGraph;

	while (graph != NULL) {
		if (strcmp(name,graph->name) == 0) {
			return(graph);
		}

		graph = graph->next;		
	}

	return(NULL);

}


struct GraphWindow *E_GetGraphWindow(name)
   char *name;
{
	struct GraphWindow *gw;

	gw = firstGW;

	while (gw != NULL) {
		if (strcmp(name,gw->windowName) == 0) {
			return(gw);
		}

		gw = gw->next;		
	}

	return(NULL);

}


int E_CreateFxDataset(dataset)
	struct FxDataset *dataset;
{
        struct FxDataset *target, *nextDataset;

	   /* printf("E_CreateFxDataset  = %s\n", dataset->name); */
/*
	target = firstFxDataset;

        while (target != NULL) {
                if (strcmp(target->name, dataset->name) == 0) {
			if (target == firstFxDataset) {
				firstFxDataset = dataset;
                        	nextDataset = target->next;
                        	target = dataset;
                        	target->next = nextDataset;
				break;
			}
			if (target == lastFxDataset) {
				lastFxDataset->next = dataset;
				lastFxDataset = dataset;
				break;
			}

                        return(1);
                }

                target = target->next;
        }
*/
	if (firstFxDataset == NULL) {
		firstFxDataset = dataset;
		    /* printf(" E_CreateFxDataset  firstFxDataset = %s\n",firstFxDataset->name); */
	}
	else {
		lastFxDataset->next = dataset;
		  /* printf(" E_CreateFxDataset  lastFxDataset = %s\n",lastFxDataset->name); */
	}

	lastFxDataset = dataset;
        return(1);
}

struct FxDataset *E_GetFxDataset(name)
   char *name;
{
	struct FxDataset *dataset;

	   /* printf("E_GetFxDataset %s\n", name); */

	dataset = firstFxDataset;

	while (dataset != NULL) {
	   	    /* printf("   E_GetFxDataset %s\n", dataset->name); */
		if (strcmp(name, dataset->name) == 0) {
	   		    /* printf("   E_GetFxDataset matched %s %d\n", name, dataset); */
			return(dataset);
		}

		dataset = dataset->next;
	}

	return(NULL);
}


struct FxDataset *E_GetFxDatasetID(id)
   int id;
{
	struct FxDataset *dataset;

	    /* printf("E_GetFxDatasetID %d\n", id); */

	dataset = firstFxDataset;

	while (dataset != NULL) {
	   	    /* printf("   E_GetFxDatasetID %s\n", dataset->name); */
		if (id == dataset->id) {
	   		    /* printf("   E_GetFxDatasetID matched %d %d\n", id, dataset); */
			return(dataset);
		}

		dataset = dataset->next;
	}

	return(NULL);
}


int E_CreateFxyDataset(dataset)
	struct FxyDataset *dataset;
{
	if (firstFxyDataset == NULL) {
		firstFxyDataset = dataset;
		   /* printf("E_CreateFxDataset  firstFxDataset = %d\n",firstFxDataset); */
	}
	else {
		lastFxyDataset->next = dataset;
		   /* printf("E_CreateFxDataset  lastFxDataset = %d\n",lastFxDataset); */
	}

	lastFxyDataset = dataset;
}

struct FxyDataset *E_GetFxyDataset(name)
   char *name;
{
	struct FxyDataset *dataset;

	dataset = firstFxyDataset;

	while (dataset != NULL) {
		if (strcmp(name, dataset->name) == 0) {
			return(dataset);
		}

		dataset = dataset->next;
	}

	return(NULL);
}

int E_CreateColumn(struct Column *col){
	if(firstColumn == NULL){
		firstColumn = col;
	}else{
		lastColumn->next = col;
	}
	
	lastColumn = col;
}

struct Column *E_GetColumn(char *name){
	struct Column *col;
	
	col = firstColumn;
	
	while(col != NULL){
		if(strcmp(name, col->name) == 0){
			return(col);
		}
		
		col = col->next;
	}
	
	return(NULL);
}

struct Column *E_GetColumnID(int id){
	struct Column *col;
	
	col = firstColumn;
	
	while(col != NULL){
		if(col->id == id){
			return(col);
		}
		
		col = col->next;
	}
	
	return(NULL);
}

int E_FreeColumns(){
	struct Column *col, *hold;
	
	col = firstColumn;
	
	while(col != NULL) {
		hold = col;
		col = col->next;
		E_Free(hold->name);
		E_Free(hold->header);
		E_Free(hold->cells);
		E_Free(hold->bgcolor);
		E_Free(hold->fontColor);
		E_Free(hold->fontName);
		E_Free(hold->fontStyle);
		E_Free(hold);
	}
	
	firstColumn = NULL;
	lastColumn = NULL;
}

void E_AddLabel(label)
	struct Label *label;
{
	if (firstLabel == NULL) {
		firstLabel = label;
	}
	else {
		lastLabel->next = label;
	}

	lastLabel = label;
}


void E_FreeLabels()
{
	struct Label *label, *hold;

	label = firstLabel;

	while (label != NULL) {
		hold = label;
		label = label->next;
		E_Free(hold->text);
		E_Free(hold->fontName);
		E_Free(hold->fontStyle);
		E_Free(hold);
	}

	firstLabel = NULL;
	lastLabel = NULL;
}


void E_FreeFxDatasets()
{
	struct FxDataset *fx, *hold;

	fx = firstFxDataset;

	while (fx != NULL) {
		hold = fx;
		fx = fx->next;
		E_Free(hold->name);
		E_Free(hold->x);
		E_Free(hold->fx);
		E_Free(hold);
	}

	firstFxDataset = NULL;
	lastFxDataset = NULL;
}


void E_FreeFxyDatasets()
{
	struct FxyDataset *fx, *hold;

	fx = firstFxyDataset;

	while (fx != NULL) {
		hold = fx;
		fx = fx->next;
		E_Free(hold->name);
		E_Free(hold->xcoords);
		E_Free(hold->ycoords);
		E_Free(hold->fxy);
		E_Free(hold);
	}

	firstFxyDataset = NULL;
	lastFxyDataset = NULL;
}

void E_FreeGraphs()
{
	struct Graph *graph, *hold;

	graph = firstGraph;

	while (graph != NULL) {
		hold = graph;
		graph = graph->next;
		E_Free(hold->name);
		E_Free(hold->labelList);
		E_Free(hold->fxDatasetList);
		E_Free(hold->columnList);
		E_Free(hold->topTextList);
		E_Free(hold->bottomTextList);
		E_Free(hold->shortTitle);
		E_Free(hold);
	}

	firstGraph = NULL;
	lastGraph = NULL;
}


void E_FreeGraphWindows()
{
	struct GraphWindow *gw, *hold;

	gw = firstGW;

	while (gw != NULL) {
		hold = gw;
		gw = gw->next;
		E_Free(hold->windowName);
		E_Free(hold->graphList);
		E_Free(hold);
	}

	firstGW = NULL;
	lastGW = NULL;
}


void E_Free(void *ptr)
{
	if (ptr != NULL) {
		free(ptr);
	}
}

void E_PrintColumns(){
	struct Column *col;
	
	col = firstColumn;
	
	while(col != NULL){
		E_PrintColumn(col);
		
		col = col->next;
	}
}

int E_PrintColumn(struct Column *col){
	int i;
	
	printf("Column %d\n", col);
	printf("   Name: %s\n", col->name);
	printf("   ID: %d\n", col->id);
	printf("   Header: %s\n", col->header);
	printf("   nCells = %d\n", col->nCells);
	printf("   Background Color:%s\n", col->bgcolor);
	printf("   Font Color:%s\n", col->fontColor);

	printf("   Cells:\n");
	for(i = 0; i<col->nCells;i++){
		printf("      %s\n", col->cells[i]);
	}
	
	printf("   Next = %d\n", col->next);
}

void E_PrintFxDatasets()
{
	struct FxDataset *d;

	d = firstFxDataset;

	while (d != NULL) {
		E_PrintFxDataset(d);

		d = d->next;		
	}
}

void E_PrintFxDataset(d)
   struct FxDataset *d;
{
	int i;

	printf("FxDataset %d\n",d);
	printf("   %s\n", d->name);
	printf("   nPoints = %d\n", d->nPoints);

	for (i=0; i<d->nPoints; i++) {
		printf("      %lf %lf\n", d->x[i], d->fx[i]);
	}

	printf("   next = %d\n",d->next);
}


void E_Strcat(char *first, char *second, char **cat) {
	int length;

	length = strlen(first) + strlen(second) + 1;
	  /* printf("length = %d\n", length); */

	*cat = malloc(length);

	strcpy(*cat, first);

	strcat(*cat, second);
	   /* printf("Strcat = %s\n", *cat); */
}


void e_close(int f) {
	if (f > 2) {
		shutdown(f, 2);
		close(f);
	}
}

/******************************************************************
 * initialize the socket
 * return socket descriptor. If failed return -1
 * if writing to GraphWindowFile return -2
 *
 * Update - B.Bariteau - 6/27/08 - This function now supports the
 * list implementation of the ELVIS_SERVER variable. It now has an
 * int parameter that acts as an array index to access either a file
 * descriptor or a hostname and port. All functions in graphwindow.c
 * have been changed to reflect this with an e_socket_initialize(0) call
 * except E_GraphWindowSendEML(), which uses a loop to get all of the
 * file descriptors and hostnames in the list. Also, this function uses
 * a new function in binio.c, binio_set_gwFile, which sets the gwFile
 * global variable so that the fileCreate and write_char methods can
 * be used to write to multiple outputs.
 ******************************************************************/
int e_socket_initialize(int jpath)
{
   int sockfd;
   char *hostname;
   char *rawport;
   int port;
   int status = -1;
   char systemString[128], localHost[128];
   int i;
   int optval = 1;
   int nTry = 0;
   int error_status;
   struct  hostent *h;
   struct sockaddr_in serv_addr;
   char *fname;

         /* printf("graphwindow::e_socket_initialize %d\n", jpath); 
            printf("  fileList = %d\n", fileList[jpath]);  
	    printf("    serverList = %s\n", serverList[jpath]); */

   if(strcmp(serverList[jpath], "filegen") == 0){
	fname = malloc(sizeof(char) * 500);
	sprintf(fname, "./%s--%s--%d.eml", application, id, getpid());
	fileList[jpath] = fopen(fname, "a");
   }

   if (fileList[jpath] != NULL) {
	   /* if hostname starts with / or . then write to file */
             /* printf("    Write to .gw file\n");  */
        binio_set_gwFile(fileList[jpath]);
	return -2;
   } else if ((serverList[jpath][0] == '\0' && fileList[jpath] == NULL) || serverList[jpath] == "localhost") {
        printf("    Try local host ...\n");

        gethostname(localHost, sizeof(localHost));
        hostname = localHost;
	binio_set_gwFile(NULL);
   } else {
	 hostname = serverList[jpath];

	 port = portList[jpath];

	 binio_set_gwFile(NULL);
   }

   if ((h=gethostbyname(hostname)) == NULL) {  		/* get the host info */
		   /* herror("gethostbyname"); */
         fprintf(stderr,"e_socket_initialize: gethostbyname(%s) failed.\n",hostname);
         return -1;
   }

     /* fill in the structure "serv_addr" with the address of the server to connect with */
   bzero((char *) &serv_addr, sizeof(serv_addr));
   serv_addr.sin_family = AF_INET;
   /* serv_addr.sin_addr.s_addr = inet_addr(inet_ntoa(*((struct in_addr *)h->h_addr))); */
   serv_addr.sin_addr.s_addr = inet_addr(inet_ntoa(*((struct in_addr *)h->h_addr_list[0])));
   serv_addr.sin_port = htons(port);

       /* printf("Host name  : %s  port =%d \n", h->h_name, port); */
       /*   printf("IP Address : %s\n",inet_ntoa(*((struct in_addr *)h->h_addr_list[0])));  */

     /* open a TCP socket (an Internet stream socket).  */
   if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
      printf("Can't open stream socket.\n");
      return -1;
   }

   status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
	 /* printf("status = %d sockfd = %d\n", status, sockfd);  */

   status = -1;

   while (status == -1 && nTry < 2) { 		/* connect to elvis */
   	status = connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
		error_status = errno;
		/* printf("error_status: %d %s\n",error_status, strerror(error_status)); */
      		/* printf("status %d %d\n", status, nTry); */
		 
	if (status == -1) {
      		   /* printf("Could not connect to ElVis on %s.\n", hostname); 
      		   printf("Retry connection.\n"); */
		/* sleep(1); */
		nTry++;
	}
   }

   if (status == 0) {
    	    /* printf("Connected to ElVis.\n"); */
   	return sockfd;
   } else {
      	/* printf("Could not connect to ElVis on %s.\n", hostname); */
	return -1;
   }
}

void xmlFixString(char s[]) {   /* set xmlS to adjusted string */
	size_t start;
	int i;

        strcpy(xmlS, s);

	for (i=0; i<strlen(xmlS); i++) {
		if (xmlS[i] == '&') {
			xmlInsert(i, "&amp;");
		}
	}

	for (i=0; i<strlen(xmlS); i++) {
		if (xmlS[i] == '<') {
			xmlInsert(i, "&lt;");
		} else if (xmlS[i] == '>') {
			xmlInsert(i, "&gt;");
		} else if (xmlS[i] == '\"') {
			xmlInsert(i, "&quot;");
		} else if (xmlS[i] == '\'') {
			xmlInsert(i, "&apos;");
                }                                                         
	}

          /* printf("%s\n", xmlS); */
}


void xmlInsert(int start, char replace[]) {
	char t[250];

          /* printf("%s %d\n", replace, start); */

	if (start == 0) {
		strcpy(t, replace);
          		/* printf("%s\n", t); */
	} else {
		strncpy(t, xmlS, start);
		t[start] = '\0';
          		/* printf("%s\n", t); */
		strcat(t, replace);
          		/* printf("%s\n", t); */
	}

	strcat(t, &xmlS[start + 1]);
	strcpy(xmlS, t);
        	/* printf("%s\n", xmlS); */
}

/*  old:  try to start elvis
		gethostname(localHost, sizeof(localHost));

		if (strcmp(localHost, hostname) == 0) {
      			printf("Starting ElVis locally.\n");
			system("elvis");
		}
		else {
      			printf("Starting ElVis on %s through ssh.\n", hostname);
			sprintf(systemString, "ssh -f -q %s elvis", hostname);
			system(systemString);
		}
*/
