Index: vtcross/trunk/src/shell/CognitiveRadioShell.cpp
===================================================================
--- vtcross/trunk/src/shell/CognitiveRadioShell.cpp	(revision 207)
+++ vtcross/trunk/src/shell/CognitiveRadioShell.cpp	(revision 207)
@@ -0,0 +1,486 @@
+/* Virginia Tech Cognitive Radio Open Source Systems
+ * Virginia Tech, 2009
+ *
+ * LICENSE INFORMATION GOES HERE
+ */
+
+/* DESCRIPTION OF FILE.
+ */
+
+
+#include <cstdlib>
+#include <cstring>
+#include <stdint.h>
+
+#include <arpa/inet.h>
+#include <iostream>
+#include <netinet/in.h>
+#include <netdb.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include "tinyxml/tinyxml.h"
+#include "tinyxml/tinystr.h"
+
+#include "vtcross/common.h"
+#include "vtcross/components.h"
+#include "vtcross/containers.h"
+#include "vtcross/debug.h"
+#include "vtcross/error.h"
+#include "vtcross/socketcomm.h"
+
+
+CognitiveRadioShell::CognitiveRadioShell()
+{
+    LOG("Creating Cognitive Radio Shell.\n");
+    SML_present = false;
+    PE_present = false;
+    CE_present = false;
+}
+
+
+CognitiveRadioShell::~CognitiveRadioShell()
+{
+    delete [] p;
+    delete [] o;
+    delete [] u;
+}
+
+
+CognitiveRadioShell::CognitiveRadioShell(const char* radioConfig, int16_t p1, \
+        int16_t p2, int16_t p3)
+{
+    LOG("Creating Cognitive Radio Shell.\n");
+
+    p = new Parameter[10];
+    o = new Observable[10];
+    u = new Utility[10];
+    radio_info = new Radio_Info;
+
+
+    LoadRadioConfiguration(radioConfig,p,u,o,radio_info);
+
+    primaryPort = p1;
+    policyPort = p2;
+    commandPort = p3;
+}
+
+
+void
+CognitiveRadioShell::SendComponentType(int32_t socketFD)
+{
+    SendMessage(socketFD, "response_shell");
+    LOG("Cognitive Radio Shell responded to GetRemoteComponentType query.\n");
+}
+
+void 
+CognitiveRadioShell::Shutdown()
+{
+    // TODO should something else be happening here?
+}
+
+
+void
+CognitiveRadioShell::Reset()
+{
+    LOG("Resetting Cognitive Radio Shell.\n");
+}
+
+
+void
+CognitiveRadioShell::SendRadioConfiguration(int32_t socketFD)
+{
+    LOG("Cognitive Radio Shell:: Sending radio configuration to Cognitive Engine.\n");
+}
+
+void
+CognitiveRadioShell::SendRadioExperience(int32_t socketFD)
+{
+
+    LOG("Cognitive Radio Shell:: Sending radio experience to Cognitive Engine.\n");
+}
+
+void
+CognitiveRadioShell::RegisterCognitiveEngine(int32_t socketFD)
+{
+    LOG("Cognitive Radio Shell:: Received registration message from Cognitive Engine.\n");
+   
+    SendRadioConfiguration(socketFD);
+    SendRadioExperience(socketFD);
+
+    numberOfCognitiveEngines++;
+    CE_present = true;
+}
+
+void 
+CognitiveRadioShell::DeregisterCognitiveEngine(int32_t socketFD)
+{
+    LOG("Cognitive Radio Shell:: Received deregistration message from Cognitive Engine.\n");
+
+    numberOfCognitiveEngines--;
+    if(numberOfCognitiveEngines == 0)
+	CE_present = false;
+
+    SendMessage(socketFD, "deregister_ack");
+    shutdown(socketFD, 2);
+    close(socketFD);
+    LOG("Cognitive Radio Shell:: Socket closed.\n");
+}
+
+void
+CognitiveRadioShell::RegisterPolicyEngine(int32_t socketFD)
+{
+    LOG("Cognitive Radio Shell:: Received registration message from Policy Engine.\n");
+    PE_present = true;
+}
+
+void 
+CognitiveRadioShell::DeregisterPolicyEngine(int32_t socketFD)
+{
+    LOG("Cognitive Radio Shell:: Received deregistration message from Policy Engine.\n");
+
+    PE_present = false;
+    
+    SendMessage(socketFD, "deregister_ack");
+    shutdown(socketFD, 2);
+    close(socketFD);
+    LOG("Cognitive Radio Shell:: Socket closed.\n");
+}
+
+void
+CognitiveRadioShell::RegisterSML(int32_t socketFD)
+{
+    LOG("Cognitive Radio Shell:: Received registration message from SML.\n");
+
+    SML_present = true;
+}
+
+void 
+CognitiveRadioShell::DeregisterSML(int32_t socketFD)
+{
+    LOG("Cognitive Radio Shell:: Received deregistration message from SML.\n");
+
+    SML_present = false;
+
+    SendMessage(socketFD, "deregister_ack");
+    shutdown(socketFD, 2);
+    close(socketFD);
+    LOG("Cognitive Radio Shell:: Socket closed.\n");
+}
+
+int32_t 
+CognitiveRadioShell::LoadRadioConfiguration(const char* radioConfig, Parameter* &pList, \
+    Utility* &uList, Observable* &oList, Radio_Info * radioInfo)
+{
+    TiXmlElement *pElem;
+    TiXmlElement *pChild;
+    TiXmlElement *pChild1;
+    TiXmlElement *pSecondChild;
+    TiXmlHandle hRoot(0);
+
+    int32_t count = 0;
+    size_t item_count = 0;
+    size_t affect_count = 0;
+    int32_t attribute_count = 0;
+    bool match_found = false;
+
+    LOG("Cognitive Radio Shell:: Loading radio configuration.\n");
+
+    TiXmlDocument doc( radioConfig );
+    bool loadOkay = doc.LoadFile();
+    if(!loadOkay)
+    {
+        ERROR(1,"Loading radio configuration failed: %s\n", radioConfig);
+        return -1;
+    }
+
+    TiXmlHandle hDoc(&doc);
+    
+    pElem = hDoc.FirstChildElement().Element();
+
+    if(!pElem) 
+        ERROR(1, "No valid root!");
+
+    hRoot = TiXmlHandle(pElem);
+
+    pElem = hRoot.FirstChild("utilities").Element();
+    pChild1 = hRoot.Child("utilities", count).Element();
+
+    for(pChild = pChild1->FirstChildElement("utility"); pChild; \
+        pChild = pChild->NextSiblingElement()) 
+    {
+        const char *uName = pChild->Attribute("name");
+        if(uName)
+            uList[item_count].name = uName;	
+
+        const char *uUnits = pChild->Attribute("units");
+        if(uUnits) 
+            uList[item_count].units = uUnits;
+
+        const char *uGoal = pChild->Attribute("goal");
+        if(uGoal) 
+            uList[item_count].goal = uGoal;
+
+        if(pChild->QueryFloatAttribute("target", &uList[item_count].target) != TIXML_SUCCESS) 
+            uList[item_count].target = -1;
+
+        item_count++;
+    }
+
+    radio_info->numUtilities = item_count;	
+    LOG("Cognitive Radio Shell:: Parsed %d utilities.\n", radioInfo->numUtilities);
+
+    item_count = 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");
+        if(oName) 
+            oList[item_count].name = oName;
+		
+        affect_count = 0;
+        for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; \
+            pSecondChild = pSecondChild->NextSiblingElement()) 
+        {
+            const char *oUtilName = pSecondChild->Attribute("utility");
+            if(oUtilName) 
+            {
+                for(attribute_count = 0; attribute_count < radio_info->numUtilities; attribute_count++ ) 
+                {
+                    if(uList[attribute_count].name == oUtilName) 
+                    {
+                        oList[item_count].affection_list[affect_count].u = &uList[attribute_count];
+                        const char *oRelate = pSecondChild->Attribute("relationship");
+                        if(oRelate) 
+                            oList[item_count].affection_list[affect_count].relation = oRelate;
+                        affect_count++;
+                        match_found = true;
+                        break;
+                    }
+                }
+            }
+
+            if(!match_found) { 
+                ERROR(1, "Error: %s: %s is not a valid utility.\n", \
+                    oList[item_count].name.c_str(), oUtilName);
+            }
+            else
+                match_found = false;	
+        }
+        oList[item_count].numAffects = affect_count; 
+        item_count++;
+    }
+
+    radioInfo->numObservables = item_count;	
+    LOG("Cognitive Radio Shell:: Parsed %d observables.\n", radioInfo->numObservables);
+
+    pElem = hRoot.FirstChild("parameters").Element();
+    pChild1 = hRoot.Child("parameters", count).Element();
+	
+    item_count = 0;
+    for(pChild = pChild1->FirstChildElement("parameter"); pChild; \
+        pChild = pChild->NextSiblingElement()) 
+    {
+        const char *pName = pChild->Attribute("name");
+        if(pName) 
+            pList[item_count].name = pName;	
+
+        const char *pUnits = pChild->Attribute("units");
+        if(pUnits) 
+            pList[item_count].units = pUnits;
+
+        if(pChild->QueryFloatAttribute("min", &pList[item_count].min) != TIXML_SUCCESS) 
+            pList[item_count].min = -1;
+
+        if(pChild->QueryFloatAttribute("max", &pList[item_count].max) != TIXML_SUCCESS) 
+            pList[item_count].max = -1;
+
+        if(pChild->QueryFloatAttribute("step", &pList[item_count].step) != TIXML_SUCCESS) 
+            pList[item_count].step = -1;
+		
+        affect_count = 0;
+        for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; \
+            pSecondChild = pSecondChild->NextSiblingElement()) 
+        {
+            const char *pUtilName = pSecondChild->Attribute("utility");
+            if(pUtilName) 
+            {
+                for(attribute_count = 0; attribute_count < radio_info->numUtilities; attribute_count++) 
+                {
+                    if(uList[attribute_count].name == pUtilName) 
+                    {
+                        pList[item_count].affection_list[affect_count].u = &uList[attribute_count];	
+
+                        const char *pRelate = pSecondChild->Attribute("relationship");
+                        if(pRelate)
+                            pList[item_count].affection_list[affect_count].relation = pRelate;
+                        else
+                            LOG("Error: No relation found.\n");
+
+                        match_found = true;
+                        affect_count++;
+                        break;
+                    }
+                }
+            }
+
+            if(!match_found) 
+            {
+                ERROR(1, "Error: %s: %s is not a valid utility.\n", \
+                    pList[item_count].name.c_str(), pUtilName);
+            }
+
+            match_found = false;	
+        }
+
+        pList[item_count].numAffects = affect_count;
+        item_count++;
+    }
+
+    radioInfo->numParameters = item_count;
+    LOG("Cognitive Radio Shell:: Parsed %d parameters.\n", radioInfo->numParameters);
+
+    return 1;
+
+}
+
+void
+CognitiveRadioShell::GetOptimalParameters(int32_t socketFD)
+{
+
+
+}
+
+void
+CognitiveRadioShell::HandleMessage(int32_t socketFD)
+{
+    char buffer[256];
+
+    ReadMessage(socketFD, buffer);
+
+    if(strcmp(buffer,"register_engine_cognitive") == 0) { 
+	    RegisterCognitiveEngine(socketFD);
+    } else if(strcmp(buffer,"deregister_engine_cognitive") == 0) {
+	    DeregisterCognitiveEngine(socketFD);
+    } else if(strcmp(buffer,"register_engine_policy") == 0) {
+	    RegisterPolicyEngine(socketFD);
+    } else if(strcmp(buffer,"deregister_engine_policy") == 0) {
+	    DeregisterPolicyEngine(socketFD);
+    } else if(strcmp(buffer,"register_sml") == 0) {
+	    RegisterSML(socketFD);
+    } else if(strcmp(buffer,"deregister_sml") == 0) {
+	    DeregisterSML(socketFD);
+    } else if(strcmp(buffer,"optimize") == 0) {
+	    /* Receive optimization request and current environment */
+	    GetOptimalParameters(socketFD);  
+    }
+}
+
+void
+CognitiveRadioShell::StartShellServer()
+{
+    int32_t * servSock;
+    struct timeval selTimeout;
+    int32_t primary = 0;
+    int32_t policy = 1;
+    int32_t command = 2;
+    int32_t running = 1;
+    int32_t port, rc, new_sd = 1;
+    int32_t desc_ready = 1;
+    int32_t timeout = 10;
+    fd_set sockSet;
+
+    servSock = (int32_t *) malloc(3 * sizeof(int32_t));
+
+    servSock[primary] = CreateTCPServerSocket(primaryPort);
+    servSock[policy] = CreateTCPServerSocket(policyPort);
+    servSock[command] = CreateTCPServerSocket(commandPort);
+
+    int32_t maxDescriptor = servSock[command];
+
+    if(InitializeTCPServerPort(servSock[primary]) == -1) {
+	ERROR(1,"Error initializing primary port\n");
+       	return; 
+    }
+ 
+    if(InitializeTCPServerPort(servSock[policy]) == -1) {
+	ERROR(1,"Error initializing policy port\n");
+       	return; 
+    }
+
+    if(InitializeTCPServerPort(servSock[command]) == -1) { 
+	ERROR(1,"Error initializing command port\n");
+       	return; 
+    }
+
+    while (running)
+    {
+        /* Zero socket descriptor vector and set for server sockets */
+        /* This must be reset every time select() is called */
+        FD_ZERO(&sockSet);
+        FD_SET(servSock[primary], &sockSet);
+        FD_SET(servSock[policy], &sockSet);
+        FD_SET(servSock[command], &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)
+            LOG("No echo requests for %i secs...Server still alive\n", timeout);
+        else 
+        {
+            desc_ready = rc;
+
+            for (port = 0; port <= maxDescriptor && desc_ready > 0; port++) {
+                if (FD_ISSET(port, &sockSet))
+                {
+	            desc_ready -= 1;
+
+                    /* Check if request is new or on an existing open descriptor */
+                    if( (port == servSock[primary]) || (port == servSock[policy]) || (port == servSock[command])) { 
+                        do
+                        { 
+                            new_sd = AcceptTCPConnection(port);
+                            if(new_sd < 0) 
+                            {
+                                break;
+                            }
+                            
+                            HandleMessage(new_sd);
+                            FD_SET(new_sd,&sockSet);
+                            if(new_sd > maxDescriptor) 
+                                maxDescriptor = new_sd;
+                            //LOG("New incoming connection - %i\n\n",new_sd);
+                        } while(new_sd != -1);
+                    } else {
+                        
+                        //LOG("Request on already open descriptor.\n\n");
+                        HandleMessage(port);
+                    }
+                }
+            }
+        }
+    }
+
+
+    /* Close sockets */
+    close(servSock[primary]);
+    close(servSock[policy]);
+    close(servSock[command]);
+
+    /* Free list of sockets */
+    free(servSock);  
+
+    return;
+}
Index: vtcross/trunk/src/shell/Makefile.am
===================================================================
--- vtcross/trunk/src/shell/Makefile.am	(revision 168)
+++ vtcross/trunk/src/shell/Makefile.am	(revision 207)
@@ -5,5 +5,5 @@
 bin_PROGRAMS = shell_demo
 
