diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9e0255b..ee75700 100755
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -84,25 +84,23 @@ ADD_DEFINITIONS(-DPGAGENT_VERSION_MAJOR=${CPACK_PACKAGE_VERSION_MAJOR})
 INCLUDE(CPack)
 
 ################################################################################
-# Find wxWidgets
+# Find BOOST
 ################################################################################
-SET(WX_DEBUG NO CACHE BOOL "Use the debug build of wxWidgets?")
-SET(WX_STATIC ${STATIC_BUILD})
-SET(WX_VERSION "2.8")
-SET(WX_UNICODE YES)
-SET(WX_MODULES "base")
+set(Boost_USE_STATIC_LIBS OFF) 
+set(Boost_USE_MULTITHREADED ON)  
+set(Boost_USE_STATIC_RUNTIME OFF) 
 
-FIND_PACKAGE(WX REQUIRED)
+FIND_PACKAGE(Boost 1.41.0 REQUIRED COMPONENTS thread program_options )
 
-INCLUDE_DIRECTORIES(${WX_INCLUDE_DIRS})
-ADD_DEFINITIONS(${WX_DEFINITIONS})
-LINK_DIRECTORIES(${WX_LIBRARY_DIRS})
-SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${WX_CXX_FLAGS}")
+include_directories(${Boost_INCLUDE_DIRS})
+ADD_DEFINITIONS(${Boost_DEFINITIONS})
+LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Boost_CXX_FLAGS} ")
 
 ################################################################################
 # Find PostgreSQL
 ################################################################################
-SET(PG_STATIC ${WX_STATIC})
+#SET(PG_STATIC ${WX_STATIC})
 
 FIND_PACKAGE(PG REQUIRED)
 
@@ -125,7 +123,7 @@ IF(WIN32)
 ENDIF(WIN32)
  
 ADD_EXECUTABLE(pgagent ${_srcs})
-TARGET_LINK_LIBRARIES(pgagent ${PG_LIBRARIES} ${WX_LIBRARIES})
+TARGET_LINK_LIBRARIES(pgagent ${PG_LIBRARIES} ${Boost_LIBRARIES})
 
 # Installation
 IF (WIN32)
@@ -166,11 +164,11 @@ MESSAGE(STATUS "  PostgreSQL config binary    : ${PG_CONFIG_PATH}")
 MESSAGE(STATUS "  PostgreSQL include path     : ${PG_INCLUDE_DIRS}")
 MESSAGE(STATUS "  PostgreSQL library path     : ${PG_LIBRARY_DIRS}")
 MESSAGE(STATUS " ")
-MESSAGE(STATUS "  wxWidgets version           : ${WX_VERSION_STRING}")
-MESSAGE(STATUS "  wxWidgets path              : ${WX_ROOT_DIR}")
-MESSAGE(STATUS "  wxWidgets config binary     : ${WX_CONFIG_PATH}")
-MESSAGE(STATUS "  wxWidgets Static linking    : ${WX_STATIC}")
-MESSAGE(STATUS "  wxWidgets Debug?            : ${WX_DEBUG}")
+MESSAGE(STATUS "  BOOST version           : ${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}")
+MESSAGE(STATUS "  BOOST Include Path      : ${Boost_INCLUDE_DIRS}")
+MESSAGE(STATUS "  BOOST Library Dirs      : ${Boost_LIBRARY_DIRS}")
+MESSAGE(STATUS "  BOOST Static linking    : ${Boost_USE_STATIC_LIBS}")
+MESSAGE(STATUS "  BOOST Debug?            : ${Boost_DEBUG}")
 MESSAGE(STATUS "================================================================================")
 MESSAGE(STATUS " ")
 
diff --git a/connection.cpp b/connection.cpp
index 6103c00..81a812c 100644
--- a/connection.cpp
+++ b/connection.cpp
@@ -11,264 +11,177 @@
 
 #include "pgAgent.h"
 
-#include <wx/regex.h>
-#include <wx/tokenzr.h>
+boost::mutex DBconn::s_PoolLock;
+std::multimap<std::string, PGconn *> DBconn::free_PGconn_map;
 
-DBconn *DBconn::primaryConn = NULL;
-wxString DBconn::basicConnectString;
-static wxMutex s_PoolLock;
-
-
-DBconn::DBconn(const wxString &connectString, const wxString &db)
+DBconn::DBconn(connInfo *cInfo)
 {
 	inUse = false;
-	next = 0;
-	prev = 0;
 	majorVersion = 0;
 	minorVersion = 0;
-	dbname = db;
-	connStr = connectString;
+	dbname = cInfo->dbname;
+	connStr = cInfo->getConnectionString();
+	cnInfo = cInfo;
 
-	if (connectString.IsEmpty())
+	LogMessage( std::string("DBconn(connInfo *cInfo): ") + connStr, LOG_DEBUG);
+	if (!connStr.empty())
 	{
-		// This is a sql call to a local database.
-		// No connection string found. Use basicConnectString.
-		Connect(basicConnectString  + wxT(" dbname=") + dbname);
+		conn = Get(cInfo);
+		if(conn == NULL) Connect(connStr);
 	}
 	else
 	{
-		Connect(connectString);
+		LogMessage( std::string("Can not create DB connection: ") + cInfo->getConnectionString(), LOG_ERROR);
 	}
 }
 
-
-bool DBconn::Connect(const wxString &connectString)
+bool DBconn::Connect(const std::string &connectString)
 {
-	LogMessage(wxString::Format(_("Creating DB connection: %s"), connectString.c_str()), LOG_DEBUG);
-	wxCharBuffer cstrUTF = connectString.mb_str(wxConvUTF8);
-	conn = PQconnectdb(cstrUTF);
+	LogMessage( std::string("DBconn::Connect - Creating DB connection: ") + connectString, LOG_DEBUG);
+
+	conn = PQconnectdb(connectString.c_str());
+
 	if (PQstatus(conn) != CONNECTION_OK)
 	{
-		lastError = wxString::FromAscii(PQerrorMessage(conn));
+		lastError = std::string(PQerrorMessage(conn));
 		PQfinish(conn);
 		conn = 0;
 	}
 	return IsValid();
 }
 
-
 DBconn::~DBconn()
 {
 	// clear a single connection
-	if (conn)
-	{
-		PQfinish(conn);
-		conn = 0;
-	}
+	this->Return();
 }
 
-
-wxString DBconn::qtDbString(const wxString &value)
+std::string DBconn::qtDbString(const std::string &value)
 {
-	wxString result = value;
+	std::string result = value;
 
-	result.Replace(wxT("\\"), wxT("\\\\"));
-	result.Replace(wxT("'"), wxT("''"));
-	result.Append(wxT("'"));
+	ReplaceString(result, std::string("\\"), std::string("\\\\"));
+	ReplaceString(result, std::string("'"), std::string("''"));
+	result.append(std::string("'"));
 
 	if (BackendMinimumVersion(8, 1))
 	{
-		if (result.Contains(wxT("\\")))
-			result.Prepend(wxT("E'"));
+		if (result.find_first_of(std::string("\\")))
+			result.insert(0, std::string("E'"));
 		else
-			result.Prepend(wxT("'"));
+			result.insert(0, std::string("'"));
 	}
 	else
-		result.Prepend(wxT("'"));
+		result.insert(0, std::string("'"));
 
 	return result;
 }
 
-
 bool DBconn::BackendMinimumVersion(int major, int minor)
 {
 	if (!majorVersion)
 	{
-		wxString version = ExecuteScalar(wxT("SELECT version();")) ;
-		sscanf(version.ToAscii(), "%*s %d.%d", &majorVersion, &minorVersion);
+		std::string version = ExecuteScalar(std::string("SELECT version();")) ;
+		sscanf(version.c_str(), "%*s %d.%d", &majorVersion, &minorVersion);
 	}
 	return majorVersion > major || (majorVersion == major && minorVersion >= minor);
 }
 
-
-DBconn *DBconn::InitConnection(const wxString &connectString)
+PGconn *DBconn::Get(const connInfo *cInfo)
 {
-	wxMutexLocker lock(s_PoolLock);
-
-	basicConnectString = connectString;
-	wxString dbname;
-
-	connInfo cnInfo = connInfo::getConnectionInfo(connectString);
-	if (cnInfo.isValid)
-	{
-		dbname = cnInfo.dbname;
-		basicConnectString = cnInfo.getConnectionString();
-		primaryConn = new DBconn(cnInfo.getConnectionString(), dbname);
-
-		if (!primaryConn)
-			LogMessage(_("Failed to create primary connection!"), LOG_ERROR);
-		primaryConn->dbname = dbname;
-		primaryConn->inUse = true;
-	}
-	else
-	{
-		primaryConn = NULL;
-		LogMessage(wxT("Primary connection string is not valid!"), LOG_ERROR);
-	}
-
-	return primaryConn;
-}
+	PGconn *ret = NULL;
 
-
-DBconn *DBconn::Get(const wxString &connStr, const wxString &db)
-{
-	if (db.IsEmpty() && connStr.IsEmpty())
+	if (cInfo == NULL)
 	{
-		LogMessage(_("Cannot allocate connection - no database or connection string specified!"), LOG_WARNING);
+		LogMessage( ("Cannot allocate connection - no database or connection string specified!"), LOG_WARNING);
 		return NULL;
 	}
 
-	wxMutexLocker lock(s_PoolLock);
-
-	DBconn *thisConn = primaryConn, *lastConn;
-
-	// find an existing connection
-	do
-	{
-		if (thisConn && ((!db.IsEmpty() && db == thisConn->dbname && connStr.IsEmpty()) || (!connStr.IsEmpty() && connStr == thisConn->connStr)) && !thisConn->inUse)
-		{
-			LogMessage(wxString::Format(_("Allocating existing connection to database %s"), thisConn->dbname.c_str()), LOG_DEBUG);
-			thisConn->inUse = true;
-			return thisConn;
-		}
-
-		lastConn = thisConn;
-		thisConn = thisConn->next;
-
-	}
-	while (thisConn != 0);
-
-
-	// No suitable connection was found, so create a new one.
-	DBconn *newConn = NULL;
-	newConn = new DBconn(connStr, db);
+	s_PoolLock.lock();
 
-	if (newConn->conn)
+	if(free_PGconn_map.count(connStr) > 0)
 	{
-		LogMessage(wxString::Format(_("Allocating new connection to database %s"), newConn->dbname.c_str()), LOG_DEBUG);
-		newConn->inUse = true;
-		newConn->prev = lastConn;
-		lastConn->next = newConn;
-	}
-	else
-	{
-		wxString warnMsg;
-		if (connStr.IsEmpty())
-			warnMsg = wxString::Format(_("Failed to create new connection to database '%s':'%s'"),
-			                           db.c_str(), newConn->GetLastError().c_str());
-		else
-			warnMsg = wxString::Format(_("Failed to create new connection for connection string '%s':%s"),
-			                           connStr.c_str(), newConn->GetLastError().c_str());
-		LogMessage(warnMsg, LOG_STARTUP);
-		return NULL;
+		std::multimap<std::string, PGconn * >::iterator it = free_PGconn_map.find(connStr);
+		// find an existing connection
+		ret = it->second;
+		free_PGconn_map.erase(it);
+		LogMessage( ("Reuse connection"), LOG_DEBUG);
 	}
+	s_PoolLock.unlock();
 
-	return newConn;
+	// No suitable connection was found
+	return ret;
 }
 
-
 void DBconn::Return()
 {
-	wxMutexLocker lock(s_PoolLock);
-
 	// Cleanup
-	this->ExecuteVoid(wxT("RESET ALL"));
-	this->lastError.Empty();
-
-	LogMessage(wxString::Format(_("Returning connection to database %s"), dbname.c_str()), LOG_DEBUG);
+	this->ExecuteVoid(std::string("RESET ALL"));
+	this->lastError.clear();
+	s_PoolLock.lock();
+	free_PGconn_map.insert( std::pair<std::string, PGconn *>(connStr, conn) );
+	conn = NULL;
+	s_PoolLock.unlock();
+	LogMessage(std::string("Returning connection to database ") + dbname, LOG_DEBUG);
 	inUse = false;
 }
 
