Index: vtcross/branches/bhilburn/shell/cr_shell.cpp
===================================================================
--- vtcross/branches/bhilburn/shell/cr_shell.cpp	(revision 106)
+++ vtcross/branches/bhilburn/shell/cr_shell.cpp	(revision 106)
@@ -0,0 +1,791 @@
+#include <iostream>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#include "tinyxml.h"
+#include "tinystr.h"
+#include <arpa/inet.h>
+#include <sys/mman.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+
+//#include "socket/ServerSocket.h"
+//#include "socket/SocketException.h"
+
+using namespace std;
+
+#define CE_SERVER_PORT 30001
+#define POLICY_SERVER_PORT 30003
+
+struct CE_Info {
+	int numUtilities;
+	int numParameters;
+	int numObservables;
+    int policy_engine;
+    int policy_socket;
+    int ce_socket;
+};
+
+struct Utility {
+	string name;
+	string units;
+	string goal;
+	float target;
+    float value;
+};
+struct Affect {
+	Utility * u;
+	string relation;
+};
+struct Parameter {
+	string name;
+	string units;
+	float min;
+	int numAffects;
+	Affect affection_list[10];
+	float max;
+	float step;
+    float value;
+};
+
+struct Observable {
+	string name;
+	Affect affection_list[10];
+	int numAffects;
+    float value;
+};
+
+void DieWithError(char *errorMessage)
+{
+        perror(errorMessage);
+            exit(1);
+}
+
+void print_current_config(Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) {
+	int i = 0;
+	int j = 0;
+
+	for(i = 0; i < ce_info->numUtilities ; i++) {
+		cout << "Utility:  " << uList[i]->name << endl;
+		cout << "     Units:  " << uList[i]->units << endl;
+		cout << "     Goal:   " << uList[i]->goal << endl;
+		cout << "     Target: " << uList[i]->target << endl;
+	}
+
+	for(i = 0; i < ce_info->numParameters; i++) {
+		cout << "Parameter:  " << pList[i]->name << endl;
+	printf("Cognitive Radio:: Radio Operation Profile has been sucessfully sent.\n");
+		cout << "       Units:   " << pList[i]->units << endl;
+		cout << "       Min:     " << pList[i]->min << endl;
+		cout << "       Max:     " << pList[i]->max << endl;
+		cout << "       Step:    " << pList[i]->step << endl;
+		for(j = 0; j < pList[i]->numAffects; j++) {
+			cout << "       Affect: " << pList[i]->affection_list[j].u->name << " -> " << pList[i]->affection_list[j].relation << endl;
+		}
+	}
+	
+    for(i = 0; i < ce_info->numObservables; i++) {
+		cout << "Observable:  " << oList[i]->name << endl;
+		for(j = 0; j < oList[i]->numAffects; j++) {
+			cout << "       Affect: " << oList[i]->affection_list[j].u->name << " -> " << oList[i]->affection_list[j].relation << endl;
+		}
+	}
+}
+
+
+int parse_ce_config( TiXmlDocument * doc , Utility * u[], Parameter * p[], Observable * o[], CE_Info * ce_info) {
+
+	TiXmlElement* pElem;	//!current element
+	TiXmlElement* pChild;	//!current child of pElem
+	TiXmlElement* pChild1;	//!current child of pElem
+	TiXmlElement* pSecondChild;	//!current child of pElem
+	TiXmlHandle hDoc(doc);	//!handle to xml document
+	TiXmlHandle hRoot(0); //! handle to root element 
+
+	int count = 0;
+	int i = 0;
+	int j = 0;
+	int k = 0;
+	int match_found = 0;
+
+	pElem = hDoc.FirstChildElement().Element();
+	if(!pElem) { cout << "no valid root! quit-ing function!" << endl; return 0; }
+	hRoot = TiXmlHandle(pElem);
+
+	// Pull utility information from XML file.
+
+	pElem = hRoot.FirstChild("utilities").Element();
+	pChild1 = hRoot.Child("utilities",count).Element();
+
+
+	for(pChild = pChild1->FirstChildElement("utility"); pChild; pChild = pChild->NextSiblingElement())
+     	{
+		u[i] = new Utility;
+   		const char *uName = pChild->Attribute("name");
+   		if(uName) u[i]->name = uName;	
+		const char *uUnits = pChild->Attribute("units");
+   		if(uUnits) u[i]->units = uUnits;
+   		const char *uGoal = pChild->Attribute("goal");
+   		if(uGoal) u[i]->goal = uGoal;
+   		if(pChild->QueryFloatAttribute("target",&u[i]->target) != TIXML_SUCCESS) u[i]->target = -1;
+		i++;
+	}
+	ce_info->numUtilities = i;	
+	cout << "Initialize:: Parsed " << ce_info->numUtilities << " utilities." << endl;
+
+	// Pull observable information from XML file.
+	i = 0;
+	pElem = hRoot.FirstChild("observables").Element();
+	pChild1 = hRoot.Child("observables",count).Element();
+	
+	for(pChild = pChild1->FirstChildElement("observable"); pChild; pChild = pChild->NextSiblingElement())
+     	{
+
+   		const char *oName = pChild->Attribute("name");
+		o[i] = new Observable;
+
+   		if(oName) o[i]->name = oName;
+		
+		j = 0;
+		for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; pSecondChild = pSecondChild->NextSiblingElement())
+		{
+   			const char *oUtilName = pSecondChild->Attribute("utility");
+
+   			// If a utility affects this parameter find the utility object and assign it
+			if(oUtilName) {
+				// Search for correct utility
+				for( k=0 ; u[k]!=NULL ; k++ ){
+					if(u[k]->name == oUtilName) {
+						o[i]->affection_list[j].u = u[k];
+						// Set relationship
+						const char *oRelate = pSecondChild->Attribute("relationship");
+   						if(oRelate) o[i]->affection_list[j].relation = oRelate;
+						j++;
+						match_found = 1;
+				 		break;
+					}
+				}
+			}
+			if(!match_found) cout << "Error: " << o[i]->name << ": " << oUtilName << " not a valid utility: Affect not added." << endl;	
+			match_found = 0;	
+		}
+		o[i]->numAffects = j; 
+		i++;
+	}
+	ce_info->numObservables = i;	
+	cout << "Initialize:: Parsed " << ce_info->numObservables << " observables." << endl;
+	
+
+	// Pull parameter information from XML file.
+	pElem = hRoot.FirstChild("parameters").Element();
+	pChild1 = hRoot.Child("parameters",count).Element();
+	
+	i = 0;
+	for(pChild = pChild1->FirstChildElement("parameter"); pChild; pChild = pChild->NextSiblingElement())
+     	{
+		p[i] = new Parameter;
+
+		const char *pName = pChild->Attribute("name");
+   		if(pName) p[i]->name = pName;	
+		const char *pUnits = pChild->Attribute("units");
+   		if(pUnits) p[i]->units = pUnits;
+
+   		if(pChild->QueryFloatAttribute("min",&p[i]->min) != TIXML_SUCCESS) p[i]->min = -1;
+   		if(pChild->QueryFloatAttribute("max",&p[i]->max) != TIXML_SUCCESS) p[i]->max = -1;
+   		if(pChild->QueryFloatAttribute("step",&p[i]->step) != TIXML_SUCCESS) p[i]->step = -1;
+		
+		j = 0;
+		for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; pSecondChild = pSecondChild->NextSiblingElement())
+		{
+   			const char *pUtilName = pSecondChild->Attribute("utility");
+   			
+			// If a utility affects this parameter find the utility object and assign it
+			if(pUtilName) {
+				// Search for correct utility
+				for( k=0 ; u[k]!=NULL ; k++ ){
+					if(u[k]->name == pUtilName) {
+						// If match found, assign it to this index
+						p[i]->affection_list[j].u = u[k];	
+						const char *pRelate = pSecondChild->Attribute("relationship");
+   						if(pRelate) {
+							p[i]->affection_list[j].relation = pRelate;
+						} else {
+							cout << "Error: No relation found." << endl;
+						}
+						match_found = 1;
+						j++;
+						break;
+					}
+				}
+			}
+			if(!match_found) cout << "Error: " << p[i]->name << ": " << pUtilName << " not a valid utility: Affect not added." << endl;	
+			match_found = 0;	
+		}
+		p[i]->numAffects = j; 
+		i++;
+
+	}
+	ce_info->numParameters = i;	
+	cout << "Initialize:: Parsed " << ce_info->numParameters << " parameters." << endl;
+	return 1;
+}
+
+
+void error(char *msg)
+{
+    perror(msg);
+    exit(1);
+}
+
+
+int ReceiveMessage(int socket,char * buffer) 
+{
+    int i,n;
+   
+    n = recv(socket,buffer,256,MSG_PEEK);
+    
+    for(i=0;i<256;i++){
+        if(strcmp(&buffer[i],"\0") == 0) break;
+    }
+    n = recv(socket,buffer,i+1,0);
+    if (n < 0)
+        error("ERROR reading from socket");
+    //    printf("ReadMessage:%s %d\n",buffer,n);
+
+    return n;
+}
+
+
+int SendMessage(int socketfd, string message) {
+	int n;
+
+	message.append("\0");	
+	// Write message back to client
+    n = send(socketfd,message.c_str(),(message.size()+1),0);
+    if (n<0)
+        error("Error sending to client\n");
+    if(n == 0)
+        printf("Client closed the socket.\n");
+
+	//printf("SendMessage:%s %d\n",message.c_str(),n);	
+    return n;
+}
+
+void GetEnvironment() {
+
+}
+
+void Policy_ValidateSettings() {
+
+}
+
+
+void LoadCEConfiguration(int socketfd,Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info){
+	int n,i,j;
+	char counter[55];
+	char var[50];
+	//int total_bytes;   
+
+	printf("Cognitive Radio:: Sending Radio Operating Profile to Cognitive Engine.\n\n");
+ 
+ 	// utilities
+	// Send number of utilities
+	sprintf(counter,"%d",ce_info->numUtilities);
+	SendMessage(socketfd,counter);
+	// send utility	
+    for(i = 0; i < ce_info->numUtilities; i++) {
+		SendMessage(socketfd,uList[i]->name);
+		SendMessage(socketfd,uList[i]->units);
+		SendMessage(socketfd,uList[i]->goal);
+		sprintf(var,"%f",uList[i]->target);
+		SendMessage(socketfd,var);
+	}
+
+	// parameters
+    sprintf(counter,"%i",ce_info->numParameters);
+	SendMessage(socketfd,counter);
+	for(i = 0; i < ce_info->numParameters; i++) {
+		SendMessage(socketfd,pList[i]->name);
+		SendMessage(socketfd,pList[i]->units);
+		sprintf(var,"%f",pList[i]->min);
+		SendMessage(socketfd,var);
+		sprintf(var,"%f",pList[i]->max);
+		SendMessage(socketfd,var);
+		sprintf(var,"%f",pList[i]->step);
+		SendMessage(socketfd,var);
+		
+		sprintf(counter,"%i",pList[i]->numAffects); 
+		SendMessage(socketfd,counter);
+		for(j = 0; j < pList[i]->numAffects; j++) {
+			SendMessage(socketfd,pList[i]->affection_list[j].u->name);
+			SendMessage(socketfd,pList[i]->affection_list[j].relation);
+		}
+	}
+
+    // observables
+	sprintf(counter,"%i",ce_info->numObservables);
+	SendMessage(socketfd,counter);
+	for(i = 0; i < ce_info->numObservables; i++) {
+		SendMessage(socketfd,oList[i]->name);
+		
+		sprintf(counter,"%i",oList[i]->numAffects); 
+		SendMessage(socketfd,counter);
+		for(j = 0; j < oList[i]->numAffects; j++) {
+			SendMessage(socketfd,oList[i]->affection_list[j].u->name);
+			SendMessage(socketfd,oList[i]->affection_list[j].relation);
+		}
+	}
+	
+	// Receive ACK for utils
+    char buffer[256];
+        string message;
+	n = ReceiveMessage(socketfd, buffer);
+    //printf("%s\n", buffer);
+        //cout << message << endl;
+	//printf("ACK received.\n");
+
+}
+
+void UpdateCEConfiguration() {
+
+}
+
+void ResetCEConfiguration(){
+
+}
+
+void UpdateCEExperience(int socketfd, int num_rows, int num_cols, 
+        float * past_exp[]) 
+{
+    int i, j;
+	char counter[55];
+	char var[50];
+
+    for (i = 0; i < num_rows; i++){
+        for (j = 0; j< num_cols; j++){
+		sprintf(var,"%f",past_exp[i][j]);
+        //printf("%f, \n", past_exp[i][j]);
+        //printf("%s, \n", var);
+        }
+    }
+    
+    // send the number of rows to the ce first
+	sprintf(counter,"%d",num_rows);
+	SendMessage(socketfd,counter);
+    // send the number of columns to the ce
+	sprintf(counter,"%d",num_cols);
+	SendMessage(socketfd,counter);
+    // update ce with experience
+    for (i = 0; i < num_rows; i++){
+        for (j = 0; j< num_cols; j++){
+		sprintf(var,"%f",past_exp[i][j]);
+		SendMessage(socketfd,var);
+        }
+    }
+
+}
+
+void ResetCEExperience() {
+
+}
+
+// Update operating settings
+// This function will interact with the hardware "drivers"
+void UpdateRadioSettings() 
+{
+}
+
+
+int RequestPolicyValidation(Parameter * pList[], CE_Info *ce_info)
+{
+	char counter[55];
+	char var[50];
+    int i;
+    string control_msg;
+    
+    int socketfd = ce_info->policy_socket;
+
+    // Control message that validation request is coming
+    control_msg = "val";
+	SendMessage(socketfd,control_msg);
+
+    printf("Cognitive Radio:: Here. %i\n\n", socketfd);
+
+	// Send parameter information 
+    sprintf(counter,"%i",ce_info->numParameters);
+	SendMessage(socketfd,counter);
+	for(i = 0; i < ce_info->numParameters; i++) {
+		SendMessage(socketfd,pList[i]->name);
+		SendMessage(socketfd,pList[i]->units);
+		sprintf(var,"%f",pList[i]->min);
+		SendMessage(socketfd,var);
+		sprintf(var,"%f",pList[i]->max);
+		SendMessage(socketfd,var);
+		sprintf(var,"%f",pList[i]->step);
+		SendMessage(socketfd,var);
+		sprintf(var,"%f",pList[i]->value);
+		SendMessage(socketfd,var);
+		
+	}
+    return 1;
+
+}
+
+
+int RequestCEOptimization(int sockfd, Utility *uList[], 
+        Parameter *pList[], Observable *oList[],
+        CE_Info *ce_info)
+{
+    char buffer[256];
+    int i;
+    float var;
+
+    // Send request optimization message followed by the current environment parameters.
+    /*
+    SendMessage(sockfd,"request"); 
+    for (i = 0; i < ce_info->numObservables; i++){
+        SendMessage(sockfd,..);
+    }
+    */
+
+    // Receive optimized values from the Cognitive Engine 
+    for (i = 0; i < ce_info->numParameters; i++){
+        bzero(buffer,256);
+        ReceiveMessage(sockfd,buffer);
+        var = atof(buffer);
+        pList[i]->value = var;
+    }
+
+
+    // If policy engine is connect, validate new values
+    if(ce_info->policy_engine == 1) {
+
+        printf("Cognitive Radio:: Found Policy Engine!\n");
+        printf("Cognitive Radio:: Validating parameters with Policy Engine\n\n");
+        RequestPolicyValidation(pList,ce_info); 
+        printf("Cognitive Radio:: Done\n\n");
+
+    }
+
+
+    return 1;
+}
+
+void RunSimulator(int socketfd, Utility * uList[], 
+        Parameter * pList[], Observable * oList[], 
+        CE_Info * ce_info) {
+	
+	float **past_exp;
+    int num_rows, num_cols;
+
+	// Set fake current environment params = current environment
+	RequestCEOptimization(socketfd, uList, pList, oList, ce_info);
+
+	// Act like we are updating the hardware tranmission settings
+	UpdateRadioSettings();
+
+	// Send back fake utility values
+    // need to initialize
+	//UpdateCEExperience(socketfd, num_rows, num_cols, past_exp);	
+}
+
+void InitializePE(int socket, CE_Info * ce_info) 
+{
+    // Policy Engine is connected
+    // Set global policy engine value to 1
+    ce_info->policy_engine = 1;
+    ce_info->policy_socket = socket;
+
+    return;
+}
+
+void InitializeCE(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) 
+{
+	LoadCEConfiguration(socketfd, uList, pList, oList, ce_info);
+	
+    // cr experience
+    float **past_exp;
+	int num_cols;
+    // get number of columns
+    num_cols = ce_info->numUtilities + ce_info->numParameters;
+    num_cols = num_cols + ce_info->numObservables;
+    num_cols = num_cols + 1;    // overall utility
+    int num_rows = 2;
+    past_exp = (float **)malloc(sizeof(float)*num_rows);
+    int i;
+    for (i=0; i<num_rows; i++){
+        past_exp[i] = (float*)malloc(sizeof(float)*num_cols);
+    }
+    // sample experience #1
+    past_exp[0][0] = 1e3f;  // throughput
+    past_exp[0][1] = 1;     // spectral_efficiency
+    past_exp[0][2] = -3.5;  // log10_ber
+    past_exp[0][3] = 1;     // mod_scheme
+    past_exp[0][4] = -10;   // tx_power
+    past_exp[0][5] = 10.0;  // SNR
+    past_exp[0][6] = 0.762; // overall utility*/
+    // sample experience #2
+    past_exp[1][0] = 1e2f;  // throughput
+    past_exp[1][1] = 1;     // spectral_efficiency
+    past_exp[1][2] = -3.5;  // log10_ber
+    past_exp[1][3] = 1;     // mod_scheme
+    past_exp[1][4] = -14;   // tx_power
+    past_exp[1][5] = 3.0;   // SNR
+    past_exp[1][6] = 0.462; // overall utility
+
+	// update ce with experience
+    printf("Cognitive Radio:: Sending Previous Experience to New Cognitive Engine.\n\n");
+    UpdateCEExperience(socketfd, num_rows, num_cols, past_exp);	
+
+	RunSimulator(socketfd, uList, pList, oList, ce_info);
+}
+
+int AcceptTCPConnection(int servSock)
+{
+    int clntSock;                    /* Socket descriptor for client */
+    struct sockaddr_in echoClntAddr;
+    unsigned int clntLen;
+
+    /* Set the size of the in-out parameter */
+    clntLen = sizeof(echoClntAddr);
+
+    /* Wait for a client to connect */
+    //if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) {
+    if ((clntSock = accept(servSock, NULL, NULL)) < 0) {
+        return -1;
+    } 
+   
+    /* clntSock is connected to a client! */
+    
+    printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));
+
+    return clntSock;
+}
+
+int CreateTCPServerSocket(unsigned short port)
+{
+    int sock;                        /* socket to create */
+    struct sockaddr_in echoServAddr; /* Local address */
+
+    /* Create socket for incoming connections */
+    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
+        DieWithError("socket() failed");
+      
+    /* Construct local address structure */
+    memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */
+    echoServAddr.sin_family = AF_INET;                /* Internet address family */
+    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
+    echoServAddr.sin_port = htons(port);              /* Local port */
+
+    /* Bind to the local address */
+    if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
+        DieWithError("bind() failed");
+
+    /* Mark the socket so it will listen for incoming connections */
+    if (listen(sock, 5) < 0) {
+        printf("listen() failed\n");
+        return 0;
+    }
+
+    return sock;
+}
+
+void HandleTCPClient(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) 
+{
+    char buffer[256];        /* Buffer for echo string */
+
+    /* Receive message from client */
+    bzero(buffer,256);
+    ReceiveMessage(socketfd,buffer);
+
+    printf("Cognitive Radio:: Message Received - %s.\n\n", buffer);
+
+    if(strcmp(buffer,"c_register") == 0) 
+	    InitializeCE(socketfd, uList, pList, oList, ce_info);
+
+    if(strcmp(buffer,"p_register") == 0)
+	    InitializePE(socketfd, ce_info);
+
+    if(strcmp(buffer,"optimize") == 0)
+	    RunSimulator(socketfd, uList, pList, oList, ce_info);
+        
+    //close(socketfd);    /* Close client socket */
+}
+
+int StartServers(Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) {
+    int * servSock; 
+    int running = 1;
+    struct timeval selTimeout;
+    int timeout = 10;
+    int cognitive_engine = 0; 
+    int policy_engine = 1; 
+    int port, rc, on = 1;
+    int new_sd;
+    int desc_ready = 0;
+    fd_set sockSet;
+    
+    servSock = (int *) malloc(2 * sizeof(int));
+
+    servSock[cognitive_engine] = CreateTCPServerSocket(CE_SERVER_PORT);
+    servSock[policy_engine] = CreateTCPServerSocket(POLICY_SERVER_PORT);
+
+
+    int maxDescriptor = servSock[cognitive_engine];
+
+    if(servSock[cognitive_engine] < servSock[policy_engine])
+        maxDescriptor = servSock[policy_engine];
+
+    rc = setsockopt(servSock[cognitive_engine], SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
+    if(rc < 0)
+    {
+        perror("setsockopt() failed");
+        close(servSock[cognitive_engine]);
+        exit(-1);
+    }
+    
+    rc = setsockopt(servSock[policy_engine], SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
+    if(rc < 0)
+    {
+        perror("setsockopt() failed");
+        close(servSock[policy_engine]);
+        exit(-1);
+    }
+    
+    rc = ioctl(servSock[cognitive_engine], FIONBIO, (char*)&on);
+    if(rc < 0)
+    {
+        perror("ioctl() failed");
+        close(servSock[cognitive_engine]);
+        exit(-1);
+    }
+    
+    rc = ioctl(servSock[policy_engine], FIONBIO, (char*)&on);
+    if(rc < 0)
+    {
+        perror("ioctl() failed");
+        close(servSock[policy_engine]);
+        exit(-1);
+    }
+    
+    printf("Starting server:  Hit return to shutdown\n");
+    while (running)
+    {
+        /* Zero socket descriptor vector and set for server sockets */
+        /* This must be reset every time select() is called */
+        FD_ZERO(&sockSet);
+        /* Add keyboard to descriptor vector */
+        FD_SET(STDIN_FILENO, &sockSet);
+        FD_SET(servSock[cognitive_engine], &sockSet);
+        FD_SET(servSock[policy_engine], &sockSet);
+
+        /* Timeout specification */
+        /* This must be reset every time select() is called */
+        selTimeout.tv_sec = timeout;       /* timeout (secs.) */
+        selTimeout.tv_usec = 0;            /* 0 microseconds */
+
+        /* Suspend program until descriptor is ready or timeout */
+        rc = select(maxDescriptor + 1, &sockSet, NULL, NULL, &selTimeout); 
+        if (rc == 0)
+            printf("No echo requests for %i secs...Server still alive\n", timeout);
+        else 
+        {
+            if (FD_ISSET(0, &sockSet)) /* Check keyboard */
+            {
+                printf("Shutting down server\n");
+                getchar();
+                running = 0;
+            }
+
+            desc_ready = rc;
+
+            for (port = 0; port <= maxDescriptor && desc_ready > 0; port++) {
+                if (FD_ISSET(port, &sockSet))
+                {
+                    printf("Request on port %d:  ", port);
+	                desc_ready -= 1;
+
+
+                    if( (port == servSock[cognitive_engine]) || (port == servSock[policy_engine])) { 
+                       
+                        do
+                        { 
+                            new_sd = AcceptTCPConnection(port);
+                            if(new_sd < 0) 
+                            {
+                                break;
+                            }
+                            
+                            HandleTCPClient(new_sd, uList, pList, oList, ce_info);
+                            FD_SET(new_sd,&sockSet);
+                            if(new_sd > maxDescriptor) 
+                                maxDescriptor = new_sd;
+                            printf("New incoming connection - %i\n\n",new_sd);
+                        } while(new_sd != -1);
+                    } else {
+                        
+                        printf("Request on already open descriptor.\n\n");
+                        HandleTCPClient(port, uList, pList, oList, ce_info);
+
+                    }
+
+                }
+            }
+        }
+    }
+
+    /* Close sockets */
+    for (port = 0; port < 2; port++)
+        close(servSock[port]);
+
+    /* Free list of sockets */
+    free(servSock);        
+        
+	return 0;
+}
+
+int main(int argc, char* argv[]) {
+
+
+	// CognitiveEngine CE;
+	// CognitiveEngineShell Shell;
+	string pFilename; 
+    int fd;
+
+	Utility * uList[10];
+	Parameter * pList[10];
+	Observable * oList[10];
+	struct CE_Info *ce_info;
+
+    if((fd = open("/dev/zero", O_RDWR)) == -1)
+            return 1;
+
+    ce_info = (struct CE_Info *)mmap(0,sizeof(CE_Info),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
+
+    close(fd);
+
+	if(argc < 2) { 
+		cout << "Warning no XML file specific using default: example.xml" << endl;
+		pFilename = "example.xml";
+	} else {  
+		pFilename = argv[1];
+	}
+
+	TiXmlDocument doc( pFilename.c_str() );
+	bool loadOkay = doc.LoadFile();
+	if (!loadOkay)
+	{
+		cout << "Loading " << pFilename << " failed." << endl;
+		return 0;
+	}
+
+	cout << "\n\nInitialize:: Attemping to parse " << pFilename << "." << endl;
+	parse_ce_config( &doc , uList, pList, oList, ce_info);
+	cout << "Initialize:: Configuration file parsing completed.\n" << endl;
+
+    //print_current_config(uList, pList, oList, &ce_info);
+	
+   StartServers(uList, pList, oList, ce_info);
+   return 1;
+}
Index: vtcross/branches/bhilburn/shell/main_cognitive_radio.cpp
===================================================================
--- vtcross/branches/bhilburn/shell/main_cognitive_radio.cpp	(revision 105)
+++ 	(revision )
@@ -1,791 +1,0 @@
-#include <iostream>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netdb.h>
-#include "tinyxml.h"
-#include "tinystr.h"
-#include <arpa/inet.h>
-#include <sys/mman.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-
-//#include "socket/ServerSocket.h"
-//#include "socket/SocketException.h"
-
-using namespace std;
-
-#define CE_SERVER_PORT 30001
-#define POLICY_SERVER_PORT 30003
-
-struct CE_Info {
-	int numUtilities;
-	int numParameters;
-	int numObservables;
-    int policy_engine;
-    int policy_socket;
-    int ce_socket;
-};
-
-struct Utility {
-	string name;
-	string units;
-	string goal;
-	float target;
-    float value;
-};
-struct Affect {
-	Utility * u;
-	string relation;
-};
-struct Parameter {
-	string name;
-	string units;
-	float min;
-	int numAffects;
-	Affect affection_list[10];
-	float max;
-	float step;
-    float value;
-};
-
-struct Observable {
-	string name;
-	Affect affection_list[10];
-	int numAffects;
-    float value;
-};
-
-void DieWithError(char *errorMessage)
-{
-        perror(errorMessage);
-            exit(1);
-}
-
-void print_current_config(Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) {
-	int i = 0;
-	int j = 0;
-
-	for(i = 0; i < ce_info->numUtilities ; i++) {
-		cout << "Utility:  " << uList[i]->name << endl;
-		cout << "     Units:  " << uList[i]->units << endl;
-		cout << "     Goal:   " << uList[i]->goal << endl;
-		cout << "     Target: " << uList[i]->target << endl;
-	}
-
-	for(i = 0; i < ce_info->numParameters; i++) {
-		cout << "Parameter:  " << pList[i]->name << endl;
-	printf("Cognitive Radio:: Radio Operation Profile has been sucessfully sent.\n");
-		cout << "       Units:   " << pList[i]->units << endl;
-		cout << "       Min:     " << pList[i]->min << endl;
-		cout << "       Max:     " << pList[i]->max << endl;
-		cout << "       Step:    " << pList[i]->step << endl;
-		for(j = 0; j < pList[i]->numAffects; j++) {
-			cout << "       Affect: " << pList[i]->affection_list[j].u->name << " -> " << pList[i]->affection_list[j].relation << endl;
-		}
-	}
-	
-    for(i = 0; i < ce_info->numObservables; i++) {
-		cout << "Observable:  " << oList[i]->name << endl;
-		for(j = 0; j < oList[i]->numAffects; j++) {
-			cout << "       Affect: " << oList[i]->affection_list[j].u->name << " -> " << oList[i]->affection_list[j].relation << endl;
-		}
-	}
-}
-
-
-int parse_ce_config( TiXmlDocument * doc , Utility * u[], Parameter * p[], Observable * o[], CE_Info * ce_info) {
-
-	TiXmlElement* pElem;	//!current element
-	TiXmlElement* pChild;	//!current child of pElem
-	TiXmlElement* pChild1;	//!current child of pElem
-	TiXmlElement* pSecondChild;	//!current child of pElem
-	TiXmlHandle hDoc(doc);	//!handle to xml document
-	TiXmlHandle hRoot(0); //! handle to root element 
-
-	int count = 0;
-	int i = 0;
-	int j = 0;
-	int k = 0;
-	int match_found = 0;
-
-	pElem = hDoc.FirstChildElement().Element();
-	if(!pElem) { cout << "no valid root! quit-ing function!" << endl; return 0; }
-	hRoot = TiXmlHandle(pElem);
-
-	// Pull utility information from XML file.
-
-	pElem = hRoot.FirstChild("utilities").Element();
-	pChild1 = hRoot.Child("utilities",count).Element();
-
-
-	for(pChild = pChild1->FirstChildElement("utility"); pChild; pChild = pChild->NextSiblingElement())
-     	{
-		u[i] = new Utility;
-   		const char *uName = pChild->Attribute("name");
-   		if(uName) u[i]->name = uName;	
-		const char *uUnits = pChild->Attribute("units");
-   		if(uUnits) u[i]->units = uUnits;
-   		const char *uGoal = pChild->Attribute("goal");
-   		if(uGoal) u[i]->goal = uGoal;
-   		if(pChild->QueryFloatAttribute("target",&u[i]->target) != TIXML_SUCCESS) u[i]->target = -1;
-		i++;
-	}
-	ce_info->numUtilities = i;	
-	cout << "Initialize:: Parsed " << ce_info->numUtilities << " utilities." << endl;
-
-	// Pull observable information from XML file.
-	i = 0;
-	pElem = hRoot.FirstChild("observables").Element();
-	pChild1 = hRoot.Child("observables",count).Element();
-	
-	for(pChild = pChild1->FirstChildElement("observable"); pChild; pChild = pChild->NextSiblingElement())
-     	{
-
-   		const char *oName = pChild->Attribute("name");
-		o[i] = new Observable;
-
-   		if(oName) o[i]->name = oName;
-		
-		j = 0;
-		for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; pSecondChild = pSecondChild->NextSiblingElement())
-		{
-   			const char *oUtilName = pSecondChild->Attribute("utility");
-
-   			// If a utility affects this parameter find the utility object and assign it
-			if(oUtilName) {
-				// Search for correct utility
-				for( k=0 ; u[k]!=NULL ; k++ ){
-					if(u[k]->name == oUtilName) {
-						o[i]->affection_list[j].u = u[k];
-						// Set relationship
-						const char *oRelate = pSecondChild->Attribute("relationship");
-   						if(oRelate) o[i]->affection_list[j].relation = oRelate;
-						j++;
-						match_found = 1;
-				 		break;
-					}
-				}
-			}
-			if(!match_found) cout << "Error: " << o[i]->name << ": " << oUtilName << " not a valid utility: Affect not added." << endl;	
-			match_found = 0;	
-		}
-		o[i]->numAffects = j; 
-		i++;
-	}
-	ce_info->numObservables = i;	
-	cout << "Initialize:: Parsed " << ce_info->numObservables << " observables." << endl;
-	
-
-	// Pull parameter information from XML file.
-	pElem = hRoot.FirstChild("parameters").Element();
-	pChild1 = hRoot.Child("parameters",count).Element();
-	
-	i = 0;
-	for(pChild = pChild1->FirstChildElement("parameter"); pChild; pChild = pChild->NextSiblingElement())
-     	{
-		p[i] = new Parameter;
-
-		const char *pName = pChild->Attribute("name");
-   		if(pName) p[i]->name = pName;	
-		const char *pUnits = pChild->Attribute("units");
-   		if(pUnits) p[i]->units = pUnits;
-
-   		if(pChild->QueryFloatAttribute("min",&p[i]->min) != TIXML_SUCCESS) p[i]->min = -1;
-   		if(pChild->QueryFloatAttribute("max",&p[i]->max) != TIXML_SUCCESS) p[i]->max = -1;
-   		if(pChild->QueryFloatAttribute("step",&p[i]->step) != TIXML_SUCCESS) p[i]->step = -1;
-		
-		j = 0;
-		for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; pSecondChild = pSecondChild->NextSiblingElement())
-		{
-   			const char *pUtilName = pSecondChild->Attribute("utility");
-   			
-			// If a utility affects this parameter find the utility object and assign it
-			if(pUtilName) {
-				// Search for correct utility
-				for( k=0 ; u[k]!=NULL ; k++ ){
-					if(u[k]->name == pUtilName) {
-						// If match found, assign it to this index
-						p[i]->affection_list[j].u = u[k];	
-						const char *pRelate = pSecondChild->Attribute("relationship");
-   						if(pRelate) {
-							p[i]->affection_list[j].relation = pRelate;
-						} else {
-							cout << "Error: No relation found." << endl;
-						}
-						match_found = 1;
-						j++;
-						break;
-					}
-				}
-			}
-			if(!match_found) cout << "Error: " << p[i]->name << ": " << pUtilName << " not a valid utility: Affect not added." << endl;	
-			match_found = 0;	
-		}
-		p[i]->numAffects = j; 
-		i++;
-
-	}
-	ce_info->numParameters = i;	
-	cout << "Initialize:: Parsed " << ce_info->numParameters << " parameters." << endl;
-	return 1;
-}
-
-
-void error(char *msg)
-{
-    perror(msg);
-    exit(1);
-}
-
-
-int ReceiveMessage(int socket,char * buffer) 
-{
-    int i,n;
-   
-    n = recv(socket,buffer,256,MSG_PEEK);
-    
-    for(i=0;i<256;i++){
-        if(strcmp(&buffer[i],"\0") == 0) break;
-    }
-    n = recv(socket,buffer,i+1,0);
-    if (n < 0)
-        error("ERROR reading from socket");
-    //    printf("ReadMessage:%s %d\n",buffer,n);
-
-    return n;
-}
-
-
-int SendMessage(int socketfd, string message) {
-	int n;
-
-	message.append("\0");	
-	// Write message back to client
-    n = send(socketfd,message.c_str(),(message.size()+1),0);
-    if (n<0)
-        error("Error sending to client\n");
-    if(n == 0)
-        printf("Client closed the socket.\n");
-
-	//printf("SendMessage:%s %d\n",message.c_str(),n);	
-    return n;
-}
-
-void GetEnvironment() {
-
-}
-
-void Policy_ValidateSettings() {
-
-}
-
-
-void LoadCEConfiguration(int socketfd,Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info){
-	int n,i,j;
-	char counter[55];
-	char var[50];
-	//int total_bytes;   
-
-	printf("Cognitive Radio:: Sending Radio Operating Profile to Cognitive Engine.\n\n");
- 
- 	// utilities
-	// Send number of utilities
-	sprintf(counter,"%d",ce_info->numUtilities);
-	SendMessage(socketfd,counter);
-	// send utility	
-    for(i = 0; i < ce_info->numUtilities; i++) {
-		SendMessage(socketfd,uList[i]->name);
-		SendMessage(socketfd,uList[i]->units);
-		SendMessage(socketfd,uList[i]->goal);
-		sprintf(var,"%f",uList[i]->target);
-		SendMessage(socketfd,var);
-	}
-
-	// parameters
-    sprintf(counter,"%i",ce_info->numParameters);
-	SendMessage(socketfd,counter);
-	for(i = 0; i < ce_info->numParameters; i++) {
-		SendMessage(socketfd,pList[i]->name);
-		SendMessage(socketfd,pList[i]->units);
-		sprintf(var,"%f",pList[i]->min);
-		SendMessage(socketfd,var);
-		sprintf(var,"%f",pList[i]->max);
-		SendMessage(socketfd,var);
-		sprintf(var,"%f",pList[i]->step);
-		SendMessage(socketfd,var);
-		
-		sprintf(counter,"%i",pList[i]->numAffects); 
-		SendMessage(socketfd,counter);
-		for(j = 0; j < pList[i]->numAffects; j++) {
-			SendMessage(socketfd,pList[i]->affection_list[j].u->name);
-			SendMessage(socketfd,pList[i]->affection_list[j].relation);
-		}
-	}
-
-    // observables
-	sprintf(counter,"%i",ce_info->numObservables);
-	SendMessage(socketfd,counter);
-	for(i = 0; i < ce_info->numObservables; i++) {
-		SendMessage(socketfd,oList[i]->name);
-		
-		sprintf(counter,"%i",oList[i]->numAffects); 
-		SendMessage(socketfd,counter);
-		for(j = 0; j < oList[i]->numAffects; j++) {
-			SendMessage(socketfd,oList[i]->affection_list[j].u->name);
-			SendMessage(socketfd,oList[i]->affection_list[j].relation);
-		}
-	}
-	
-	// Receive ACK for utils
-    char buffer[256];
-        string message;
-	n = ReceiveMessage(socketfd, buffer);
-    //printf("%s\n", buffer);
-        //cout << message << endl;
-	//printf("ACK received.\n");
-
-}
-
-void UpdateCEConfiguration() {
-
-}
-
-void ResetCEConfiguration(){
-
-}
-
-void UpdateCEExperience(int socketfd, int num_rows, int num_cols, 
-        float * past_exp[]) 
-{
-    int i, j;
-	char counter[55];
-	char var[50];
-
-    for (i = 0; i < num_rows; i++){
-        for (j = 0; j< num_cols; j++){
-		sprintf(var,"%f",past_exp[i][j]);
-        //printf("%f, \n", past_exp[i][j]);
-        //printf("%s, \n", var);
-        }
-    }
-    
-    // send the number of rows to the ce first
-	sprintf(counter,"%d",num_rows);
-	SendMessage(socketfd,counter);
-    // send the number of columns to the ce
-	sprintf(counter,"%d",num_cols);
-	SendMessage(socketfd,counter);
-    // update ce with experience
-    for (i = 0; i < num_rows; i++){
-        for (j = 0; j< num_cols; j++){
-		sprintf(var,"%f",past_exp[i][j]);
-		SendMessage(socketfd,var);
-        }
-    }
-
-}
-
-void ResetCEExperience() {
-
-}
-
-// Update operating settings
-// This function will interact with the hardware "drivers"
-void UpdateRadioSettings() 
-{
-}
-
-
-int RequestPolicyValidation(Parameter * pList[], CE_Info *ce_info)
-{
-	char counter[55];
-	char var[50];
-    int i;
-    string control_msg;
-    
-    int socketfd = ce_info->policy_socket;
-
-    // Control message that validation request is coming
-    control_msg = "val";
-	SendMessage(socketfd,control_msg);
-
-    printf("Cognitive Radio:: Here. %i\n\n", socketfd);
-
-	// Send parameter information 
-    sprintf(counter,"%i",ce_info->numParameters);
-	SendMessage(socketfd,counter);
-	for(i = 0; i < ce_info->numParameters; i++) {
-		SendMessage(socketfd,pList[i]->name);
-		SendMessage(socketfd,pList[i]->units);
-		sprintf(var,"%f",pList[i]->min);
-		SendMessage(socketfd,var);
-		sprintf(var,"%f",pList[i]->max);
-		SendMessage(socketfd,var);
-		sprintf(var,"%f",pList[i]->step);
-		SendMessage(socketfd,var);
-		sprintf(var,"%f",pList[i]->value);
-		SendMessage(socketfd,var);
-		
-	}
-    return 1;
-
-}
-
-
-int RequestCEOptimization(int sockfd, Utility *uList[], 
-        Parameter *pList[], Observable *oList[],
-        CE_Info *ce_info)
-{
-    char buffer[256];
-    int i;
-    float var;
-
-    // Send request optimization message followed by the current environment parameters.
-    /*
-    SendMessage(sockfd,"request"); 
-    for (i = 0; i < ce_info->numObservables; i++){
-        SendMessage(sockfd,..);
-    }
-    */
-
-    // Receive optimized values from the Cognitive Engine 
-    for (i = 0; i < ce_info->numParameters; i++){
-        bzero(buffer,256);
-        ReceiveMessage(sockfd,buffer);
-        var = atof(buffer);
-        pList[i]->value = var;
-    }
-
-
-    // If policy engine is connect, validate new values
-    if(ce_info->policy_engine == 1) {
-
-        printf("Cognitive Radio:: Found Policy Engine!\n");
-        printf("Cognitive Radio:: Validating parameters with Policy Engine\n\n");
-        RequestPolicyValidation(pList,ce_info); 
-        printf("Cognitive Radio:: Done\n\n");
-
-    }
-
-
-    return 1;
-}
-
-void RunSimulator(int socketfd, Utility * uList[], 
-        Parameter * pList[], Observable * oList[], 
-        CE_Info * ce_info) {
-	
-	float **past_exp;
-    int num_rows, num_cols;
-
-	// Set fake current environment params = current environment
-	RequestCEOptimization(socketfd, uList, pList, oList, ce_info);
-
-	// Act like we are updating the hardware tranmission settings
-	UpdateRadioSettings();
-
-	// Send back fake utility values
-    // need to initialize
-	//UpdateCEExperience(socketfd, num_rows, num_cols, past_exp);	
-}
-
-void InitializePE(int socket, CE_Info * ce_info) 
-{
-    // Policy Engine is connected
-    // Set global policy engine value to 1
-    ce_info->policy_engine = 1;
-    ce_info->policy_socket = socket;
-
-    return;
-}
-
-void InitializeCE(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) 
-{
-	LoadCEConfiguration(socketfd, uList, pList, oList, ce_info);
-	
-    // cr experience
-    float **past_exp;
-	int num_cols;
-    // get number of columns
-    num_cols = ce_info->numUtilities + ce_info->numParameters;
-    num_cols = num_cols + ce_info->numObservables;
-    num_cols = num_cols + 1;    // overall utility
-    int num_rows = 2;
-    past_exp = (float **)malloc(sizeof(float)*num_rows);
-    int i;
-    for (i=0; i<num_rows; i++){
-        past_exp[i] = (float*)malloc(sizeof(float)*num_cols);
-    }
-    // sample experience #1
-    past_exp[0][0] = 1e3f;  // throughput
-    past_exp[0][1] = 1;     // spectral_efficiency
-    past_exp[0][2] = -3.5;  // log10_ber
-    past_exp[0][3] = 1;     // mod_scheme
-    past_exp[0][4] = -10;   // tx_power
-    past_exp[0][5] = 10.0;  // SNR
-    past_exp[0][6] = 0.762; // overall utility*/
-    // sample experience #2
-    past_exp[1][0] = 1e2f;  // throughput
-    past_exp[1][1] = 1;     // spectral_efficiency
-    past_exp[1][2] = -3.5;  // log10_ber
-    past_exp[1][3] = 1;     // mod_scheme
-    past_exp[1][4] = -14;   // tx_power
-    past_exp[1][5] = 3.0;   // SNR
-    past_exp[1][6] = 0.462; // overall utility
-
-	// update ce with experience
-    printf("Cognitive Radio:: Sending Previous Experience to New Cognitive Engine.\n\n");
-    UpdateCEExperience(socketfd, num_rows, num_cols, past_exp);	
-
-	RunSimulator(socketfd, uList, pList, oList, ce_info);
-}
-
-int AcceptTCPConnection(int servSock)
-{
-    int clntSock;                    /* Socket descriptor for client */
-    struct sockaddr_in echoClntAddr;
-    unsigned int clntLen;
-
-    /* Set the size of the in-out parameter */
-    clntLen = sizeof(echoClntAddr);
-
-    /* Wait for a client to connect */
-    //if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) {
-    if ((clntSock = accept(servSock, NULL, NULL)) < 0) {
-        return -1;
-    } 
-   
-    /* clntSock is connected to a client! */
-    
-    printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));
-
-    return clntSock;
-}
-
-int CreateTCPServerSocket(unsigned short port)
-{
-    int sock;                        /* socket to create */
-    struct sockaddr_in echoServAddr; /* Local address */
-
-    /* Create socket for incoming connections */
-    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
-        DieWithError("socket() failed");
-      
-    /* Construct local address structure */
-    memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */
-    echoServAddr.sin_family = AF_INET;                /* Internet address family */
-    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
-    echoServAddr.sin_port = htons(port);              /* Local port */
-
-    /* Bind to the local address */
-    if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
-        DieWithError("bind() failed");
-
-    /* Mark the socket so it will listen for incoming connections */
-    if (listen(sock, 5) < 0) {
-        printf("listen() failed\n");
-        return 0;
-    }
-
-    return sock;
-}
-
-void HandleTCPClient(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) 
-{
-    char buffer[256];        /* Buffer for echo string */
-
-    /* Receive message from client */
-    bzero(buffer,256);
-    ReceiveMessage(socketfd,buffer);
-
-    printf("Cognitive Radio:: Message Received - %s.\n\n", buffer);
-
-    if(strcmp(buffer,"c_register") == 0) 
-	    InitializeCE(socketfd, uList, pList, oList, ce_info);
-
-    if(strcmp(buffer,"p_register") == 0)
-	    InitializePE(socketfd, ce_info);
-
-    if(strcmp(buffer,"optimize") == 0)
-	    RunSimulator(socketfd, uList, pList, oList, ce_info);
-        
-    //close(socketfd);    /* Close client socket */
-}
-
-int StartServers(Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) {
-    int * servSock; 
-    int running = 1;
-    struct timeval selTimeout;
-    int timeout = 10;
-    int cognitive_engine = 0; 
-    int policy_engine = 1; 
-    int port, rc, on = 1;
-    int new_sd;
-    int desc_ready = 0;
-    fd_set sockSet;
-    
-    servSock = (int *) malloc(2 * sizeof(int));
-
-    servSock[cognitive_engine] = CreateTCPServerSocket(CE_SERVER_PORT);
-    servSock[policy_engine] = CreateTCPServerSocket(POLICY_SERVER_PORT);
-
-
-    int maxDescriptor = servSock[cognitive_engine];
-
-    if(servSock[cognitive_engine] < servSock[policy_engine])
-        maxDescriptor = servSock[policy_engine];
-
-    rc = setsockopt(servSock[cognitive_engine], SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
-    if(rc < 0)
-    {
-        perror("setsockopt() failed");
-        close(servSock[cognitive_engine]);
-        exit(-1);
-    }
-    
-    rc = setsockopt(servSock[policy_engine], SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
-    if(rc < 0)
-    {
-        perror("setsockopt() failed");
-        close(servSock[policy_engine]);
-        exit(-1);
-    }
-    
-    rc = ioctl(servSock[cognitive_engine], FIONBIO, (char*)&on);
-    if(rc < 0)
-    {
-        perror("ioctl() failed");
-        close(servSock[cognitive_engine]);
-        exit(-1);
-    }
-    
-    rc = ioctl(servSock[policy_engine], FIONBIO, (char*)&on);
-    if(rc < 0)
-    {
-        perror("ioctl() failed");
-        close(servSock[policy_engine]);
-        exit(-1);
-    }
-    
-    printf("Starting server:  Hit return to shutdown\n");
-    while (running)
-    {
-        /* Zero socket descriptor vector and set for server sockets */
-        /* This must be reset every time select() is called */
-        FD_ZERO(&sockSet);
-        /* Add keyboard to descriptor vector */
-        FD_SET(STDIN_FILENO, &sockSet);
-        FD_SET(servSock[cognitive_engine], &sockSet);
-        FD_SET(servSock[policy_engine], &sockSet);
-
-        /* Timeout specification */
-        /* This must be reset every time select() is called */
-        selTimeout.tv_sec = timeout;       /* timeout (secs.) */
-        selTimeout.tv_usec = 0;            /* 0 microseconds */
-
-        /* Suspend program until descriptor is ready or timeout */
-        rc = select(maxDescriptor + 1, &sockSet, NULL, NULL, &selTimeout); 
-        if (rc == 0)
-            printf("No echo requests for %i secs...Server still alive\n", timeout);
-        else 
-        {
-            if (FD_ISSET(0, &sockSet)) /* Check keyboard */
-            {
-                printf("Shutting down server\n");
-                getchar();
-                running = 0;
-            }
-
-            desc_ready = rc;
-
-            for (port = 0; port <= maxDescriptor && desc_ready > 0; port++) {
-                if (FD_ISSET(port, &sockSet))
-                {
-                    printf("Request on port %d:  ", port);
-	                desc_ready -= 1;
-
-
-                    if( (port == servSock[cognitive_engine]) || (port == servSock[policy_engine])) { 
-                       
-                        do
-                        { 
-                            new_sd = AcceptTCPConnection(port);
-                            if(new_sd < 0) 
-                            {
-                                break;
-                            }
-                            
-                            HandleTCPClient(new_sd, uList, pList, oList, ce_info);
-                            FD_SET(new_sd,&sockSet);
-                            if(new_sd > maxDescriptor) 
-                                maxDescriptor = new_sd;
-                            printf("New incoming connection - %i\n\n",new_sd);
-                        } while(new_sd != -1);
-                    } else {
-                        
-                        printf("Request on already open descriptor.\n\n");
-                        HandleTCPClient(port, uList, pList, oList, ce_info);
-
-                    }
-
-                }
-            }
-        }
-    }
-
-    /* Close sockets */
-    for (port = 0; port < 2; port++)
-        close(servSock[port]);
-
-    /* Free list of sockets */
-    free(servSock);        
-        
-	return 0;
-}
-
-int main(int argc, char* argv[]) {
-
-
-	// CognitiveEngine CE;
-	// CognitiveEngineShell Shell;
-	string pFilename; 
-    int fd;
-
-	Utility * uList[10];
-	Parameter * pList[10];
-	Observable * oList[10];
-	struct CE_Info *ce_info;
-
-    if((fd = open("/dev/zero", O_RDWR)) == -1)
-            return 1;
-
-    ce_info = (struct CE_Info *)mmap(0,sizeof(CE_Info),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
-
-    close(fd);
-
-	if(argc < 2) { 
-		cout << "Warning no XML file specific using default: example.xml" << endl;
-		pFilename = "example.xml";
-	} else {  
-		pFilename = argv[1];
-	}
-
-	TiXmlDocument doc( pFilename.c_str() );
-	bool loadOkay = doc.LoadFile();
-	if (!loadOkay)
-	{
-		cout << "Loading " << pFilename << " failed." << endl;
-		return 0;
-	}
-
-	cout << "\n\nInitialize:: Attemping to parse " << pFilename << "." << endl;
-	parse_ce_config( &doc , uList, pList, oList, ce_info);
-	cout << "Initialize:: Configuration file parsing completed.\n" << endl;
-
-    //print_current_config(uList, pList, oList, &ce_info);
-	
-   StartServers(uList, pList, oList, ce_info);
-   return 1;
-}