-shell_demo_SOURCES = cr_shell.cpp
+shell_demo_SOURCES = CognitiveRadioShell.cpp shell_demo.cpp
 shell_demo_LDADD = ../lib/tinyxml/libtinyxml.a ../lib/socketcomm/libsocketcomm.a
 
Index: vtcross/trunk/src/shell/shell_demo.cpp
===================================================================
--- vtcross/trunk/src/shell/shell_demo.cpp	(revision 207)
+++ vtcross/trunk/src/shell/shell_demo.cpp	(revision 207)
@@ -0,0 +1,39 @@
+/* Virginia Tech Cognitive Radio Open Source Systems
+ * Virginia Tech, 2009
+ *
+ * TODO LICENSE INFORMATION GOES HERE
+ */
+
+/* TODO DESCRIPTION OF FILE.
+ *
+ * This file is a temporary demo of a policy engine using some of our socket
+ * communication functions. This is *not* an actual implementation of our
+ * defined PolicyEngine class.
+ */
+
+
+#include <cstdlib>
+#include <cstring>
+#include <stdint.h>
+
+#include "vtcross/common.h"
+#include "vtcross/components.h"
+#include "vtcross/containers.h"
+#include "vtcross/debug.h"
+#include "vtcross/error.h"
+#include "vtcross/socketcomm.h"
+
+
+int32_t 
+main(int32_t argc, char *argv[])
+{
+    if(argc < 3)
+       ERROR(1, "Usage: %s config_file primary_port policy_port command_port\n", argv[0]);
+    
+    CognitiveRadioShell cognitiveRadioShell(argv[1], atoi(argv[2]), atoi(argv[3]), atoi(argv[4]));
+
+    cognitiveRadioShell.StartShellServer();
+
+    return 0;
+}
+
Index: vtcross/trunk/src/shell/cr_shell.cpp
===================================================================
--- vtcross/trunk/src/shell/cr_shell.cpp	(revision 195)
+++ 	(revision )
@@ -1,705 +1,0 @@
-/* Virginia Tech Cognitive Radio Open Source Systems
- * Virginia Tech, 2009
- *
- * TODO LICENSE INFORMATION GOES HERE
- */
-
-/* TODO DESCRIPTION OF FILE.
- */
-
-
-#include <arpa/inet.h>
-#include <iostream>
-#include <netinet/in.h>
-#include <netdb.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <sys/mman.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-
-#include "tinyxml/tinyxml.h"
-#include "tinyxml/tinystr.h"
-
-#include "vtcross/common.h"
-#include "vtcross/components.h"
-#include "vtcross/containers.h"
-#include "vtcross/debug.h"
-#include "vtcross/error.h"
-#include "vtcross/socketcomm.h"
-
-
-using namespace std;
-
-
-#define CE_SERVER_PORT 30001
-#define PE_SERVER_PORT 30003
-
-
-void 
-print_current_config(Utility* uList[], Parameter* pList[], \
-        Observable* oList[], Radio_Info* radio_info)
-{
-	for(size_t i = 0; i < radio_info->numUtilities ; i++) {
-        LOG("Shell:: Utility: %s\n\tUnits: %s\n\tGoal: %s\n\tTarget: %f\n", \
-                uList[i]->name.c_str(), uList[i]->units.c_str(), \
-                uList[i]->goal.c_str(), uList[i]->target);
-	}
-
-	for(size_t i = 0; i < radio_info->numParameters; i++) {
-	    LOG("Shell:: Radio Operation Profile has been sucessfully sent.\n");
-        LOG("Shell:: Parameter: %s\n\tUnits: %s\n\tMin: %f\n\t", \
-                pList[i]->name.c_str(), pList[i]->units.c_str(), \
-                pList[i]->min);
-        LOG("\tMax: %f\n\tStep: %f\n", pList[i]->max, pList[i]->step);
-
-		for(size_t j = 0; j < pList[i]->numAffects; j++) {
-			LOG("\t\tAffect %s -> %s\n", pList[i]->affection_list[j].u->name.c_str(), \
-                    pList[i]->affection_list[j].relation.c_str());
-		}
-	}
-	
-    for(size_t i = 0; i < radio_info->numObservables; i++) {
-		LOG("Observable: %s\n", oList[i]->name.c_str());
-
-		for(size_t j = 0; j < oList[i]->numAffects; j++) {
-			LOG("\t\tAffect %s -> %s ", oList[i]->affection_list[j].u->name.c_str(), \
-                    oList[i]->affection_list[j].relation.c_str());
-		}
-	}
-}
-
-
-// TODO should this function really be called parse 'ce' config?  Seems like it
-// affects the entire radio?
-// TODO Why are we always returning 1? Is this just a success variable? It's not
-// even being used when we call it...
-// TODO this function needs some serious comments
-int32_t
-parse_ce_config(TiXmlDocument* doc, Utility* u[], Parameter* p[], \
-        Observable* o[], Radio_Info* radio_info)
-{
-
-	TiXmlElement *pElem;
-	TiXmlElement *pChild;
-	TiXmlElement *pChild1;
-	TiXmlElement *pSecondChild;
-	TiXmlHandle hDoc(doc);
-	TiXmlHandle hRoot(0);
-
-	int32_t count = 0;
-	size_t item_count = 0;
-    size_t affect_count = 0;
-	int32_t attribute_count = 0;
-    bool match_found = false;
-
-	pElem = hDoc.FirstChildElement().Element();
-
-	if(!pElem) 
-        ERROR(1, "No valid root!");
-
-	hRoot = TiXmlHandle(pElem);
-
-	pElem = hRoot.FirstChild("utilities").Element();
-	pChild1 = hRoot.Child("utilities", count).Element();
-
-	for(pChild = pChild1->FirstChildElement("utility"); pChild; \
-            pChild = pChild->NextSiblingElement()) {
-
-		u[item_count] = new Utility;
-
-   		const char *uName = pChild->Attribute("name");
-   		if(uName)
-            u[item_count]->name = uName;	
-
-		const char *uUnits = pChild->Attribute("units");
-   		if(uUnits) 
-            u[item_count]->units = uUnits;
-
-   		const char *uGoal = pChild->Attribute("goal");
-   		if(uGoal) 
-            u[item_count]->goal = uGoal;
-
-   		if(pChild->QueryFloatAttribute("target", &u[item_count]->target) != TIXML_SUCCESS) 
-            u[item_count]->target = -1;
-
-		item_count++;
-	}
-
-	radio_info->numUtilities = item_count;	
-	LOG("Initialize:: Parsed %d utilities.\n", radio_info->numUtilities);
-
-	item_count = 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[item_count] = new Observable;
-   		if(oName) 
-            o[item_count]->name = oName;
-		
-		affect_count = 0;
-		for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; \
-                pSecondChild = pSecondChild->NextSiblingElement()) {
-
-   			const char *oUtilName = pSecondChild->Attribute("utility");
-			if(oUtilName) {
-				for(attribute_count = 0; u[attribute_count] != NULL; attribute_count++ ) {
-					if(u[attribute_count]->name == oUtilName) {
-						o[item_count]->affection_list[affect_count].u = u[attribute_count];
-
-						const char *oRelate = pSecondChild->Attribute("relationship");
-   						if(oRelate) 
-                            o[item_count]->affection_list[affect_count].relation = oRelate;
-
-						affect_count++;
-						match_found = true;
-				 		break;
-					}
-				}
-			}
-
-			if(!match_found) { 
-                ERROR(1, "Error: %s: %s is not a valid utility.\n", \
-                        o[item_count]->name.c_str(), oUtilName);
-            }
-            else
-                match_found = false;	
-		}
-
-		o[item_count]->numAffects = affect_count; 
-		item_count++;
-	}
-
-	radio_info->numObservables = item_count;	
-	LOG("Initialize:: Parsed %d observables.\n", radio_info->numObservables);
-
-	pElem = hRoot.FirstChild("parameters").Element();
-	pChild1 = hRoot.Child("parameters", count).Element();
-	
-	item_count = 0;
-	for(pChild = pChild1->FirstChildElement("parameter"); pChild; \
-            pChild = pChild->NextSiblingElement()) {
-
-		p[item_count] = new Parameter;
-
-		const char *pName = pChild->Attribute("name");
-   		if(pName) 
-            p[item_count]->name = pName;	
-
-		const char *pUnits = pChild->Attribute("units");
-   		if(pUnits) 
-            p[item_count]->units = pUnits;
-
-   		if(pChild->QueryFloatAttribute("min", &p[item_count]->min) != TIXML_SUCCESS) 
-            p[item_count]->min = -1;
-
-   		if(pChild->QueryFloatAttribute("max", &p[item_count]->max) != TIXML_SUCCESS) 
-            p[item_count]->max = -1;
-
-   		if(pChild->QueryFloatAttribute("step", &p[item_count]->step) != TIXML_SUCCESS) 
-            p[item_count]->step = -1;
-		
-		affect_count = 0;
-		for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; \
-                pSecondChild = pSecondChild->NextSiblingElement()) {
-
-   			const char *pUtilName = pSecondChild->Attribute("utility");
-			if(pUtilName) {
-				for(attribute_count = 0; u[attribute_count] != NULL; attribute_count++) {
-					if(u[attribute_count]->name == pUtilName) {
-						p[item_count]->affection_list[affect_count].u = u[attribute_count];	
-
-						const char *pRelate = pSecondChild->Attribute("relationship");
-   						if(pRelate)
-							p[item_count]->affection_list[affect_count].relation = pRelate;
-						else
-							LOG("Error: No relation found.\n");
-
-						match_found = true;
-						affect_count++;
-						break;
-					}
-				}
-			}
-
-			if(!match_found) {
-                ERROR(1, "Error: %s: %s is not a valid utility.\n", \
-                        p[item_count]->name.c_str(), pUtilName);
-            }
-
-			match_found = false;	
-		}
-
-		p[item_count]->numAffects = affect_count;
-		item_count++;
-	}
-
-	radio_info->numParameters = item_count;
-	LOG("Initialize:: Parsed %d parameters.\n", radio_info->numParameters);
-
-	return 1;
-}
-
-
-void 
-LoadCEConfiguration(int32_t socketfd,Utility* uList[], Parameter* pList[], \
-        Observable* oList[], Radio_Info* radio_info)
-{
-	int32_t n,i,j;
-	char counter[55];
-	char var[50];
-	//int32_t total_bytes;   
-
-	printf("Cognitive Radio:: Sending Radio Operating Profile to Cognitive Engine.\n\n");
- 
- 	// utilities
-	// Send number of utilities
-	sprintf(counter,"%d",radio_info->numUtilities);
-	SendMessage(socketfd,counter);
-	// send utility	
-    for(i = 0; i < radio_info->numUtilities; i++) {
-		SendMessage(socketfd, uList[i]->name.c_str());
-		SendMessage(socketfd, uList[i]->units.c_str());
-		SendMessage(socketfd, uList[i]->goal.c_str());
-		sprintf(var,"%f", uList[i]->target);
-		SendMessage(socketfd,var);
-	}
-
-	// parameters
-    sprintf(counter,"%i",radio_info->numParameters);
-	SendMessage(socketfd,counter);
-	for(i = 0; i < radio_info->numParameters; i++) {
-		SendMessage(socketfd,pList[i]->name.c_str());
-		SendMessage(socketfd,pList[i]->units.c_str());
-		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.c_str());
-			SendMessage(socketfd,pList[i]->affection_list[j].relation.c_str());
-		}
-	}
-
-    // observables
-	sprintf(counter,"%i",radio_info->numObservables);
-	SendMessage(socketfd,counter);
-	for(i = 0; i < radio_info->numObservables; i++) {
-		SendMessage(socketfd,oList[i]->name.c_str());
-		
-		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.c_str());
-			SendMessage(socketfd,oList[i]->affection_list[j].relation.c_str());
-		}
-	}
-	
-	// Receive ACK for utils
-    char buffer[256];
-        string message;
-	ReadMessage(socketfd, buffer);
-    //printf("%s\n", buffer);
-        //cout << message << endl;
-	//printf("ACK received.\n");
-
-}
-
-
-void 
-UpdateCEExperience(int32_t socketfd, int32_t num_rows, int32_t num_cols, 
-        float * past_exp[]) 
-{
-    int32_t 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);
-        }
-    }
-
-}
-
-
-int32_t 
-RequestPolicyValidation(Parameter * pList[], Radio_Info *radio_info)
-{
-	char counter[55];
-	char var[50];
-    int32_t i;
-    char* control_msg = "val";
-    
-    int32_t socketfd = radio_info->policy_socket;
-
-    // Control message that validation request is coming
-	SendMessage(socketfd,control_msg);
-
-    printf("Cognitive Radio:: Here. %i\n\n", socketfd);
-
-	// Send parameter information 
-    sprintf(counter,"%i",radio_info->numParameters);
-	SendMessage(socketfd,counter);
-	for(i = 0; i < radio_info->numParameters; i++) {
-		SendMessage(socketfd,pList[i]->name.c_str());
-		SendMessage(socketfd,pList[i]->units.c_str());
-		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;
-
-}
-
-
-int32_t 
-RequestCEOptimization(int32_t sockfd, Utility *uList[], 
-        Parameter *pList[], Observable *oList[],
-        Radio_Info *radio_info)
-{
-    char buffer[256];
-    int32_t i;
-    float var;
-
-    // Send request optimization message followed by the current environment parameters.
-    /*
-    SendMessage(sockfd,"request"); 
-    for (i = 0; i < radio_info->numObservables; i++){
-        SendMessage(sockfd,..);
-    }
-    */
-
-    // Receive optimized values from the Cognitive Engine 
-    for (i = 0; i < radio_info->numParameters; i++){
-        bzero(buffer,256);
-        ReadMessage(sockfd,buffer);
-        var = atof(buffer);
-        pList[i]->value = var;
-    }
-
-
-    // If policy engine is connect, validate new values
-    if(radio_info->policy_engine == 1) {
-
-        printf("Cognitive Radio:: Found Policy Engine!\n");
-        printf("Cognitive Radio:: Validating parameters with Policy Engine\n\n");
-        RequestPolicyValidation(pList,radio_info); 
-        printf("Cognitive Radio:: Done\n\n");
-
-    }
-
-
-    return 1;
-}
-
-void 
-RunSimulator(int32_t socketfd, Utility * uList[], 
-        Parameter * pList[], Observable * oList[], 
-        Radio_Info * radio_info) {
-	
-	float **past_exp;
-    int32_t num_rows, num_cols;
-
-	// Set fake current environment params = current environment
-	RequestCEOptimization(socketfd, uList, pList, oList, radio_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(int32_t socket, Radio_Info * radio_info) 
-{
-    // Policy Engine is connected
-    // Set global policy engine value to 1
-    radio_info->policy_engine = 1;
-    radio_info->policy_socket = socket;
-
-    return;
-}
-
-void 
-InitializeCE(int32_t socketfd, Utility* uList[], Parameter* pList[], \
-        Observable* oList[], Radio_Info* radio_info) 
-{
-	LoadCEConfiguration(socketfd, uList, pList, oList, radio_info);
-	
-    // cr experience
-    float **past_exp;
-	int32_t num_cols;
-    // get number of columns
-    num_cols = radio_info->numUtilities + radio_info->numParameters;
-    num_cols = num_cols + radio_info->numObservables;
-    num_cols = num_cols + 1;    // overall utility
-    int32_t num_rows = 2;
-    past_exp = (float **)malloc(sizeof(float)*num_rows);
-    int32_t 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, radio_info);
-}
-
-
-void 
-HandleTCPClient(int32_t socketFD, Utility* uList[], Parameter* pList[], \
-        Observable* oList[], Radio_Info* radio_info) 
-{
-    char buffer[256];
-
-    /* Receive message from client */
-    bzero(buffer, 256);
-    ReadMessage(socketFD, buffer);
-
-    LOG("Cognitive Radio:: Message Received - %s.\n\n", buffer);
-
-    if(strcmp(buffer,"register_engine_cognitive") == 0) 
-	    InitializeCE(socketFD, uList, pList, oList, radio_info);
-
-    if(strcmp(buffer,"register_engine_policy") == 0)
-	    InitializePE(socketFD, radio_info);
-
-    if(strcmp(buffer,"optimize") == 0)
-	    RunSimulator(socketFD, uList, pList, oList, radio_info);
-        
-    // TODO why aren't we doing this anymore?
-    //close(socketfd);    /* Close client socket */
-}
-
-
-int32_t 
-StartServers(Utility* uList[], Parameter* pList[], Observable* oList[], \
-        Radio_Info* radio_info)
-{
-    int32_t * servSock; 
-    int32_t running = 1;
-    struct timeval selTimeout;
-    int32_t timeout = 10;
-    int32_t cognitive_engine = 0; 
-    int32_t policy_engine = 1; 
-    int32_t port, rc, on = 1;
-    int32_t new_sd;
-    int32_t desc_ready = 0;
-    fd_set sockSet;
-    
-    servSock = (int32_t *) malloc(2 * sizeof(int32_t));
-
-    servSock[cognitive_engine] = CreateTCPServerSocket(CE_SERVER_PORT);
-    servSock[policy_engine] = CreateTCPServerSocket(PE_SERVER_PORT);
-
-
-    int32_t 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, radio_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, radio_info);
-
-                    }
-
-                }
-            }
-        }
-    }
-
-    /* Close sockets */
-    for (port = 0; port < 2; port++)
-        close(servSock[port]);
-
-    /* Free list of sockets */
-    free(servSock);        
-        
-	return 0;
-}
-
-int32_t 
-main(int32_t argc, char* argv[])
-{
-	// CognitiveEngine CE;
-	// CognitiveEngineShell Shell;
-	string pFilename; 
-    int32_t fd;
-
-	Utility * uList[10];
-	Parameter * pList[10];
-	Observable * oList[10];
-	struct Radio_Info *radio_info;
-
-    if((fd = open("/dev/zero", O_RDWR)) == -1)
-            return 1;
-
-    radio_info = (struct Radio_Info *)mmap(0,sizeof(Radio_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, radio_info);
-	cout << "Initialize:: Configuration file parsing completed.\n" << endl;
-
-    //print_current_config(uList, pList, oList, &radio_info);
-	
-   StartServers(uList, pList, oList, radio_info);
-   return 1;
-}