+connInfo *DBconn::getConnInfo()
+{
+	return this->cnInfo;
+}
 
 void DBconn::ClearConnections(bool all)
 {
-	wxMutexLocker lock(s_PoolLock);
+	int deleted = 0;
+
+	s_PoolLock.lock();
 
 	if (all)
-		LogMessage(_("Clearing all connections"), LOG_DEBUG);
+		LogMessage( ("Clearing all connections"), LOG_DEBUG);
 	else
-		LogMessage(_("Clearing inactive connections"), LOG_DEBUG);
+		LogMessage( ("Clearing inactive connections"), LOG_DEBUG);
 
-	DBconn *thisConn = primaryConn, *deleteConn;
-	int total = 0, free = 0, deleted = 0;
-
-	if (thisConn)
+	if (all)
 	{
-
-		total++;
-
-		// Find the last connection
-		while (thisConn->next != 0)
+		for (std::multimap<std::string, PGconn * >::iterator it = free_PGconn_map.begin(); it != free_PGconn_map.end(); ++it)
 		{
-			total++;
-
-			if (!thisConn->inUse)
-				free++;
-
-			thisConn = thisConn->next;
+			++deleted;
+			PQfinish(it->second);
 		}
-		if (!thisConn->inUse)
-			free++;
+		free_PGconn_map.clear();
+	}
+	else
+	{
+		std::pair<std::multimap<std::string, PGconn * >::iterator, std::multimap<std::string, PGconn * >::iterator> it_range;
 
-		// Delete connections as required
-		// If a connection is not in use, delete it, and reset the next and previous
-		// pointers appropriately. If it is in use, don't touch it.
-		while (thisConn->prev != 0)
+		// equal_range(connStr) returns pair<iterator,iterator> representing the range
+		// of element with key connStr
+		it_range = free_PGconn_map.equal_range(connStr);
+
+		// Loop through range of maps of key connStr
+		for (std::multimap<std::string, PGconn * >::iterator it2 = it_range.first; it2 != it_range.second; ++it2)
 		{
-			if ((!thisConn->inUse) || all)
+			//cout << "  [" << (*it2).first << ", " << (*it2).second << "]" << endl;
+			if((*it2).second == conn)
 			{
-				deleteConn = thisConn;
-				thisConn = deleteConn->prev;
-				thisConn->next = deleteConn->next;
-				if (deleteConn->next)
-					deleteConn->next->prev = deleteConn->prev;
-				delete deleteConn;
-				deleted++;
+				free_PGconn_map.erase(it2);
+				PQfinish((*it2).second);
+				++deleted;
 			}
-			else
-			{
-				thisConn = thisConn->prev;
-			}
-		}
-
-		if (all)
-		{
-			delete thisConn;
-			deleted++;
 		}
+	}
 
-		wxString tmp;
-		tmp.Printf(_("Connection stats: total - %d, free - %d, deleted - %d"), total, free, deleted);
-		LogMessage(tmp, LOG_DEBUG);
+	if(deleted == 0) LogMessage( ("No connections found!"), LOG_DEBUG);
 
-	}
-	else
-		LogMessage(_("No connections found!"), LOG_DEBUG);
+	std::ostringstream oss;
+	oss << "Connection stats: total (free) - " << free_PGconn_map.size() << ", deleted - " << deleted << std::endl;
+	LogMessage(oss.str(), LOG_DEBUG);
 
+	s_PoolLock.unlock();
 }
 
-
-DBresult *DBconn::Execute(const wxString &query)
+DBresult *DBconn::Execute(const std::string &query)
 {
 	DBresult *res = new DBresult(this, query);
 	if (!res->IsValid())
@@ -282,23 +195,23 @@ DBresult *DBconn::Execute(const wxString &query)
 }
 
 
-wxString DBconn::ExecuteScalar(const wxString &query)
+std::string DBconn::ExecuteScalar(const std::string &query)
 {
-	int rows = -1;
+//	int rows = -1;
 	DBresult *res = Execute(query);
-	wxString data;
+	std::string data;
 	if (res)
 	{
 		data = res->GetString(0);
-		rows = res->RowsAffected();
+		//rows = res->RowsAffected();
 		delete res;
 		return data;
 	}
-	return wxEmptyString;
+	return std::string("");
 }
 
 
-int DBconn::ExecuteVoid(const wxString &query)
+int DBconn::ExecuteVoid(const std::string &query)
 {
 	int rows = -1;
 	DBresult *res = Execute(query);
@@ -311,75 +224,66 @@ int DBconn::ExecuteVoid(const wxString &query)
 }
 
 
-wxString DBconn::GetLastError()
+std::string DBconn::GetLastError()
 {
 	// Return the last error message, minus any trailing line ends
-	if (lastError.substr(lastError.length() - 2, 2) == wxT("\r\n")) // DOS
-		return lastError.substr(0, lastError.length() - 2);
-	else if (lastError.substr(lastError.length() - 1, 1) == wxT("\n")) // Unix
-		return lastError.substr(0, lastError.length() - 1);
-	else if (lastError.substr(lastError.length() - 1, 1) == wxT("\r")) // Mac
-		return lastError.substr(0, lastError.length() - 1);
-	else
-		return lastError;
+	return rtrim(lastError);
 }
 
 ///////////////////////////////////////////////////////7
 
-DBresult::DBresult(DBconn *conn, const wxString &query)
+DBresult::DBresult(DBconn *conn, const std::string &query)
 {
-	wxCharBuffer cstrUTF = query.mb_str(wxConvUTF8);
-	result = PQexec(conn->conn, cstrUTF);
+	//wxCharBuffer cstrUTF = query.mb_str(wxConvUTF8);
+	result = PQexec(conn->conn, query.c_str());
 	currentRow = 0;
 	maxRows = 0;
 
 	if (result)
 	{
 		int rc = PQresultStatus(result);
-		conn->SetLastResult(rc);
 		if (rc == PGRES_TUPLES_OK)
 			maxRows = PQntuples(result);
 		else if (rc != PGRES_COMMAND_OK)
 		{
-			conn->lastError = wxString::FromAscii(PQerrorMessage(conn->conn));
-			LogMessage(wxT("Query error: ") + conn->lastError, LOG_WARNING);
+			conn->lastError = std::string(PQerrorMessage(conn->conn));
+			LogMessage(("Query error: ") + conn->lastError, LOG_WARNING);
 			PQclear(result);
 			result = 0;
 		}
 	}
 	else
-		conn->lastError = wxString::FromAscii(PQerrorMessage(conn->conn));
-
+		conn->lastError = std::string(PQerrorMessage(conn->conn));
+	std::ostringstream oss;
+	oss << "Query: " << query << " currentRow: " << currentRow << " maxRow: " << maxRows;
+	LogMessage(oss.str(), LOG_DEBUG);
 }
 
-
 DBresult::~DBresult()
 {
 	if (result)
 		PQclear(result);
 }
 
-
-wxString DBresult::GetString(int col) const
+std::string DBresult::GetString(int col) const
 {
-	wxString str;
+	std::string str;
 
 	if (result && currentRow < maxRows && col >= 0)
 	{
-		str = wxString::FromAscii(PQgetvalue(result, currentRow, col));
+		str = std::string(PQgetvalue(result, currentRow, col));
 	}
 	return str;
 }
 
-
-wxString DBresult::GetString(const wxString &colname) const
+std::string DBresult::GetString(const std::string &colname) const
 {
-	wxCharBuffer cstrUTF = colname.mb_str(wxConvUTF8);
-	int col = PQfnumber(result, cstrUTF);
+	//wxCharBuffer cstrUTF = colname.mb_str(wxConvUTF8);
+	int col = PQfnumber(result, colname.c_str());
 	if (col < 0)
 	{
 		// fatal: not found
-		return wxT("");
+		return std::string("");
 	}
 	return GetString(col);
 }
@@ -388,41 +292,49 @@ wxString DBresult::GetString(const wxString &colname) const
 
 bool connInfo::IsValidIP()
 {
-	if (host.IsEmpty())
+	if (host.empty())
 		return false;
 
 	// check for IPv4 format
-	wxStringTokenizer tkip4(host, wxT("."));
+	std::string token;
+
+	std::istringstream tkip(host);
 	int count = 0;
 
-	while (tkip4.HasMoreTokens())
+	// Unix Domain Sockets a la '/tmp/._socket_5432'
+	if( host.find_first_of('/') != std::string::npos) return false;
+
+	while (std::getline(tkip, token, '.'))
 	{
 		unsigned long val = 0;
-		if (!tkip4.GetNextToken().ToULong(&val))
-			break;
+		std::istringstream conv(token);
+		if (!(conv >> val)) 	break;
+
 		if (count == 0 || count == 3)
-			if (val > 0 && val < 255)
-				count++;
-			else
-				break;
-		else if (val >= 0 && val < 255)
-			count++;
+		{
+			if (val > 0 && val < 255)  	count++;
+			else break;
+		}
 		else
-			break;
+		{
+			//if (val >= 0 && val < 255) count++;
+			if (val < 255) count++;
+			else break;
+		}
 	}
 
 	if (count == 4)
 		return true;
 
 	// check for IPv6 format
-	wxStringTokenizer tkip6(host, wxT(":"));
 	count = 0;
 
-	while (tkip6.HasMoreTokens())
+	while (std::getline(tkip, token, ':'))
 	{
-		unsigned long val = 0;
-		wxString strVal = tkip6.GetNextToken();
-		if (strVal.Length() > 4 || !strVal.ToULong(&val, 16))
+// TODO make it better
+//		unsigned long val = 0;
+		//std::string strVal = tkip6.GetNextToken();
+		if (token.size() > 4 ) //|| !strVal.ToULong(&val, 16))
 			return false;
 		count++;
 	}
@@ -434,118 +346,177 @@ bool connInfo::IsValidIP()
 	return false;
 }
 
-
-wxString connInfo::getConnectionString()
+std::string connInfo::getConnectionString()
 {
-	wxString connStr;
+	std::ostringstream connStr, str_port, str_connection_timeout;
 
 	// Check if it has valid connection info
-	if (!isValid)
-		return connStr;
+	//if (!isValid) return connStr.str();
 
 	// User
-	connStr = wxT("user=") + user;
+	connStr << " user=" << user;
 
-	// Port
-	if (port != 0)
+	// Port as INT ??? Why
+	if (port != "0")
 	{
-		wxString portStr;
-		portStr.Printf(wxT("%ld"), port);
-		connStr += wxT(" port=") + portStr;
+		str_port << port;
+		connStr << " port=" << port;
 	}
 
 	// host or hostaddr
-	if (!host.IsEmpty())
+	if (!host.empty())
+	{
 		if (IsValidIP())
-			connStr += wxT(" hostaddr=") + host;
+		{
+			connStr << " hostaddr=" << host;
+			//LogMessage(std::string("     ValidIP      : "), LOG_DEBUG);
+		}
 		else
-			connStr += wxT(" host=") + host;
-
+		{
+			connStr << " host=" << host;
+			//LogMessage(std::string("    NON ValidIP   : "), LOG_DEBUG);
+		}
+	}
 	// connection timeout
-	if (connection_timeout != 0)
+	if (connection_timeout != "0")
 	{
-		wxString val;
-		val.Printf(wxT("%ld"), connection_timeout);
-		connStr += wxT(" connection_timeout=") + val;
+		str_connection_timeout << connection_timeout;
+		connStr << " connection_timeout=" << connection_timeout;
 	}
 
 	// password
-	if (!password.IsEmpty())
-		connStr += wxT(" password=") + password;
-
-	if (!dbname.IsEmpty())
-		connStr += wxT(" dbname=") + dbname;
-
-	LogMessage(wxString::Format(_("Connection Information:")), LOG_DEBUG);
-	LogMessage(wxString::Format(_("     user         : %s"), user.c_str()), LOG_DEBUG);
-	LogMessage(wxString::Format(_("     port         : %ld"), port), LOG_DEBUG);
-	LogMessage(wxString::Format(_("     host         : %s"), host.c_str()), LOG_DEBUG);
-	LogMessage(wxString::Format(_("     dbname       : %s"), dbname.c_str()), LOG_DEBUG);
-	LogMessage(wxString::Format(_("     password     : %s"), password.c_str()), LOG_DEBUG);
-	LogMessage(wxString::Format(_("     conn timeout : %ld"), connection_timeout), LOG_DEBUG);
-
-	return connStr;
+	if (!password.empty())
+		connStr << " password=" << password;
+
+	if (!dbname.empty())
+		connStr << " dbname=" << dbname;
+	/*
+	    LogMessage(std::string("Connection Information:"), LOG_DEBUG);
+	    LogMessage(std::string("     user         : ") + user, LOG_DEBUG);
+	    LogMessage(std::string("     port         : ") + str_port.str(), LOG_DEBUG);
+	    LogMessage(std::string("     host         : ") + host, LOG_DEBUG);
+	    LogMessage(std::string("     hostaddr     : ") + hostaddr, LOG_DEBUG);
+	    LogMessage(std::string("     dbname       : ") + dbname, LOG_DEBUG);
+	    LogMessage(std::string("     password     : ") + password, LOG_DEBUG);
+	    LogMessage(std::string("     conn timeout : ") + str_connection_timeout.str(), LOG_DEBUG);
+	    LogMessage(std::string("     conn string  : ") + connStr.str(), LOG_DEBUG);
+	*/
+	return connStr.str();
 }
 
-
-connInfo connInfo::getConnectionInfo(wxString connStr)
+bool connInfo::setConnectionString(std::string str_conn)
 {
-	connInfo cnInfo;
-
-	wxRegEx propertyExp;
-
-	// Remove the white-space(s) to match the following format
-	// i.e. prop=value
-	bool res = propertyExp.Compile(wxT("(([ ]*[\t]*)+)="));
-
-	propertyExp.ReplaceAll(&connStr, wxT("="));
-
-	res = propertyExp.Compile(wxT("=(([ ]*[\t]*)+)"));
-	propertyExp.ReplaceAll(&connStr, wxT("="));
-
-	// Seperate all the prop=value patterns
-	wxArrayString tokens = wxStringTokenize(connStr, wxT("\t \n\r"));
-
-	unsigned int index = 0;
-	while (index < tokens.Count())
+	std::string key;
+	std::string val;
+	bool ret = false, valtrim = false;
+	std::size_t anf;
+
+	// example key-value connect string: host = AAA password = "dasd d asd as" password = 'a aa' user= thst
+	// parse from left to right
+	std::size_t pos = str_conn.find_first_of('=');
+	while(pos != std::string::npos)
 	{
-		wxString prop, value;
 
-		wxArrayString pairs = wxStringTokenize(tokens[index++], wxT("="));
-
-		if (pairs.GetCount() != 2)
-			return cnInfo;
-
-		prop = pairs[0];
-		value = pairs[1];
-
-		if (prop.CmpNoCase(wxT("user")) == 0)
-			cnInfo.user = value;
-		else if (prop.CmpNoCase(wxT("host")) == 0 || prop.CmpNoCase(wxT("hostAddr")) == 0)
-			cnInfo.host = value;
-		else if (prop.CmpNoCase(wxT("port")) == 0)
+		// extract key part
+		key = str_conn.substr(0, pos);
+		trim(key);
+		//LogMessage("KEY: "+key,LOG_DEBUG);
+		// cut key part off from connect string
+		str_conn = str_conn.substr(pos + 1, str_conn.size() - pos - 1);
+		ltrim(str_conn);
+		//LogMessage("CS: "+str_conn,LOG_DEBUG);
+		if(str_conn[0] == '"')
 		{
-			if (!value.ToULong(&cnInfo.port))
-				// port must be an unsigned integer
-				return cnInfo;
+			pos = str_conn.find_first_of('"', 1);
+			anf = 1;
+			valtrim = false;
 		}
-		else if (prop.CmpNoCase(wxT("password")) == 0)
-			cnInfo.password = value;
-		else if (prop.CmpNoCase(wxT("connection_timeout")) == 0)
+		else if(str_conn[0] == '\'')
 		{
-			if (!value.ToULong(&cnInfo.connection_timeout))
-				// connection timeout must be an unsigned interger
-				return cnInfo;
+			pos = str_conn.find_first_of("'", 1);
+			anf = 1;
+			valtrim = false;
 		}
-		else if (prop.CmpNoCase(wxT("dbname")) == 0)
-			cnInfo.dbname = value;
 		else
-			// Not valid property found
-			return cnInfo;
+		{
+			pos = str_conn.find_first_of(" ", 0);
+			anf = 0;
+			valtrim = true;
+		}
+		// extract value part
+		val = str_conn.substr(anf, pos - anf);
+		if(valtrim) trim(val);
+		//LogMessage("VAL: "+val,LOG_DEBUG);
+		// cut val part off from connect string
+		str_conn = str_conn.substr(pos + 1, str_conn.size() - pos - 1);
+		ltrim(str_conn);
+		//LogMessage("CS: "+str_conn,LOG_DEBUG);
+		// set next position
+		pos = str_conn.find_first_of('=');
+
+		// set option
+		ret = setKeyValue(key, val);
 	}
+	return ret;
+}
+
+bool connInfo::setKeyValue(std::string key, std::string val)
+{
+	trim(key);
+	trim(val);
+	boost::to_upper(key);
+
+	if (std::string("USER") == key)
+	{
+		user = val;
+		return true;
+	}
+	else if(std::string("HOST") == key)
+	{
+		host = val;
+		return true;
+	}
+	else if(std::string("HOSTADDR") == key)
+	{
+		hostaddr = val;
+		return true;
+	}
+	else if(std::string("PORT") == key)
+	{
+		port = val;
+		return true;
+	}
+	else if ((std::string("PASSWORD")) == key)
+	{
+		password = val;
+		return true;
+	}
+	else if (std::string("CONNECTION_TIMEOUT") == key)
+	{
+		connection_timeout = val;
+		return true;
+	}
+	else if(std::string("DBNAME") == key)
+	{
+		dbname = val;
+		return true;
+	}
+	return false;
+}
+
+connInfo connInfo::getConnectionInfo()
+{
+	connInfo cnInfo;
+
+	cnInfo.user = user;
+	cnInfo.host = host;
+	cnInfo.password = password;
+	cnInfo.dbname = dbname;
+	cnInfo.host = host;
+	cnInfo.hostaddr = hostaddr;
 
 	// If user, dbname & host all are blank than we will consider this an invalid connection string
-	if (cnInfo.user.IsEmpty() && cnInfo.dbname.IsEmpty() && cnInfo.host.IsEmpty())
+	if (cnInfo.user.empty() && cnInfo.dbname.empty() && cnInfo.host.empty())
 		cnInfo.isValid = false;
 	else
 		cnInfo.isValid = true;
@@ -553,3 +524,4 @@ connInfo connInfo::getConnectionInfo(wxString connStr)
 	return cnInfo;
 }
 
+
diff --git a/include/connection.h b/include/connection.h
index f56a279..ed0429c 100644
--- a/include/connection.h
+++ b/include/connection.h
@@ -9,116 +9,84 @@
 //
 //////////////////////////////////////////////////////////////////////////
 
-
 #ifndef CONNECTION_H
 #define CONNECTION_H
 
-#include <libpq-fe.h>
+#include <pgsql/libpq-fe.h>
 
 class DBresult;
-
+class connInfo;
 
 class DBconn
 {
-protected:
-	DBconn(const wxString &, const wxString &);
+public:
+	DBconn(connInfo *cInfo);
 	~DBconn();
 
-public:
-	wxString qtDbString(const wxString &value);
+	std::string qtDbString(const std::string &value);
 
 	bool BackendMinimumVersion(int major, int minor);
 
-	static DBconn *Get(const wxString &connStr, const wxString &db);
-	static DBconn *InitConnection(const wxString &connectString);
+	PGconn *Get(const connInfo *cInfo);
+
+	void ClearConnections(bool allIncludingPrimary = false);
 
-	static void ClearConnections(bool allIncludingPrimary = false);
-	static void SetBasicConnectString(const wxString &bcs)
+	void SetBasicConnectString(const std::string &bcs)
 	{
 		basicConnectString = bcs;
 	}
-	static const wxString &GetBasicConnectString()
+	const std::string &GetBasicConnectString()
 	{
 		return basicConnectString;
 	}
 
-	wxString GetLastError();
-	wxString GetDBname()
+	std::string GetLastError();
+	std::string GetDBname()
 	{
 		return dbname;
 	}
-
 	bool IsValid()
 	{
 		return conn != 0;
 	}
 
-        bool LastCommandOk()
-        {
-                return IsCommandOk((ExecStatusType)lastResult);
-        }
-
-        bool IsCommandOk(ExecStatusType ret)
-        {
-                switch (ret)
-                {
-                        case PGRES_COMMAND_OK:
-                        case PGRES_TUPLES_OK:
-                        case PGRES_COPY_OUT:
-                        case PGRES_COPY_IN:
-#if (PG_VERSION_NUM >= 90100)
-                        case PGRES_COPY_BOTH:
-#endif
-                                return true;
-                        default:
-                                return false;
-                };
-        }
-
-        void SetLastResult(int res)
-        {
-                lastResult = res;
-        }
-
-        int GetLastResult()
-        {
-                return lastResult;
-        }
-	
-	DBresult *Execute(const wxString &query);
-	wxString ExecuteScalar(const wxString &query);
-	int ExecuteVoid(const wxString &query);
+	DBresult *Execute(const std::string &query);
+	std::string ExecuteScalar(const std::string &query);
+	int ExecuteVoid(const std::string &query);
 	void Return();
 
+	connInfo *getConnInfo();
+
 private:
-	bool Connect(const wxString &connectString);
+	bool Connect(const std::string &connectString);
 
 	int minorVersion, majorVersion;
 
 protected:
-	static wxString basicConnectString;
-	static DBconn *primaryConn;
+	std::string basicConnectString;
+
+	connInfo *cnInfo;
 
-	wxString dbname, lastError, connStr;
+	std::string dbname, lastError, connStr;
 	PGconn *conn;
-	DBconn *next, *prev;
 	bool inUse;
-	int lastResult;
+
 	friend class DBresult;
 
+	static std::multimap<std::string, PGconn *> free_PGconn_map;
+	static boost::mutex s_PoolLock;
 };
 
-
 class DBresult
 {
 protected:
-	DBresult(DBconn *conn, const wxString &query);
+	DBresult(DBconn *conn, const std::string &query);
 
 public:
 	~DBresult();
 
-	wxString GetString(int col) const;
-	wxString GetString(const wxString &colname) const;
+	std::string GetString(int col) const;
+	std::string GetString(const std::string &colname) const;
 
 	bool IsValid() const
 	{
@@ -128,6 +96,7 @@ public:
 	{
 		return currentRow < maxRows;
 	}
+
 	void MoveNext()
 	{
 		if (currentRow < maxRows) currentRow++;
@@ -135,7 +104,10 @@ public:
 
 	long RowsAffected() const
 	{
-		return atol(PQcmdTuples(result));
+		long n;
+		std::istringstream in(PQcmdTuples(result));
+		in >> n;
+		return n;
 	}
 
 protected:
@@ -152,21 +124,43 @@ public:
 	connInfo()
 	{
 		isValid = false;
-		connection_timeout = 0;
-		port = 0;
+		connection_timeout = "0";
+		port = "5432";
 	}
 
-private:
-	wxString      user;
-	unsigned long port;
-	wxString      host;
-	wxString      dbname;
-	unsigned long connection_timeout;
-	wxString      password;
-	bool          isValid;
-
-	wxString getConnectionString();
-	static connInfo getConnectionInfo(wxString connStr);
+	//copy constructor
+	connInfo(connInfo *preInfo)
+	{
+		isValid = false;
+
+		user = preInfo->user;
+		port = preInfo->port;
+		host = preInfo->host;
+		hostaddr = preInfo->hostaddr;
+		dbname = preInfo->dbname;
+		connection_timeout = preInfo->connection_timeout;
+		password = preInfo->password;
+		if(connection_timeout.empty()) connection_timeout = "0";
+		if(port.empty() || port == "0") port = "5432";
+	}
+
+	std::string      user;
+	std::string      port;
+	std::string      host;
+	std::string      hostaddr;
+	std::string      dbname;
+	std::string      connection_timeout;
+	std::string      password;
+	bool             isValid;
+
+	std::string backendPid;
+
+	std::string getConnectionString();
+
+	connInfo getConnectionInfo();
+
+	bool setConnectionString(std::string str_conn);
+	bool setKeyValue(std::string key, std::string val);
 
 protected:
 	bool IsValidIP();
diff --git a/include/job.h b/include/job.h
index fb7ba9e..8098596 100644
--- a/include/job.h
+++ b/include/job.h
@@ -13,43 +13,44 @@
 #ifndef JOB_H
 #define JOB_H
 
-#include <wx/wx.h>
-
-
 class Job
 {
 public:
-	Job(DBconn *conn, const wxString &jid);
+	Job(connInfo *cInfo, const std::string &jid);
 	~Job();
 
 	int Execute();
 	bool Runnable()
 	{
-		return status == wxT("r");
+		return status == std::string("r");
 	}
 
 protected:
 	DBconn *threadConn;
-	wxString jobid, logid;
-	wxString status;
+	std::string jobid, logid;
+	std::string status;
 };
 
 
-class JobThread : public wxThread
+class JobThread
 {
 public:
-	JobThread(const wxString &jid);
+	JobThread(const std::string &jid, connInfo *serviceConnInfo);
+
+	bool finished();
+
 	~JobThread();
-	bool Runnable()
-	{
-		return runnable;
-	}
 
-	virtual void *Entry();
+	void start();
+	void stop();
+	void run();
+protected:
+	bool m_stop;
 
 private:
-	wxString jobid;
-	bool runnable;
+	boost::thread m_thread;
+	connInfo *m_serviceConnInfo;
+	std::string jobid;
 	Job *job;
 };
 
diff --git a/include/misc.h b/include/misc.h
index 9a94fd5..c4eb095 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -13,11 +13,11 @@
 #ifndef MISC_H
 #define MISC_H
 
-
 void WaitAWhile(const bool waitLong = false);
-void setOptions(int argc, char **argv, const wxString &executable);
-wxString getArg(int &argc, char **&argv);
-wxString NumToStr(const long l);
+void setOptions(boost::program_options::variables_map vm, boost::shared_ptr<boost::program_options::options_description> desc, connInfo *cInfo);
+std::string getArg(int &argc, char ** &argv);
+
+void ReplaceString(std::string &subject, const std::string &search, const std::string &replace);
 
 #endif // MISC_H
 
diff --git a/include/pgAgent.h b/include/pgAgent.h
index 966d212..5b48ba2 100644
--- a/include/pgAgent.h
+++ b/include/pgAgent.h
@@ -13,49 +13,88 @@
 #ifndef PGAGENT_H
 #define PGAGENT_H
 
-// Disable all the GUI classes that might get pulled in through the headers
-#define wxUSE_GUI 0
+#include <fstream>
+#include <iostream>
+#include <stdlib.h>
+#include <sstream>
+#include <boost/thread.hpp>
+#include <boost/thread/mutex.hpp>
+#include <boost/program_options.hpp>
 
-#include <wx/wx.h>
+namespace po = boost::program_options;
 
-#include "misc.h"
-#include "connection.h"
-#include "job.h"
+#include <boost/shared_ptr.hpp>
+#include <boost/algorithm/string.hpp>
+#include <set>
+#include <map>
+#include <utility>
+#include <vector>
+#include <algorithm>
+#include <functional>
+#include <cctype>
+#include <locale>
 
 extern long longWait;
 extern long shortWait;
 extern long minLogLevel;
-extern wxString connectString;
-extern wxString serviceDBname;
-extern wxString backendPid;
 
-#ifndef __WXMSW__
+//#ifndef __WXMSW__
 extern bool runInForeground;
-extern wxString logFile;
-#endif
+extern std::string logFile;
+//#endif
 
 // Log levels
 enum
 {
-	LOG_ERROR = 0,
-	LOG_WARNING,
-	LOG_DEBUG,
-	// NOTE:
-	//     "STARTUP" will be used to log messages for any LogLevel
-	//     Use it for logging database connection errors which we
-	//     don't want to abort the whole shebang.
-	LOG_STARTUP = 15
+    LOG_ERROR = 0,
+    LOG_WARNING,
+    LOG_DEBUG,
+    // NOTE:
+    //     "STARTUP" will be used to log messages for any LogLevel
+    //     Use it for logging database connection errors which we
+    //     don't want to abort the whole shebang.
+    LOG_STARTUP = 15
 };
 
 // Prototypes
-void LogMessage(wxString msg, int level);
-void MainLoop();
+class connInfo;
+void LogMessage(std::string msg, int level);
+std::string CreateTempFileName(std::string prefix);
+int Mkdir(std::string dirname, mode_t rights);
+int RemoveFile(std::string filename);
+int Rmdir(std::string dirname);
+int Chmod(std::string dirname, mode_t rights);
+void MainLoop(connInfo *serviceConnInfo);
 
 #ifdef __WIN32__
 #include <windows.h>
 void CheckForInterrupt();
-HANDLE win32_popen_r(const TCHAR *command, HANDLE &handle);
+HANDLE win32_popen_r(const TCHAR *command);
 #endif
 
+// trim from start
+inline std::string &ltrim(std::string &s)
+{
+	s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
+	return s;
+}
+
+// trim from end
+inline std::string &rtrim(std::string &s)
+{
+	s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
+	return s;
+}
+
+// trim from both ends
+inline std::string &trim(std::string &s)
+{
+	return ltrim(rtrim(s));
+}
+
+#include "misc.h"
+#include "connection.h"
+#include "job.h"
+
 #endif // PGAGENT_H
 
diff --git a/job.cpp b/job.cpp
index f9bf487..d2d8bae 100644
--- a/job.cpp
+++ b/job.cpp
@@ -11,44 +11,36 @@
 
 #include "pgAgent.h"
 
-#include <wx/file.h>
-#include <wx/filefn.h>
-#include <wx/filename.h>
-#include <wx/process.h>
-
 #include <sys/types.h>
 
+
 #ifndef __WIN32__
 #include <errno.h>
 #include <sys/wait.h>
 #endif
 
-Job::Job(DBconn *conn, const wxString &jid)
+Job::Job(connInfo *cInfo, const std::string &jid): threadConn( new DBconn(cInfo)), jobid(jid), status("")
 {
-	threadConn = conn;
-	jobid = jid;
-	status = wxT("");
-
-	LogMessage(wxString::Format(_("Starting job: %s"), jobid.c_str()), LOG_DEBUG);
+	LogMessage(std::string("Starting job: ") + jobid, LOG_DEBUG);
 
 	int rc = threadConn->ExecuteVoid(
-	             wxT("UPDATE pgagent.pga_job SET jobagentid=") + backendPid + wxT(", joblastrun=now() ")
-	             wxT(" WHERE jobagentid IS NULL AND jobid=") + jobid);
+	             std::string("UPDATE pgagent.pga_job SET jobagentid=") + cInfo->backendPid + std::string(", joblastrun=now() ") +
+	             std::string(" WHERE jobagentid IS NULL AND jobid=") + jobid);
 
 	if (rc == 1)
 	{
 		DBresult *id = threadConn->Execute(
-		                   wxT("SELECT nextval('pgagent.pga_joblog_jlgid_seq') AS id"));
+		                   std::string("SELECT nextval('pgagent.pga_joblog_jlgid_seq') AS id"));
 		if (id)
 		{
-			logid = id->GetString(wxT("id"));
+			logid = id->GetString(std::string("id"));
 
 			DBresult *res = threadConn->Execute(
-			                    wxT("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ")
-			                    wxT("VALUES (") + logid + wxT(", ") + jobid + wxT(", 'r')"));
+			                    std::string("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ") +
+			                    std::string("VALUES (") + logid + std::string(", ") + jobid + std::string(", 'r')"));
 			if (res)
 			{
-				status = wxT("r");
+				status = std::string("r");
 				delete res;
 			}
 			delete id;
@@ -56,60 +48,61 @@ Job::Job(DBconn *conn, const wxString &jid)
 	}
 }
 
-
 Job::~Job()
 {
-	if (status != wxT(""))
+	if (status != std::string(""))
 	{
 		threadConn->ExecuteVoid(
-		    wxT("UPDATE pgagent.pga_joblog ")
-		    wxT("   SET jlgstatus='") + status + wxT("', jlgduration=now() - jlgstart ")
-		    wxT(" WHERE jlgid=") + logid + wxT(";\n")
+		    std::string("UPDATE pgagent.pga_joblog ") +
+		    std::string("   SET jlgstatus='") + status + std::string("', jlgduration=now() - jlgstart ") +
+		    std::string(" WHERE jlgid=") + logid + std::string(";\n") +
 
-		    wxT("UPDATE pgagent.pga_job ")
-		    wxT("   SET jobagentid=NULL, jobnextrun=NULL ")
-		    wxT(" WHERE jobid=") + jobid
+		    std::string("UPDATE pgagent.pga_job ") +
+		    std::string("   SET jobagentid=NULL, jobnextrun=NULL ") +
+		    std::string(" WHERE jobid=") + jobid
 		);
 	}
 	threadConn->Return();
 
-	LogMessage(wxString::Format(_("Completed job: %s"), jobid.c_str()), LOG_DEBUG);
+	LogMessage(std::string("Completed job: ") + jobid, LOG_DEBUG);
 }
 
-
 int Job::Execute()
 {
+	std::ostringstream oss;
 	int rc = 0;
-	bool succeeded = false;
+	DBconn *stepConn = NULL;
+
 	DBresult *steps = threadConn->Execute(
-	                      wxT("SELECT * ")
-	                      wxT("  FROM pgagent.pga_jobstep ")
-	                      wxT(" WHERE jstenabled ")
-	                      wxT("   AND jstjobid=") + jobid +
-	                      wxT(" ORDER BY jstname, jstid"));
+	                      std::string("SELECT * ") +
+	                      std::string("  FROM pgagent.pga_jobstep ") +
+	                      std::string(" WHERE jstenabled ") +
+	                      std::string("   AND jstjobid=") + jobid +
+	                      std::string(" ORDER BY jstname, jstid"));
 
 	if (!steps)
 	{
-		status = wxT("i");
+		status = std::string("i");
 		return -1;
 	}
-
+	oss << "Job::Execute() STEPS: " << steps->RowsAffected() << std::endl;
+	LogMessage(oss.str(), LOG_DEBUG);
 	while (steps->HasData())
 	{
-		DBconn *stepConn;
-		wxString jslid, stepid, jpecode, output;
+		std::string jslid, stepid, jpecode;
+		std::ostringstream output;
 
-		stepid = steps->GetString(wxT("jstid"));
+		stepid = steps->GetString(std::string("jstid"));
 
 		DBresult *id = threadConn->Execute(
-		                   wxT("SELECT nextval('pgagent.pga_jobsteplog_jslid_seq') AS id"));
+		                   std::string("SELECT nextval('pgagent.pga_jobsteplog_jslid_seq') AS id"));
 		if (id)
 		{
-			jslid = id->GetString(wxT("id"));
+			jslid = id->GetString(std::string("id"));
 			DBresult *res = threadConn->Execute(
-			                    wxT("INSERT INTO pgagent.pga_jobsteplog(jslid, jsljlgid, jsljstid, jslstatus) ")
-			                    wxT("SELECT ") + jslid + wxT(", ") + logid + wxT(", ") + stepid + wxT(", 'r'")
-			                    wxT("  FROM pgagent.pga_jobstep WHERE jstid=") + stepid);
+			                    std::string("INSERT INTO pgagent.pga_jobsteplog(jslid, jsljlgid, jsljstid, jslstatus) ") +
+			                    std::string("SELECT ") + jslid + std::string(", ") + logid + std::string(", ") + stepid + std::string(", 'r'") +
+			                    std::string("  FROM pgagent.pga_jobstep WHERE jstid=") + stepid);
 
 			if (res)
 			{
@@ -123,129 +116,139 @@ int Job::Execute()
 
 		if (rc != 1)
 		{
-			status = wxT("i");
+			status = std::string("i");
 			return -1;
 		}
 
-		switch ((int) steps->GetString(wxT("jstkind"))[0])
+		output.clear();
+		switch ((int) steps->GetString(std::string("jstkind"))[0])
 		{
 			case 's':
 			{
-				wxString jstdbname = steps->GetString(wxT("jstdbname"));
-				wxString jstconnstr = steps->GetString(wxT("jstconnstr"));
+				std::string jstdbname = steps->GetString(std::string("jstdbname"));
+				std::string jstconnstr = steps->GetString(std::string("jstconnstr"));
 
-				stepConn = DBconn::Get(jstconnstr, jstdbname);
-				if (stepConn)
+				// copy connect infos from service connection
+				connInfo *sinfo = new connInfo(threadConn->getConnInfo());
+				// when extra connect_string specified
+				if( !jstconnstr.empty()) sinfo->setConnectionString(jstconnstr);
+				// when extra database specified
+				if( !jstdbname.empty()) sinfo->dbname = jstdbname;
+				LogMessage(std::string("Starting job: ") + jobid + " Connect: " + sinfo->getConnectionString(), LOG_DEBUG);
+
+				stepConn = new DBconn(sinfo);
+
+				if (stepConn != NULL)
 				{
-					LogMessage(wxString::Format(_("Executing SQL step %s (part of job %s)"), stepid.c_str(), jobid.c_str()), LOG_DEBUG);
-					rc = stepConn->ExecuteVoid(steps->GetString(wxT("jstcode")));
-					succeeded = stepConn->LastCommandOk();
-					output = stepConn->GetLastError();
-					stepConn->Return();
+					LogMessage(std::string("Executing SQL step " + stepid + " (part of job " + jobid + ")"), LOG_DEBUG);
+					rc = stepConn->ExecuteVoid(steps->GetString(std::string("jstcode")));
+					LogMessage(std::string("Executed SQL step " + stepid + " (Err-Meldung: " + stepConn->GetLastError() + ")"), LOG_DEBUG);
+					output <<  stepConn->GetLastError();
+					delete stepConn;
 				}
 				else
 				{
-					output = _("Couldn't get a connection to the database!");
-					succeeded = false;
+					output << ("Couldn't get a connection to the database!");
+					rc = -1;
 				}
 
-
 				break;
 			}
 			case 'b':
 			{
 				// Batch jobs are more complex thank SQL, for obvious reasons...
-				LogMessage(wxString::Format(_("Executing batch step %s (part of job %s)"), stepid.c_str(), jobid.c_str()), LOG_DEBUG);
+				LogMessage(std::string("Executing batch step " + stepid + " (part of job " + jobid + ")"), LOG_DEBUG);
 
 				// Get a temporary filename, then reuse it to create an empty directory.
-				wxString dirname = wxFileName::CreateTempFileName(wxT("pga_"));
-				if (dirname.Length() == 0)
+				std::string dirname = CreateTempFileName(std::string("pga_"));
+				if (dirname.empty())
 				{
-					output = _("Couldn't get a temporary filename!");
-					LogMessage(_("Couldn't get a temporary filename!"), LOG_WARNING);
+					output.clear();
+					output << ("Couldn't get a temporary filename!");
+					LogMessage(output.str(), LOG_WARNING);
 					rc = -1;
 					break;
 				}
 
-				;
-				if (!wxRemoveFile(dirname))
+				if (RemoveFile(dirname) != 0)
 				{
-					output.Printf(_("Couldn't remove temporary file: %s"), dirname.c_str());
-					LogMessage(output, LOG_WARNING);
+					output <<  "Couldn't remove temporary file: " << dirname << std::endl;
+					LogMessage(output.str(), LOG_WARNING);
 					rc = -1;
 					break;
 				}
 
-				if (!wxMkdir(dirname, 0700))
+				if (Mkdir(dirname, 0700) != 0)
 				{
-					output.Printf(_("Couldn't create temporary directory: %s"), dirname.c_str());
-					LogMessage(output, LOG_WARNING);
+					output << "Couldn't create temporary directory: " << dirname << std::endl;
+					LogMessage(output.str(), LOG_WARNING);
 					rc = -1;
 					break;
 				}
 
 #ifdef __WIN32__
-				wxString filename = dirname + wxT("\\") + jobid + wxT("_") + stepid + wxT(".bat");
+				std::string filename = dirname + std::string("\\") + jobid + std::string("_") + stepid + std::string(".bat");
 #else
-				wxString filename = dirname + wxT("/") + jobid + wxT("_") + stepid + wxT(".scr");
+				std::string filename = dirname + std::string("/") + jobid + std::string("_") + stepid + std::string(".scr");
 #endif
 
 				// Write the script
-				wxFile *file = new wxFile();
+				std::ofstream of;
+				of.open(filename.c_str(), std::ios::out | std::ios::app);
 
-				if (!file->Create(filename, true, wxS_IRUSR | wxS_IWUSR | wxS_IXUSR))
+				if(!of.is_open())
 				{
-					output.Printf(_("Couldn't create temporary script file: %s"), filename.c_str());
-					LogMessage(output, LOG_WARNING);
+					output << "Couldn't open temporary script file: " << filename << std::endl;
+					LogMessage(output.str(), LOG_WARNING);
+					RemoveFile(filename);
+					Rmdir(dirname);
 					rc = -1;
 					break;
 				}
 
-				if (!file->Open(filename, wxFile::write))
+				if (Chmod(filename, 0700) != 0 )
 				{
-					output.Printf(_("Couldn't open temporary script file: %s"), filename.c_str());
-					LogMessage(output, LOG_WARNING);
-					wxRemoveFile(filename);
-					wxRmdir(dirname);
+					output << "Couldn't create temporary script file: " << filename << std::endl;
+					LogMessage(output.str(), LOG_WARNING);
 					rc = -1;
 					break;
 				}
-
-				wxString code = steps->GetString(wxT("jstcode"));
+				std::string code = steps->GetString(std::string("jstcode"));
 
 				// Cleanup the code. If we're on Windows, we need to make all line ends \r\n,
 				// If we're on Unix, we need \n
-				code.Replace(wxT("\r\n"), wxT("\n"));
+				ReplaceString(code, std::string("\r\n"), std::string("\n"));
 #ifdef __WIN32__
-				code.Replace(wxT("\n"), wxT("\r\n"));
+				ReplaceString(code, std::string("\n"), std::string("\r\n"));
 #endif
 
-				if (!file->Write(code))
+				//if (!file->Write(code))
+				if(!of.good())
 				{
-					output.Printf(_("Couldn't write to temporary script file: %s"), filename.c_str());
-					LogMessage(output, LOG_WARNING);
-					wxRemoveFile(filename);
-					wxRmdir(dirname);
+					output << "Couldn't write to temporary script file: " << filename << std::endl;
+					LogMessage(output.str(), LOG_WARNING);
+					RemoveFile(filename);
+					Rmdir(dirname);
 					rc = -1;
 					break;
 				}
+				of << code;
+				of.close();
 
-				file->Close();
-				LogMessage(wxString::Format(_("Executing script file: %s"), filename.c_str()), LOG_DEBUG);
+				LogMessage(std::string("Executing script file: ") + filename, LOG_DEBUG);
 
 				// Execute the file and capture the output
 #ifdef __WIN32__
 				// The Windows way
-				HANDLE h_script, h_process;
+				HANDLE h_script;
 				DWORD dwRead;
 				char chBuf[4098];
 
-				h_script = win32_popen_r(filename.wc_str(), h_process);
+				h_script = win32_popen_r(filename.wc_str());
 				if (!h_script)
 				{
-					output.Printf(_("Couldn't execute script: %s, GetLastError() returned %d, errno = %d"), filename.c_str(), GetLastError(), errno);
-					LogMessage(output, LOG_WARNING);
-					CloseHandle(h_process);
+					output << "Couldn't execute script: " << filename << ", GetLastError() returned " << GetLastError() << ", errno = " << errno << "" << std::endl;
+					LogMessage(output.str(), LOG_WARNING);
 					rc = -1;
 					break;
 				}
@@ -260,11 +263,10 @@ int Job::Execute()
 							break;
 
 						chBuf[dwRead] = 0;
-						output += wxString::FromAscii(chBuf);
+						output << (chBuf);
 					}
 				}
 
-
 				GetExitCodeProcess(h_process, (LPDWORD)&rc);
 				CloseHandle(h_process);
 				CloseHandle(h_script);
@@ -274,11 +276,11 @@ int Job::Execute()
 				FILE *fp_script;
 				char buf[4098];
 
-				fp_script = popen(filename.mb_str(wxConvUTF8), "r");
+				fp_script = popen(filename.c_str(), "r");
 				if (!fp_script)
 				{
-					output.Printf(_("Couldn't execute script: %s, errno = %d"), filename.c_str(), errno);
-					LogMessage(output, LOG_WARNING);
+					output << "Couldn't execute script: " << filename << ", errno = " << errno << std::endl;
+					LogMessage(output.str(), LOG_WARNING);
 					rc = -1;
 					break;
 				}
@@ -287,7 +289,7 @@ int Job::Execute()
 				while(!feof(fp_script))
 				{
 					if (fgets(buf, 4096, fp_script) != NULL)
-						output += wxString::FromAscii(buf);
+						output << (buf);
 				}
 
 				rc = pclose(fp_script);
@@ -296,97 +298,121 @@ int Job::Execute()
 					rc = WEXITSTATUS(rc);
 				else
 					rc = -1;
-
 #endif
 
-				// set success status for batch runs, be pessimistic by default
-				LogMessage(wxString::Format(_("Script return code: %d"), rc), LOG_DEBUG);
-				if (rc == 0)
-					succeeded = true;
-
 				// Delete the file/directory. If we fail, don't overwrite the script output in the log, just throw warnings.
-				if (!wxRemoveFile(filename))
+
+				if (RemoveFile(filename) != 0)
 				{
-					LogMessage(wxString::Format(_("Couldn't remove temporary script file: %s"), filename.c_str()), LOG_WARNING);
-					wxRmdir(dirname);
+					LogMessage(std::string("Couldn't remove temporary script file: ") + filename, LOG_WARNING);
 					break;
 				}
 
-				if (!wxRmdir(dirname))
+				if (Rmdir(dirname) != 0)
 				{
-					LogMessage(wxString::Format(_("Couldn't remove temporary directory: "), dirname.c_str()), LOG_WARNING);
+					LogMessage(std::string("Couldn't remove temporary directory: ") + dirname, LOG_WARNING);
 					break;
 				}
 
 				break;
 			}
+
 			default:
 			{
-				output = _("Invalid step type!");
-				status = wxT("i");
+				output << ("Invalid step type!");
+				status = std::string("i");
 				return -1;
 			}
 		}
 
-		wxString stepstatus;
-		if (succeeded)
-			stepstatus = wxT("s");
+		std::string stepstatus;
+		if (rc >= 0)
+		{
+			stepstatus = std::string("s");
+		}
 		else
-			stepstatus = steps->GetString(wxT("jstonerror"));
-
-		rc = threadConn->ExecuteVoid(
-		         wxT("UPDATE pgagent.pga_jobsteplog ")
-		         wxT("   SET jslduration = now() - jslstart, ")
-		         wxT("       jslresult = ") + NumToStr(rc) + wxT(", jslstatus = '") + stepstatus + wxT("', ")
-		         wxT("       jsloutput = ") + threadConn->qtDbString(output) + wxT(" ")
-		         wxT(" WHERE jslid=") + jslid);
-		if (rc != 1 || stepstatus == wxT("f"))
 		{
-			status = wxT("f");
+			stepstatus = steps->GetString(std::string("jstonerror"));
+		}
+
+		std::ostringstream oss;
+		oss << std::string("UPDATE pgagent.pga_jobsteplog ");
+		oss << std::string("   SET jslduration = now() - jslstart, ");
+		oss << std::string("       jslresult = ") << rc << std::string(", jslstatus = '") <<  stepstatus + std::string("', ");
+		oss << std::string("       jsloutput = ") << threadConn->qtDbString(output.str());
+		oss << std::string(" ") << std::string(" WHERE jslid=") << jslid;
+		rc = threadConn->ExecuteVoid(oss.str());
+		if (rc != 1 || stepstatus == std::string("f"))
+		{
+			status = std::string("f");
+			LogMessage(std::string("ERROR: UPDATE STEP STATUS Stepstatus=") + stepstatus, LOG_DEBUG);
 			return -1;
 		}
+		LogMessage(std::string("steps->MoveNext()"), LOG_DEBUG);
 		steps->MoveNext();
 	}
 	delete steps;
 
-	status = wxT("s");
+	status = std::string("s");
 	return 0;
 }
 
-
-
-JobThread::JobThread(const wxString &jid)
-	: wxThread(wxTHREAD_DETACHED)
+JobThread::JobThread(const std::string &jid, connInfo *serviceConnInfo): m_stop(false), m_serviceConnInfo(serviceConnInfo), jobid(jid)
 {
-	LogMessage(wxString::Format(_("Creating job thread for job %s"), jid.c_str()), LOG_DEBUG);
-
-	runnable = false;
-	jobid = jid;
+	LogMessage(std::string("JobThread(const std::string &jid, connInfo* serviceConnInfo) job thread job ") + jid, LOG_DEBUG);
+}
 
-	DBconn *threadConn = DBconn::Get(DBconn::GetBasicConnectString(), serviceDBname);
-	if (threadConn)
+JobThread::~JobThread()
+{
+	try
 	{
-		job = new Job(threadConn, jobid);
-
-		if (job->Runnable())
-			runnable = true;
+		stop();
+		LogMessage(std::string("Destroying JobThread for job ") + jobid, LOG_DEBUG);
+	}
+	catch(...)
+	{
+		LogMessage(std::string("Destroying JobThread for job ") + jobid, LOG_ERROR);
 	}
 }
 
-
-JobThread::~JobThread()
+void JobThread::run()
 {
-	LogMessage(wxString::Format(_("Destroying job thread for job %s"), jobid.c_str()), LOG_DEBUG);
+	try
+	{
+		if (!m_stop)
+		{
+			job = new Job(m_serviceConnInfo, jobid);
+			if(job != NULL)
+			{
+				job->Execute();
+				LogMessage(std::string("JobThread::run() - Destroying job thread for job ") + jobid, LOG_DEBUG);
+				delete job;
+			}
+			else
+			{
+				LogMessage(std::string("JobThread::run() - Job execute - ") + jobid, LOG_ERROR);
+			}
+		}
+	}
+	catch(...)
+	{
+		LogMessage(std::string("JobThread::run() - Destroying job thread for job ") + jobid, LOG_ERROR);
+	}
+	m_stop = true;
 }
 
+void JobThread::stop()
+{
+	m_stop = true;
+	m_thread.join();
+}
 
-void *JobThread::Entry()
+void JobThread::start()
 {
-	if (runnable)
-	{
-		job->Execute();
-		delete job;
-	}
+	m_thread = boost::thread(&JobThread::run, this);
+}
 
-	return(NULL);
+bool JobThread::finished()
+{
+	return m_stop;
 }
diff --git a/misc.cpp b/misc.cpp
index da9c4ee..a066f6c 100644
--- a/misc.cpp
+++ b/misc.cpp
@@ -10,100 +10,124 @@
 //////////////////////////////////////////////////////////////////////////
 
 #include "pgAgent.h"
-#include "connection.h"
 
-#ifndef __WXMSW__
 #include <unistd.h>
-#endif
 
-// In unix.c or win32.c
-void usage(const wxString &executable);
+namespace po = boost::program_options;
+// In unix.cpp or win32.cpp
 
-wxString getArg(int &argc, char **&argv)
+void setOptions(po::variables_map vm, boost::shared_ptr< po::options_description>  desc, connInfo *cInfo)
 {
-	wxString s;
-	if (argv[0][2])
-		s = wxString::FromAscii(argv[0] + 2);
-	else
+	std::string key, val;
+
+	if ( vm.count("foreground")  )
 	{
-		if (argc >= 1)
-		{
-			argc--;
-			argv++;
-			s = wxString::FromAscii(argv[0]);
-		}
-		else
-		{
-			// very bad!
-			LogMessage(_("Invalid command line argument"), LOG_ERROR);
-		}
+		std::cout << "foreground = true" << std::endl;
+		runInForeground = true;
+	}
+	if ( vm.count("time_poll")  )
+	{
+		shortWait = vm["time_poll"].as< int >();
+		std::cout << "time_poll=" << shortWait << std::endl;
+	}
+	if ( vm.count("retry_period")  )
+	{
+		longWait = vm["retry_period"].as< int >();
+		std::cout << "retry_period=" << longWait << std::endl;
+	}
+	if ( vm.count("logfile")  )
+	{
+		logFile = vm["logfile"].as< std::string >();
+		std::cout << "logfile=" << logFile << std::endl;
+	}
+	if ( vm.count("log_verbosity")  )
+	{
+		minLogLevel = vm["log_verbosity"].as< int >();
+		std::cout << "log_verbosity=" << minLogLevel << std::endl;
+	}
+	if ( vm.count("help")  )
+	{
+		std::cout << *desc << std::endl;
+		exit(1);
 	}
 
-	return s;
-}
+	if ( vm.count("connect_string")  )
+	{
+		std::vector<std::string> v_connect_string = vm["connect_string"].as< std::vector<std::string> >();
 
+		std::vector<std::string>::iterator it = v_connect_string.begin();
 
-void setOptions(int argc, char **argv, const wxString &executable)
-{
-	while (argc-- > 0)
-	{
-		if (argv[0][0] == '-')
+		while(it != v_connect_string.end())
 		{
-			switch (argv[0][1])
+			key = "";
+			val = "";
+			std::string temp = *it;
+			std::size_t pos = temp.find_first_of('=');
+			if(pos == std::string::npos)
 			{
-				case 't':
+				// Key stand alone
+				key = *it;
+				// get Value
+				++it;
+				// if next Token == (=) goto next
+				// eval value-token
+				temp = *it;
+				std::size_t pos = temp.find_first_of('=');
+				if(pos == std::string::npos)
 				{
-					int val = atoi(getArg(argc, argv).mb_str(wxConvUTF8));
-					if (val > 0)
-						shortWait = val;
-					break;
+					// val stand alone ==> wrong connection_string
+					throw;
 				}
-				case 'r':
+				else if(*it == "=")
 				{
-					int val = atoi(getArg(argc, argv).mb_str(wxConvUTF8));
-					if (val >= 10)
-						longWait = val;
-					break;
-				}
-				case 'l':
-				{
-					int val = atoi(getArg(argc, argv).mb_str(wxConvUTF8));
-					if (val >= 0 && val <= 2)
-						minLogLevel = val;
-					break;
-				}
-#ifndef __WXMSW__
-				case 'f':
-				{
-					runInForeground = true;
-					break;
+					// value is "="
+					// get next string, thus must be the value
+					++it;
+					val = *it;
+
 				}
-				case 's':
+				else if(pos == 0)
 				{
-					logFile = getArg(argc, argv);
-					break;
+					// value is "= value"
+					val = temp.substr(pos + 1, temp.size() - pos);
+					val = ltrim( val );
 				}
-#endif
-				default:
+				else
 				{
-					usage(executable);
-					exit(1);
+					// Error
+					throw;
 				}
+
 			}
+			else if(pos == temp.length() - 1)
+			{
+				//key with =
+				// cut = off
+				key = temp.substr(0, temp.length() - 1);
+				// rtrim key
+				key = rtrim(key);
+				// get value
+				++it;
+				val = *it;
+
+			}
+			else if(pos < (temp.length() - 1))
+			{
+				//key=value
+				// split and trim key/value
+				key = temp.substr(0, pos);
+				key = rtrim( key );
+				val = temp.substr(pos + 1, temp.size() - pos);
+				val = ltrim( val );
+
+			}
+			std::cout << "KEY:" << key << "# VAL:"  << val << "#" << std::endl;
+			cInfo->setKeyValue(key, val);
+			++it;
 		}
-		else
-		{
-			if (connectString != wxT(""))
-				connectString += wxT(" ");
-			connectString += wxString::FromAscii(*argv);
-			if (**argv == '"')
-				connectString = connectString.substr(1, connectString.length() - 2);
-		}
-		argv++;
 	}
 }
 
-
 void WaitAWhile(const bool waitLong)
 {
 	int count;
@@ -123,12 +147,12 @@ void WaitAWhile(const bool waitLong)
 	}
 }
 
-
-
-wxString NumToStr(const long l)
+void ReplaceString(std::string &subject, const std::string &search, const std::string &replace)
 {
-	wxString buf;
-	buf.Printf(wxT("%ld"), l);
-	return buf;
+	size_t pos = 0;
+	while ((pos = subject.find(search, pos)) != std::string::npos)
+	{
+		subject.replace(pos, search.length(), replace);
+		pos += replace.length();
+	}
 }
-
diff --git a/pgAgent.cpp b/pgAgent.cpp
index 1fe109b..e0652de 100644
--- a/pgAgent.cpp
+++ b/pgAgent.cpp
@@ -11,13 +11,6 @@
 
 #include "pgAgent.h"
 
-#ifndef __WXMSW__
-#include <unistd.h>
-#endif
-
-wxString connectString;
-wxString serviceDBname;
-wxString backendPid;
 long longWait = 30;
 long shortWait = 5;
 long minLogLevel = LOG_ERROR;
@@ -26,101 +19,129 @@ long minLogLevel = LOG_ERROR;
 
 #ifndef __WXMSW__
 bool runInForeground = false;
-wxString logFile = wxEmptyString;
+std::string logFile;
+
+#include <stdio.h>
+#include <stdlib.h>
 #else
 //pgAgent Initialized
 void Initialized();
 #endif
 
+std::set<JobThread *> jtListe;
+
+void ClearJobThreads()
+{
+	std::set<JobThread *>::iterator it_jtListe;
+	std::ostringstream oss;
+	int counter = 0;
+	int counter_erase = 0;
+	for(it_jtListe = jtListe.begin(); it_jtListe != jtListe.end(); ++it_jtListe)
+	{
+		++counter;
+		JobThread *temp = *it_jtListe;
+		if(temp->finished())
+		{
+			delete temp;
+			jtListe.erase(it_jtListe);
+			++counter_erase;
+		}
+	}
+	oss << "ClearJobThreads: ERASE(" << counter_erase << ") / (" << counter << ")" << std::endl;
+	LogMessage(oss.str(), LOG_DEBUG);
+}
+
 int MainRestartLoop(DBconn *serviceConn)
 {
 	// clean up old jobs
 
 	int rc;
+	char c_hostname[1024];
+	c_hostname[1023] = '\0';
 
-	LogMessage(_("Clearing zombies"), LOG_DEBUG);
-	rc = serviceConn->ExecuteVoid(wxT("CREATE TEMP TABLE pga_tmp_zombies(jagpid int4)"));
+	LogMessage(("Clearing zombies"), LOG_DEBUG);
+	rc = serviceConn->ExecuteVoid("CREATE TEMP TABLE pga_tmp_zombies(jagpid int4)");
 
 	if (serviceConn->BackendMinimumVersion(9, 2))
 	{
 		rc = serviceConn->ExecuteVoid(
-		         wxT("INSERT INTO pga_tmp_zombies (jagpid) ")
-		         wxT("SELECT jagpid ")
-		         wxT("  FROM pgagent.pga_jobagent AG ")
-		         wxT("  LEFT JOIN pg_stat_activity PA ON jagpid=pid ")
-		         wxT(" WHERE pid IS NULL")
+		         std::string("INSERT INTO pga_tmp_zombies (jagpid) ") +
+		         ("SELECT jagpid ") +
+		         ("  FROM pgagent.pga_jobagent AG ") +
+		         ("  LEFT JOIN pg_stat_activity PA ON jagpid=pid ") +
+		         (" WHERE pid IS NULL")
 		     );
 	}
 	else
 	{
 		rc = serviceConn->ExecuteVoid(
-		         wxT("INSERT INTO pga_tmp_zombies (jagpid) ")
-		         wxT("SELECT jagpid ")
-		         wxT("  FROM pgagent.pga_jobagent AG ")
-		         wxT("  LEFT JOIN pg_stat_activity PA ON jagpid=procpid ")
-		         wxT(" WHERE procpid IS NULL")
+		         std::string("INSERT INTO pga_tmp_zombies (jagpid) ") +
+		         std::string("SELECT jagpid ") +
+		         std::string("  FROM pgagent.pga_jobagent AG ") +
+		         std::string("  LEFT JOIN pg_stat_activity PA ON jagpid=procpid ") +
+		         std::string(" WHERE procpid IS NULL")
 		     );
 	}
-
 	if (rc > 0)
 	{
 		// There are orphaned agent entries
 		// mark the jobs as aborted
 		rc = serviceConn->ExecuteVoid(
-		         wxT("UPDATE pgagent.pga_joblog SET jlgstatus='d' WHERE jlgid IN (")
-		         wxT("SELECT jlgid ")
-		         wxT("FROM pga_tmp_zombies z, pgagent.pga_job j, pgagent.pga_joblog l ")
-		         wxT("WHERE z.jagpid=j.jobagentid AND j.jobid = l.jlgjobid AND l.jlgstatus='r');\n")
+		         std::string("UPDATE pgagent.pga_joblog SET jlgstatus='d' WHERE jlgid IN (") +
+		         std::string("SELECT jlgid ") +
+		         std::string("FROM pga_tmp_zombies z, pgagent.pga_job j, pgagent.pga_joblog l ") +
+		         std::string("WHERE z.jagpid=j.jobagentid AND j.jobid = l.jlgjobid AND l.jlgstatus='r');\n") +
 
-		         wxT("UPDATE pgagent.pga_jobsteplog SET jslstatus='d' WHERE jslid IN ( ")
-		         wxT("SELECT jslid ")
-		         wxT("FROM pga_tmp_zombies z, pgagent.pga_job j, pgagent.pga_joblog l, pgagent.pga_jobsteplog s ")
-		         wxT("WHERE z.jagpid=j.jobagentid AND j.jobid = l.jlgjobid AND l.jlgid = s.jsljlgid AND s.jslstatus='r');\n")
+		         std::string("UPDATE pgagent.pga_jobsteplog SET jslstatus='d' WHERE jslid IN ( ") +
+		         std::string("SELECT jslid ") +
+		         std::string("FROM pga_tmp_zombies z, pgagent.pga_job j, pgagent.pga_joblog l, pgagent.pga_jobsteplog s ") +
+		         std::string("WHERE z.jagpid=j.jobagentid AND j.jobid = l.jlgjobid AND l.jlgid = s.jsljlgid AND s.jslstatus='r');\n") +
 
-		         wxT("UPDATE pgagent.pga_job SET jobagentid=NULL, jobnextrun=NULL ")
-		         wxT("  WHERE jobagentid IN (SELECT jagpid FROM pga_tmp_zombies);\n")
+		         std::string("UPDATE pgagent.pga_job SET jobagentid=NULL, jobnextrun=NULL ") +
+		         std::string("  WHERE jobagentid IN (SELECT jagpid FROM pga_tmp_zombies);\n") +
 
-		         wxT("DELETE FROM pgagent.pga_jobagent ")
-		         wxT("  WHERE jagpid IN (SELECT jagpid FROM pga_tmp_zombies);\n")
+		         std::string("DELETE FROM pgagent.pga_jobagent ") +
+		         std::string("  WHERE jagpid IN (SELECT jagpid FROM pga_tmp_zombies);\n")
 		     );
 	}
 
-	rc = serviceConn->ExecuteVoid(wxT("DROP TABLE pga_tmp_zombies"));
+	rc = serviceConn->ExecuteVoid(std::string("DROP TABLE pga_tmp_zombies"));
 
-	wxString hostname = wxGetFullHostName();
+	// get Hostname
+	gethostname(c_hostname, 1023);
+	std::string hostname = c_hostname;
 
 	rc = serviceConn->ExecuteVoid(
-	         wxT("INSERT INTO pgagent.pga_jobagent (jagpid, jagstation) SELECT pg_backend_pid(), '") + hostname + wxT("'"));
+	         std::string("INSERT INTO pgagent.pga_jobagent (jagpid, jagstation) SELECT pg_backend_pid(), '") + hostname + std::string("'"));
 	if (rc < 0)
 		return rc;
 
 	while (1)
 	{
-		bool foundJobToExecute = false;
-
-		LogMessage(_("Checking for jobs to run"), LOG_DEBUG);
+		LogMessage(("Checking for jobs to run"), LOG_DEBUG);
 		DBresult *res = serviceConn->Execute(
-		                    wxT("SELECT J.jobid ")
-		                    wxT("  FROM pgagent.pga_job J ")
-		                    wxT(" WHERE jobenabled ")
-		                    wxT("   AND jobagentid IS NULL ")
-		                    wxT("   AND jobnextrun <= now() ")
-		                    wxT("   AND (jobhostagent = '' OR jobhostagent = '") + hostname + wxT("')")
-		                    wxT(" ORDER BY jobnextrun"));
+		                    std::string("SELECT J.jobid ") +
+		                    std::string("  FROM pgagent.pga_job J ") +
+		                    std::string(" WHERE jobenabled ") +
+		                    std::string("   AND jobagentid IS NULL ") +
+		                    std::string("   AND jobnextrun <= now() ") +
+		                    std::string("   AND (jobhostagent = '' OR jobhostagent = '") + hostname + std::string("')") +
+		                    std::string(" ORDER BY jobnextrun"));
 
 		if (res)
 		{
 			while(res->HasData())
 			{
-				wxString jobid = res->GetString(wxT("jobid"));
+				std::string jobid = res->GetString(std::string("jobid"));
 
-				JobThread *jt = new JobThread(jobid);
+				JobThread *jt = new JobThread(jobid, serviceConn->getConnInfo());
 
-				if (jt->Runnable())
+				if (jt != NULL)
 				{
-					jt->Create();
-					jt->Run();
-					foundJobToExecute = true;
+					// start the Threading Job
+					jt->start();
+					// remember the Thread Job
+					jtListe.insert(jt);
 				}
 				else
 				{
@@ -128,8 +149,8 @@ int MainRestartLoop(DBconn *serviceConn)
 					// "internal error" status in the joblog table, to leave
 					// a trace of fact that we tried to launch the job.
 					DBresult *res = serviceConn->Execute(
-						wxT("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ")
-						wxT("VALUES (nextval('pgagent.pga_joblog_jlgid_seq'), ") + jobid + wxT(", 'i')"));
+					                    std::string("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ") +
+					                    std::string("VALUES (nextval('pgagent.pga_joblog_jlgid_seq'), ") + jobid + std::string(", 'i')"));
 					if (res)
 						delete res;
 
@@ -142,45 +163,46 @@ int MainRestartLoop(DBconn *serviceConn)
 			}
 
 			delete res;
-			LogMessage(_("Sleeping..."), LOG_DEBUG);
+			LogMessage(("Sleeping..."), LOG_DEBUG);
 			WaitAWhile();
 		}
 		else
 		{
-			LogMessage(_("Failed to query jobs table!"), LOG_ERROR);
+			LogMessage(("Failed to query jobs table!"), LOG_ERROR);
 		}
-		if (!foundJobToExecute)
-			DBconn::ClearConnections();
+		// clear JobThreads when idle or every loop
+		ClearJobThreads();
+		serviceConn->ClearConnections(true);
 	}
 	return 0;
 }
 
 
-void MainLoop()
+void MainLoop(connInfo *serviceConnInfo)
 {
 	int attemptCount = 1;
-
+	DBconn *serviceConn = NULL;
 	// OK, let's get down to business
 	do
 	{
-		LogMessage(_("Creating primary connection"), LOG_DEBUG);
-		DBconn *serviceConn = DBconn::InitConnection(connectString);
+		LogMessage(("Creating primary connection"), LOG_DEBUG);
+		LogMessage( std::string("MainLoop(connInfo* serviceConnInfo): ") + serviceConnInfo->getConnectionString(), LOG_DEBUG);
+		serviceConn = new DBconn(serviceConnInfo);
+		LogMessage(("Database Conn Info: ") + serviceConnInfo->getConnectionString(), LOG_DEBUG);
 
 		if (serviceConn && serviceConn->IsValid())
 		{
-			serviceDBname = serviceConn->GetDBname();
-
 			// Basic sanity check, and a chance to get the serviceConn's PID
-			LogMessage(_("Database sanity check"), LOG_DEBUG);
-			DBresult *res = serviceConn->Execute(wxT("SELECT count(*) As count, pg_backend_pid() AS pid FROM pg_class cl JOIN pg_namespace ns ON ns.oid=relnamespace WHERE relname='pga_job' AND nspname='pgagent'"));
+			LogMessage(("Database sanity check DB:") + serviceConnInfo->dbname, LOG_DEBUG);
+			DBresult *res = serviceConn->Execute(std::string("SELECT count(*) As count, pg_backend_pid() AS pid FROM pg_class cl JOIN pg_namespace ns ON ns.oid=relnamespace WHERE relname='pga_job' AND nspname='pgagent'"));
 			if (res)
 			{
-				wxString val = res->GetString(wxT("count"));
+				std::string val = res->GetString(std::string("count"));
 
-				if (val == wxT("0"))
-					LogMessage(_("Could not find the table 'pgagent.pga_job'. Have you run pgagent.sql on this database?"), LOG_ERROR);
+				if (val == std::string("0"))
+					LogMessage(("Could not find the table 'pgagent.pga_job'. Have you run pgagent.sql on this database?"), LOG_ERROR);
 
-				backendPid = res->GetString(wxT("pid"));
+				serviceConnInfo->backendPid = res->GetString(std::string("pid"));
 
 				delete res;
 				res = NULL;
@@ -189,23 +211,23 @@ void MainLoop()
 			// Check for particular version
 
 			bool hasSchemaVerFunc = false;
-			wxString sqlCheckSchemaVersion
-			= wxT("SELECT COUNT(*)                                            ")\
-			  wxT("FROM pg_proc                                               ")\
-			  wxT("WHERE proname = 'pgagent_schema_version' AND               ")\
-			  wxT("      pronamespace = (SELECT oid                           ")\
-			  wxT("                      FROM pg_namespace                    ")\
-			  wxT("                      WHERE nspname = 'pgagent') AND       ")\
-			  wxT("      prorettype = (SELECT oid                             ")\
-			  wxT("                    FROM pg_type                           ")\
-			  wxT("                    WHERE typname = 'int2') AND            ")\
-			  wxT("      proargtypes = ''                                     ");
+			std::string sqlCheckSchemaVersion
+			    = std::string("SELECT COUNT(*)                                            ") +
+			      std::string("FROM pg_proc                                               ") +
+			      std::string("WHERE proname = 'pgagent_schema_version' AND               ") +
+			      std::string("      pronamespace = (SELECT oid                           ") +
+			      std::string("                      FROM pg_namespace                    ") +
+			      std::string("                      WHERE nspname = 'pgagent') AND       ") +
+			      std::string("      prorettype = (SELECT oid                             ") +
+			      std::string("                    FROM pg_type                           ") +
+			      std::string("                    WHERE typname = 'int2') AND            ") +
+			      std::string("      proargtypes = ''                                     ");
 
 			res = serviceConn->Execute(sqlCheckSchemaVersion);
 
 			if (res)
 			{
-				if (res->IsValid() && res->GetString(0) == wxT("1"))
+				if (res->IsValid() && res->GetString(0) == std::string("1"))
 					hasSchemaVerFunc = true;
 				delete res;
 				res = NULL;
@@ -213,17 +235,17 @@ void MainLoop()
 
 			if (!hasSchemaVerFunc)
 			{
-				LogMessage(_("Couldn't find the function 'pgagent_schema_version' - please run pgagent_upgrade.sql."), LOG_ERROR);
+				LogMessage(("Couldn't find the function 'pgagent_schema_version' - please run pgagent_upgrade.sql."), LOG_ERROR);
 			}
 
-			wxString strPgAgentSchemaVer = serviceConn->ExecuteScalar(wxT("SELECT pgagent.pgagent_schema_version()"));
-			wxString currentPgAgentVersion;
-			currentPgAgentVersion.Printf(_("%d"), PGAGENT_VERSION_MAJOR);
-			if (strPgAgentSchemaVer != currentPgAgentVersion)
+			std::string strPgAgentSchemaVer = serviceConn->ExecuteScalar(std::string("SELECT pgagent.pgagent_schema_version()"));
+			std::stringstream currentPgAgentVersion;
+			currentPgAgentVersion <<  PGAGENT_VERSION_MAJOR;
+			if (strPgAgentSchemaVer != currentPgAgentVersion.str())
 			{
-				wxString strSchemaVerMisMatch;
-				strSchemaVerMisMatch.Printf(_("Unsupported schema version: %s. Version %s is required - please run pgagent_upgrade.sql."), strPgAgentSchemaVer.c_str(), currentPgAgentVersion.c_str());
-				LogMessage(strSchemaVerMisMatch, LOG_ERROR);
+				std::stringstream strSchemaVerMisMatch;
+				strSchemaVerMisMatch << "Unsupported schema version: " << strPgAgentSchemaVer << ". Version " << currentPgAgentVersion.str() << " is required - please run pgagent_upgrade.sql." << std::endl;
+				LogMessage(strSchemaVerMisMatch.str(), LOG_ERROR);
 			}
 
 #ifdef WIN32
@@ -231,14 +253,16 @@ void MainLoop()
 #endif
 			MainRestartLoop(serviceConn);
 		}
-
-		LogMessage(wxString::Format(_("Couldn't create the primary connection (attempt %d): %s"), attemptCount, serviceConn->GetLastError().c_str()), LOG_STARTUP);
-		DBconn::ClearConnections(true);
-
+		else
+		{
+			std::stringstream log;
+			log << "Couldn't create the primary connection (attempt " << attemptCount << "):" << serviceConn->GetLastError() << "" << std::endl;
+			LogMessage(log.str(), LOG_STARTUP);
+		}
 		// Try establishing primary connection upto MAXATTEMPTS times
 		if (attemptCount++ >= (int)MAXATTEMPTS)
 		{
-			LogMessage(wxString::Format(_("Stopping pgAgent: Couldn't establish the primary connection with the database server.")), LOG_ERROR);
+			LogMessage(std::string("Stopping pgAgent: Couldn't establish the primary connection with the database server."), LOG_ERROR);
 		}
 		WaitAWhile();
 	}
diff --git a/unix.cpp b/unix.cpp
index 84a95dc..b23b5fd 100644
--- a/unix.cpp
+++ b/unix.cpp
@@ -14,69 +14,113 @@
 // *nix only!!
 #ifndef WIN32
 
-#include <wx/filename.h>
-#include <wx/ffile.h>
+#include <boost/program_options/parsers.hpp>
+#include <boost/program_options/variables_map.hpp>
+
 #include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <time.h>
+#include <sys/stat.h>
+
+std::string CreateTempFileName(std::string prefix)
+{
+	std::ostringstream oss;
+	FILE *pFile;
+
+	char *pointer = tmpnam (NULL);
+	std::string temp(pointer);
+	std::size_t pos = temp.find_last_of('/');
+
+	oss << temp.substr(0, pos + 1) << prefix << temp.substr(pos + 1, temp.size() - pos - 1);
+
+	LogMessage("TEMP: " + temp + " - " + oss.str(), LOG_DEBUG);
+	temp = oss.str();
+	pFile = fopen (temp.c_str(), "w");
+
+	if (pFile != NULL) fclose(pFile);
+	else return std::string("");
+	return temp;
+}
+
+int Mkdir(std::string dirname, mode_t rights)
+{
+	return mkdir(dirname.c_str(), rights);
+}
+
+int RemoveFile(std::string filename)
+{
+	return remove(filename.c_str());
+}
+
+int Rmdir(std::string dirname)
+{
+	return rmdir(dirname.c_str());
+}
+
+int Chmod(std::string dirname, mode_t rights)
+{
+	return chmod(dirname.c_str(), rights);
+}
 
-void usage(const wxString &executable)
+boost::shared_ptr< po::options_description> usage(int argc, char **argv)
 {
-	wxFileName *fn = new wxFileName(executable);
-
-	wxPrintf(_("Usage:\n"));
-	wxPrintf(fn->GetName() + _(" [options] <connect-string>\n"));
-	wxPrintf(_("options:\n"));
-	wxPrintf(_("-f run in the foreground (do not detach from the terminal)\n"));
-	wxPrintf(_("-t <poll time interval in seconds (default 10)>\n"));
-	wxPrintf(_("-r <retry period after connection abort in seconds (>=10, default 30)>\n"));
-	wxPrintf(_("-s <log file (messages are logged to STDOUT if not specified>\n"));
-	wxPrintf(_("-l <logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>\n"));
+	boost::shared_ptr< po::options_description> desc;
+	return desc;
 }
 
-void LogMessage(wxString msg, int level)
+void LogMessage(std::string msg, int level)
 {
-	wxFFile file;
-	if (logFile.IsEmpty())
+	std::streambuf *buf;
+	std::ofstream of;
+
+	time_t rawtime;
+	struct tm *timeinfo;
+	char buffer [80];
+
+	time (&rawtime);
+	timeinfo = localtime (&rawtime);
+
+	strftime (buffer, 80, "%F %H:%M:%S", timeinfo);
+
+	if(!logFile.empty())
 	{
-		file.Attach(stdout);
+		of.open(logFile.c_str(), std::ios::out | std::ios::app);
+		if(of.is_open())
+		{
+			buf = of.rdbuf();
+		}
+		else
+		{
+			std::cerr << "Can not open the logfile " << logFile << "! Log output goes to STDOUT" << std::flush << std::endl;
+			buf = std::cout.rdbuf();
+		}
 	}
 	else
 	{
-		file.Open(logFile.c_str(), wxT("a"));
+		buf = std::cout.rdbuf();
 	}
 
-	if (!file.IsOpened())
-	{
-		wxFprintf(stderr, _("Can not open the logfile!"));
-		return;
-	}
+	std::ostream log(buf);
 
 	switch (level)
 	{
 		case LOG_DEBUG:
 			if (minLogLevel >= LOG_DEBUG)
-				file.Write(_("DEBUG: ") + msg + wxT("\n"));
+				log << " DEBUG " << msg  << std::flush << std::endl;
 			break;
 		case LOG_WARNING:
 			if (minLogLevel >= LOG_WARNING)
-				file.Write(_("WARNING: ") + msg + wxT("\n"));
+				log << " WARNING " << msg  << std::flush << std::endl;
 			break;
 		case LOG_ERROR:
-			file.Write(_("ERROR: ") + msg + wxT("\n"));
+			log << " ERROR " << msg  << std::flush << std::endl;
 			exit(1);
 			break;
 		case LOG_STARTUP:
-			file.Write(_("WARNING: ") + msg + wxT("\n"));
+			log << " WARNING " << msg  << std::flush << std::endl;
 			break;
 	}
-
-	if (logFile.IsEmpty())
-	{
-		file.Detach();
-	}
-	else
-	{
-		file.Close();
-	}
 }
 
 // Shamelessly lifted from pg_autovacuum...
@@ -87,7 +131,7 @@ static void daemonize(void)
 	pid = fork();
 	if (pid == (pid_t) - 1)
 	{
-		LogMessage(_("Cannot disassociate from controlling TTY"), LOG_ERROR);
+		LogMessage(("Cannot disassociate from controlling TTY"), LOG_ERROR);
 		exit(1);
 	}
 	else if (pid)
@@ -96,37 +140,79 @@ static void daemonize(void)
 #ifdef HAVE_SETSID
 	if (setsid() < 0)
 	{
-		LogMessage(_("Cannot disassociate from controlling TTY"), LOG_ERROR);
+		LogMessage(("Cannot disassociate from controlling TTY"), LOG_ERROR);
 		exit(1);
 	}
 #endif
 
 }
 
-int main(int argc, char **argv)
+int main(int argc, char *argv[])
 {
-	// Statup wx
-	wxInitialize();
-
-	wxString executable;
-	executable = wxString::FromAscii(argv[0]);
+	try
+	{
 
-	if (argc < 2)
+		std::string executable;
+		size_t pos = executable.find_last_of('/');
+		std::string temp = std::string(argv[0]);
+		if(pos != std::string::npos) executable = temp.substr(pos, temp.size() - pos - 1);
+
+		// commandline pramaeter
+		std::ostringstream oss;
+		oss << "Usage:" << std::endl;
+		oss << executable << " [options] <connect-string>" << std::endl;
+		oss << std::endl << "options"; //<< std::endl;
+		boost::shared_ptr< po::options_description>  desc( new po::options_description(oss.str()) );
+
+		desc->add_options()
+		("help,h", "produce this help message")
+		("foreground,f", "run in the foreground (do not detach from the terminal)")
+		("time_poll,t", po::value<int>(), "<poll time interval in seconds (default 10)>")
+		("retry_period,r", po::value<int>(), "<retry period after connection abort in seconds (>=10, default 30)>")
+		("logfile,s", po::value<std::string>(), "<log file (messages are logged to STDOUT if not specified>")
+		("log_verbosity,l", po::value< int >(), "<logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>")
+		("connect_string", po::value< std::vector<std::string > >(), "<connect string like dbname=myDB host=myHost user=me password=secret port=5432>");
+
+		po::positional_options_description p;
+		p.add("connect_string", -1);
+
+		po::variables_map vm;
+		try
+		{
+			po::parsed_options parsed = po::command_line_parser(argc, argv).options(*desc).positional(p).run();
+			po::store(parsed, vm);
+			po::notify(vm);
+		}
+		catch(po::error &e)
+		{
+			std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
+			std::cerr << desc << std::endl;
+			return 2;
+		}
+
+		if (argc < 2)
+		{
+			std::cout << (*desc) << std::endl;
+			return 1;
+		}
+
+		connInfo *serviceConnInfo = new connInfo();
+		setOptions(vm, desc, serviceConnInfo);
+
+		if (!runInForeground) daemonize();
+
+		LogMessage( std::string("MainLOOP"), LOG_DEBUG);
+		MainLoop(serviceConnInfo);
+
+		delete serviceConnInfo;
+	}
+	catch(std::exception &e)
 	{
-		usage(executable);
+		std::cerr << "Unhandled Exception reached the top of main: "
+		          << e.what() << ", application will now exit" << std::endl;
 		return 1;
 	}
 
-	argc--;
-	argv++;
-
-	setOptions(argc, argv, executable);
-
-	if (!runInForeground)
-		daemonize();
-
-	MainLoop();
-
 	return 0;
 }
 
diff --git a/win32.cpp b/win32.cpp
index 254f818..c611427 100644
--- a/win32.cpp
+++ b/win32.cpp
@@ -14,8 +14,6 @@
 // This is for Win32 only!!
 #ifdef WIN32
 
-#include <wx/filename.h>
-#include <wx/config.h>
 #include <process.h>
 
 // for debugging purposes, we can start the service paused
@@ -25,8 +23,8 @@
 
 static SERVICE_STATUS serviceStatus;
 static SERVICE_STATUS_HANDLE serviceStatusHandle;
-static wxString serviceName;
-static wxString user = wxT(".\\Administrator"), password;
+static std::string serviceName;
+static std::string user = (".\\Administrator"), password;
 static HANDLE threadHandle = 0;
 
 
@@ -57,14 +55,14 @@ void CheckForInterrupt()
 	serviceIsRunning = true;
 }
 
-void LogMessage(wxString msg, int level)
+void LogMessage(std::string msg, int level)
 {
 	if (eventHandle)
 	{
 		LPCTSTR *tmp;
 
 		tmp = (LPCTSTR *)malloc(sizeof(LPCTSTR));
-		tmp[0] = _wcsdup(msg.wc_str());
+		tmp[0] = _wcsdup(msg.c_str());
 
 		switch (level)
 		{
@@ -105,20 +103,20 @@ void LogMessage(wxString msg, int level)
 		{
 			case LOG_DEBUG:
 				if (minLogLevel >= LOG_DEBUG)
-					wxPrintf(_("DEBUG: %s\n"), msg);
+					std::cout << std::string("DEBUG: ") + msg + "\n" << std::endl;
 				break;
 			case LOG_WARNING:
 				if (minLogLevel >= LOG_WARNING)
-					wxPrintf(_("WARNING: %s\n"), msg);
+					std::cout << std::string("WARNING: ") + msg + "\n" << std::endl;
 				break;
 			case LOG_ERROR:
-				wxPrintf(_("ERROR: %s\n"), msg);
+				std::cout << std::string("ERROR: ") + msg + "\n" << std::endl;
 				pgagentInitialized = true;
 				exit(1);
 				break;
 				// Log startup/connection warnings (valid for any log level)
 			case LOG_STARTUP:
-				wxPrintf(_("WARNING: %s\n"), msg);
+				std::cout << std::string("WARNING: ") + msg + "\n" << std::endl;
 				break;
 		}
 	}
@@ -128,7 +126,8 @@ void LogMessage(wxString msg, int level)
 
 unsigned int __stdcall threadProcedure(void *unused)
 {
-	MainLoop();
+	connInfo *serviceConnInfo = new connInfo();
+	MainLoop(serviceConnInfo);
 	return 0;
 }
 
@@ -139,7 +138,7 @@ unsigned int __stdcall threadProcedure(void *unused)
 // _popen doesn't work in Win2K from a service so we have to
 // do it the fun way :-)
 
-HANDLE win32_popen_r(const TCHAR *command, HANDLE &handle)
+HANDLE win32_popen_r(const TCHAR *command)
 {
 	HANDLE hWrite, hRead;
 	SECURITY_ATTRIBUTES saAttr;
@@ -185,13 +184,16 @@ HANDLE win32_popen_r(const TCHAR *command, HANDLE &handle)
 	if (!ret)
 		return NULL;
 	else
+	{
+		CloseHandle(piProcInfo.hProcess);
 		CloseHandle(piProcInfo.hThread);
+	}
+
 
 	// Close the write end of the pipe and return the read end.
 	if (!CloseHandle(hWrite))
 		return NULL;
 
-	handle = piProcInfo.hProcess;
 	return hRead;
 }
 
@@ -322,7 +324,7 @@ void CALLBACK serviceMain(DWORD argc, LPTSTR *argv)
 
 ////////////////////////////////////////////////////////////
 // installation and removal
-bool installService(const wxString &serviceName, const wxString &executable,  const wxString &args, const wxString &displayname, const wxString &user, const wxString &password)
+bool installService(const std::string &serviceName, const std::string &executable,  const std::string &args, const std::string &displayname, const std::string &user, const std::string &password)
 {
 	DWORD dwData;
 	bool done = false;
@@ -330,11 +332,11 @@ bool installService(const wxString &serviceName, const wxString &executable,  co
 	SC_HANDLE manager = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
 	if (manager)
 	{
-		wxString cmd = executable + wxT(" ") + args;
+		std::string cmd = executable + wxT(" ") + args;
 
-		wxString quser;
-		if (!user.Contains(wxT("\\")))
-			quser = wxT(".\\") + user;
+		std::string quser;
+		if (!user.find_first_of("\\"))
+			quser = std::string(".\\") + user;
 		else
 			quser = user;
 
@@ -361,7 +363,7 @@ bool installService(const wxString &serviceName, const wxString &executable,  co
 			    (LPTSTR) &lpMsgBuf,
 			    0, NULL
 			);
-			wxString error;
+			std::string error;
 			error.Printf(wxT("%s"), lpMsgBuf);
 			LogMessage(error, LOG_ERROR);
 		}
@@ -374,24 +376,24 @@ bool installService(const wxString &serviceName, const wxString &executable,  co
 	if(!msgKey->Exists())
 	{
 		if (!msgKey->Create())
-			LogMessage(_("Could not open the message source registry key."), LOG_WARNING);
+			LogMessage(("Could not open the message source registry key."), LOG_WARNING);
 	}
 
-	wxString path = executable.BeforeLast('\\') + wxT("\\pgaevent.dll");
+	std::string path = executable.BeforeLast('\\') + std::string("\\pgaevent.dll");
 
-	if (!msgKey->SetValue(wxT("EventMessageFile"), path))
-		LogMessage(_("Could not set the event message file registry value."), LOG_WARNING);
+	if (!msgKey->SetValue(std::string("EventMessageFile"), path))
+		LogMessage(("Could not set the event message file registry value."), LOG_WARNING);
 
 	dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
 
-	if (!msgKey->SetValue(wxT("TypesSupported"), dwData))
-		LogMessage(_("Could not set the supported types."), LOG_WARNING);;
+	if (!msgKey->SetValue(std::string("TypesSupported"), dwData))
+		LogMessage(("Could not set the supported types."), LOG_WARNING);;
 
 	return done;
 }
 
 
-bool removeService(const wxString &serviceName)
+bool removeService(const std::string &serviceName)
 {
 	bool done = false;
 
@@ -430,30 +432,30 @@ bool removeService(const wxString &serviceName)
 	return done;
 }
 
-
-
-void usage(const wxString &executable)
+void usage(const std::string &executable)
 {
-	wxFileName *fn = new wxFileName(executable);
-
-	wxPrintf(_("Usage:\n"));
-	wxPrintf(fn->GetName() + _(" REMOVE <serviceName>\n"));
-	wxPrintf(fn->GetName() + _(" INSTALL <serviceName> [options] <connect-string>\n"));
-	wxPrintf(fn->GetName() + _(" DEBUG [options] <connect-string>\n"));
-	wxPrintf(_("options:\n"));
-	wxPrintf(_("-u <user or DOMAIN\\user>\n"));
-	wxPrintf(_("-p <password>\n"));
-	wxPrintf(_("-d <displayname>\n"));
-	wxPrintf(_("-t <poll time interval in seconds (default 10)>\n"));
-	wxPrintf(_("-r <retry period after connection abort in seconds (>=10, default 30)>\n"));
-	wxPrintf(_("-l <logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>\n"));
+	//wxFileName *fn = new wxFileName(executable);
+	size_t pos = executable.find_last_of('\\');
+	std::string fn = executable.substr(pos, executable.size() - pos);
+
+	std::cout << "Usage:\n" << std::endl;
+	std::cout << fn << (" REMOVE <serviceName>\n" << std::endl;
+	                    std::cout << fn << (" INSTALL <serviceName> [options] <connect-string>\n" << std::endl;
+	                                        std::cout << fn << (" DEBUG [options] <connect-string>\n" << std::endl;
+	                                                std::cout << "options:\n" << std::endl;
+	                                                std::cout << "-u <user or DOMAIN\\user>\n" << std::endl;
+	                                                std::cout << "-p <password>\n" << std::endl;
+	                                                std::cout << "-d <displayname>\n" << std::endl;
+	                                                std::cout << "-t <poll time interval in seconds (default 10)>\n" << std::endl;
+	                                                std::cout << "-r <retry period after connection abort in seconds (>=10, default 30)>\n" << std::endl;
+	                                                std::cout << "-l <logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>\n" << std::endl;
 }
 
 
 
 ////////////////////////////////////////////////////////////
 
-void setupForRun(int argc, char **argv, bool debug, const wxString &executable)
+                                                void setupForRun(int argc, char **argv, bool debug, const std::string &executable)
 {
 	if (!debug)
 	{
@@ -471,31 +473,47 @@ void main(int argc, char **argv)
 	// Statup wx
 	wxInitialize();
 
-	wxFileName file = wxString::FromAscii(*argv++);
-	file.MakeAbsolute();
-	wxString executable = file.GetFullPath();
+	// commandline pramaeter
+	std::ostringstream oss;
+	oss << "Usage:" << std::endl;
+	oss << std::string(argv[0]) << " REMOVE <serviceName>" << std::endl;
+	oss << std::string(argv[0]) << " INSTALL <serviceName> [options] <connect-string>" << std::endl;
+	oss << std::string(argv[0]) << " DEBUG [options] <connect-string>" << std::endl;
+	oss << std::endl << "options:" << std::endl;
+	boost::shared_ptr< po::options_description>  win32_service_opt( new po::options_description(oss.str()) );
+
+	win32_service_opt->add_options()
+	("help", "produce help message")
+	("User,u", "<user or DOMAIN\\user>")
+	("password,p", "<password>")
+	("displayname,d", "<displayname>")
+	("time_poll,t", "<poll time interval in seconds (default 10)>")
+	("retry_period,r", "<retry period after connection abort in seconds (>=10, default 30)>")
+	("log_verbosity,l", "<logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>")
+	;
+
 
 	if (argc < 3)
 	{
-		usage(executable);
+		std::cout << win32_service_opt << std::endl;
 		return;
 	}
 
-	wxString command;
-	command = wxString::FromAscii(*argv++);
+	std::string command;
+	command = std::string(*argv++);
 
-	if (command != wxT("DEBUG"))
+	if (command != std::string("DEBUG"))
 	{
-		serviceName = wxString::FromAscii(*argv++);
+		serviceName = std::string(*argv++);
 		argc -= 3;
 	}
 	else
 		argc -= 2;
 
-	if (command == wxT("INSTALL"))
+	if (command == std::string("INSTALL"))
 	{
-		wxString displayname = _("PostgreSQL Scheduling Agent - ") + serviceName;
-		wxString args = wxT("RUN ") + serviceName;
+		std::string displayname = ("PostgreSQL Scheduling Agent - ") + serviceName;
+		std::string args = std::string("RUN ") + serviceName;
 
 		while (argc-- > 0)
 		{
@@ -520,14 +538,14 @@ void main(int argc, char **argv)
 					}
 					default:
 					{
-						args += wxT(" ") + wxString::FromAscii(*argv);
+						args += wxT(" ") + std::string(*argv);
 						break;
 					}
 				}
 			}
 			else
 			{
-				args += wxT(" ") + wxString::FromAscii(*argv);
+				args += wxT(" ") + std::string(*argv);
 			}
 
 			argv++;
@@ -535,11 +553,11 @@ void main(int argc, char **argv)
 
 		bool rc = installService(serviceName, executable, args, displayname, user, password);
 	}
-	else if (command == wxT("REMOVE"))
+	else if (command == std::string("REMOVE"))
 	{
 		bool rc = removeService(serviceName);
 	}
-	else if (command == wxT("DEBUG"))
+	else if (command == std::string("DEBUG"))
 	{
 		setupForRun(argc, argv, true, executable);
 
@@ -550,12 +568,12 @@ void main(int argc, char **argv)
 
 		WaitForSingleObject(threadHandle, INFINITE);
 	}
-	else if (command == wxT("RUN"))
+	else if (command == std::string("RUN"))
 	{
-		wxString app = _("pgAgent Service");
+		std::string app = std::string("pgAgent Service");
 
 		SERVICE_TABLE_ENTRY serviceTable[] =
-		{ (LPWSTR)app.wc_str(), serviceMain, 0, 0};
+		{ (LPWSTR)app.c_str(), serviceMain, 0, 0};
 
 		setupForRun(argc, argv, false, executable);
 
