diff --git a/connection.cpp b/connection.cpp
index 6103c00..0bc9a4c 100644
--- a/connection.cpp
+++ b/connection.cpp
@@ -11,45 +11,35 @@
 
 #include "pgAgent.h"
 
-#include <wx/regex.h>
-#include <wx/tokenzr.h>
-
-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;
-
-	if (connectString.IsEmpty())
-	{
-		// This is a sql call to a local database.
-		// No connection string found. Use basicConnectString.
-		Connect(basicConnectString  + wxT(" dbname=") + dbname);
-	}
-	else
-	{
-		Connect(connectString);
-	}
+    inUse = false;
+    next = 0;
+    prev = 0;
+    majorVersion = 0;
+    minorVersion = 0;
+    dbname = cInfo->dbname;
+    connStr = cInfo->getConnectionString();
+    cnInfo = cInfo;
+
+    LogMessage( std::string("DBconn(connInfo *cInfo): ") + connStr, LOG_DEBUG);
+    if (!connStr.empty())
+    {
+        Connect(connStr);
+    } else {
+        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);
+    //wxCharBuffer cstrUTF = connectString.mb_str(wxConvUTF8);
+    conn = PQconnectdb(connectString.c_str());
+
 	if (PQstatus(conn) != CONNECTION_OK)
 	{
-		lastError = wxString::FromAscii(PQerrorMessage(conn));
+        lastError = std::string(PQerrorMessage(conn));
 		PQfinish(conn);
 		conn = 0;
 	}
@@ -67,208 +57,53 @@ DBconn::~DBconn()
 	}
 }
 
-
-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)
-{
-	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;
-}
-
-
-DBconn *DBconn::Get(const wxString &connStr, const wxString &db)
-{
-	if (db.IsEmpty() && connStr.IsEmpty())
-	{
-		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);
-
-	if (newConn->conn)
-	{
-		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;
-	}
-
-	return newConn;
-}
-
-
 void DBconn::Return()
 {
-	wxMutexLocker lock(s_PoolLock);
-
-	// Cleanup
-	this->ExecuteVoid(wxT("RESET ALL"));
-	this->lastError.Empty();
+    // Cleanup
+    this->ExecuteVoid(std::string("RESET ALL"));
+    this->lastError.clear();
 
-	LogMessage(wxString::Format(_("Returning connection to database %s"), dbname.c_str()), LOG_DEBUG);
+    LogMessage(std::string("Returning connection to database ") + dbname, LOG_DEBUG);
 	inUse = false;
 }
 
-
-void DBconn::ClearConnections(bool all)
+connInfo* DBconn::getConnInfo()
 {
-	wxMutexLocker lock(s_PoolLock);
-
-	if (all)
-		LogMessage(_("Clearing all connections"), LOG_DEBUG);
-	else
-		LogMessage(_("Clearing inactive connections"), LOG_DEBUG);
-
-	DBconn *thisConn = primaryConn, *deleteConn;
-	int total = 0, free = 0, deleted = 0;
-
-	if (thisConn)
-	{
-
-		total++;
-
-		// Find the last connection
-		while (thisConn->next != 0)
-		{
-			total++;
-
-			if (!thisConn->inUse)
-				free++;
-
-			thisConn = thisConn->next;
-		}
-		if (!thisConn->inUse)
-			free++;
-
-		// 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)
-		{
-			if ((!thisConn->inUse) || all)
-			{
-				deleteConn = thisConn;
-				thisConn = deleteConn->prev;
-				thisConn->next = deleteConn->next;
-				if (deleteConn->next)
-					deleteConn->next->prev = deleteConn->prev;
-				delete deleteConn;
-				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);
-
-	}
-	else
-		LogMessage(_("No connections found!"), LOG_DEBUG);
-
+    return this->cnInfo;
 }
 
-
-DBresult *DBconn::Execute(const wxString &query)
+DBresult *DBconn::Execute(const std::string &query)
 {
 	DBresult *res = new DBresult(this, query);
 	if (!res->IsValid())
@@ -282,23 +117,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 +146,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 +214,46 @@ 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;
-		if (count == 0 || count == 3)
-			if (val > 0 && val < 255)
-				count++;
-			else
-				break;
-		else if (val >= 0 && val < 255)
-			count++;
-		else
-			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 < 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,122 +265,159 @@ 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 (IsValidIP())
-			connStr += wxT(" hostaddr=") + host;
-		else
-			connStr += wxT(" host=") + host;
-
+    if (!host.empty()) {
+        if (IsValidIP())   {
+            connStr << " hostaddr=" << host;
+            //LogMessage(std::string("     ValidIP      : "), LOG_DEBUG);
+        } else {
+            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);
+    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();
+}
 
-	return connStr;
+bool connInfo::setConnectionString(std::string str_conn)
+{
+    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) {
+
+        // 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] == '"') {
+            pos = str_conn.find_first_of('"',1);
+            anf = 1;
+            valtrim = false;
+        } else if(str_conn[0] == '\'') {
+            pos = str_conn.find_first_of("'",1);
+            anf = 1;
+            valtrim = false;
+        } else {
+            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);
+
+    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(wxString connStr)
+connInfo connInfo::getConnectionInfo()
 {
 	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())
-	{
-		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)
-		{
-			if (!value.ToULong(&cnInfo.port))
-				// port must be an unsigned integer
-				return cnInfo;
-		}
-		else if (prop.CmpNoCase(wxT("password")) == 0)
-			cnInfo.password = value;
-		else if (prop.CmpNoCase(wxT("connection_timeout")) == 0)
-		{
-			if (!value.ToULong(&cnInfo.connection_timeout))
-				// connection timeout must be an unsigned interger
-				return cnInfo;
-		}
-		else if (prop.CmpNoCase(wxT("dbname")) == 0)
-			cnInfo.dbname = value;
-		else
-			// Not valid property found
-			return 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())
-		cnInfo.isValid = false;
+    if (cnInfo.user.empty() && cnInfo.dbname.empty() && cnInfo.host.empty())
+        cnInfo.isValid = false;
 	else
-		cnInfo.isValid = true;
+        cnInfo.isValid = true;
 
 	return cnInfo;
 }
 
+
diff --git a/include/connection.h b/include/connection.h
index f56a279..0303a86 100644
--- a/include/connection.h
+++ b/include/connection.h
@@ -9,116 +9,85 @@
 //
 //////////////////////////////////////////////////////////////////////////
 
-
 #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);
+    static DBconn *Get(const std::string &connStr, const std::string &db);
+    static DBconn *InitConnection(const std::string &connectString);
 
 	static void ClearConnections(bool allIncludingPrimary = false);
-	static void SetBasicConnectString(const wxString &bcs)
+    static void SetBasicConnectString(const std::string &bcs)
 	{
 		basicConnectString = bcs;
 	}
-	static const wxString &GetBasicConnectString()
+    static 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 std::string basicConnectString;
 	static DBconn *primaryConn;
 
-	wxString dbname, lastError, connStr;
+    connInfo* cnInfo;
+
+    std::string dbname, lastError, connStr;
 	PGconn *conn;
 	DBconn *next, *prev;
 	bool inUse;
-	int lastResult;
+
 	friend class DBresult;
 
 };
 
-
 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
 	{
@@ -126,16 +95,27 @@ public:
 	}
 	bool HasData() const
 	{
-		return currentRow < maxRows;
+        //std::ostringstream oss;
+        //oss << "HasData: " << " currentRow: " << currentRow << " maxRow: " << maxRows;
+        //LogMessage(oss.str(), LOG_DEBUG);
+        return currentRow < maxRows;
 	}
+
 	void MoveNext()
 	{
-		if (currentRow < maxRows) currentRow++;
+        //std::ostringstream oss;
+        //oss << "MoveNext: " << " currentRow: " << currentRow << " maxRow: " << maxRows;
+        //LogMessage(oss.str(), LOG_DEBUG);
+        if (currentRow < maxRows) currentRow++;
 	}
 
 	long RowsAffected() const
 	{
-		return atol(PQcmdTuples(result));
+        long n;
+        std::istringstream in(PQcmdTuples(result));
+        in >> n;
+        //return atol(PQcmdTuples(result));
+        return n;
 	}
 
 protected:
@@ -152,21 +132,45 @@ 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";
+
+
+    }
+//private:
+    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..4a64233 100644
--- a/include/job.h
+++ b/include/job.h
@@ -13,44 +13,60 @@
 #ifndef JOB_H
 #define JOB_H
 
-#include <wx/wx.h>
-
+//#include <wx/wx.h>
+#include <atomic>
+#include <thread>
 
 class Job
 {
 public:
-	Job(DBconn *conn, const wxString &jid);
+    Job(DBconn *conn, 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();
+    JobThread(const std::string &jid, connInfo* serviceConnInfo);
+
 	bool Runnable()
 	{
 		return runnable;
-	}
+    }
+
+    bool finished();
+    //virtual void *Entry();
 
-	virtual void *Entry();
+    ~JobThread();
+
+    JobThread(JobThread const&) = delete;
+    JobThread& operator =(JobThread const&) = delete;
+    void start();
+    void stop();
+     void run();
+protected:
+    DBconn *thConn;
+    std::atomic<bool> m_stop;
 
 private:
-	wxString jobid;
+    std::thread m_thread;
+
+    std::string jobid;
 	bool runnable;
 	Job *job;
+
 };
 
 #endif // JOB_H
diff --git a/include/misc.h b/include/misc.h
index 9a94fd5..d6b070c 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -15,9 +15,11 @@
 
 
 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(int argc, char **argv, connInfo *cInfo);
+std::string getArg(int &argc, char **&argv);
+
+// THST - Neue Fkt
+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..39f80a2 100644
--- a/include/pgAgent.h
+++ b/include/pgAgent.h
@@ -13,26 +13,29 @@
 #ifndef PGAGENT_H
 #define PGAGENT_H
 
-// Disable all the GUI classes that might get pulled in through the headers
-#define wxUSE_GUI 0
-
-#include <wx/wx.h>
-
-#include "misc.h"
-#include "connection.h"
-#include "job.h"
+#include <fstream>
+#include <iostream>
+#include <stdlib.h>
+#include <sstream>
+#include <thread>
+#include <atomic>
+#include <mutex>
+#include <set>
+#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__
+#define PGAGENT_VERSION_MAJOR "3"
+
+//#ifndef __WXMSW__
 extern bool runInForeground;
-extern wxString logFile;
-#endif
+extern std::string logFile;
+//#endif
 
 // Log levels
 enum
@@ -48,14 +51,41 @@ enum
 };
 
 // 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..f2e9488 100644
--- a/job.cpp
+++ b/job.cpp
@@ -11,44 +11,44 @@
 
 #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(DBconn *conn, const std::string &jid)
 {
 	threadConn = conn;
 	jobid = jid;
-	status = wxT("");
+    status = std::string("");
 
-	LogMessage(wxString::Format(_("Starting job: %s"), jobid.c_str()), LOG_DEBUG);
+    LogMessage(std::string("Starting job: ") + jobid, LOG_DEBUG);
+
+    // every DBconn object has the serviceConnInfo object pointer
+    connInfo* serviceConnInfo = conn->getConnInfo();
 
 	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=") + serviceConnInfo->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"));
+//TODO - Vereinfachung mit RETURNING Clause
+        DBresult *id = threadConn->Execute(
+                           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;
@@ -59,57 +59,60 @@ 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()
 {
-	int rc = 0;
-	bool succeeded = false;
+    std::ostringstream oss;
+    int rc = 0;
 	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"));
 
+//TODO - Vereinfachung mit RETURNING Clause
 		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 +126,138 @@ 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"));
-
-				stepConn = DBconn::Get(jstconnstr, jstdbname);
+                std::string jstdbname = steps->GetString(std::string("jstdbname"));
+                std::string jstconnstr = steps->GetString(std::string("jstconnstr"));
+
+                // 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)
 				{
-					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();
+                    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();
 					stepConn->Return();
+                    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':
+            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(filename);
 
-				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))
-				{
-					output.Printf(_("Couldn't open temporary script file: %s"), filename.c_str());
-					LogMessage(output, LOG_WARNING);
-					wxRemoveFile(filename);
-					wxRmdir(dirname);
-					rc = -1;
-					break;
-				}
-
-				wxString code = steps->GetString(wxT("jstcode"));
+                if (Chmod(filename, 0700) !=0 )
+                {
+                    output << "Couldn't create temporary script file: " << filename << std::endl;
+                    LogMessage(output.str(), LOG_WARNING);
+                    rc = -1;
+                    break;
+                }
+                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,25 +272,24 @@ int Job::Execute()
 							break;
 
 						chBuf[dwRead] = 0;
-						output += wxString::FromAscii(chBuf);
+                        output << (chBuf);
 					}
 				}
 
 
-				GetExitCodeProcess(h_process, (LPDWORD)&rc);
-				CloseHandle(h_process);
 				CloseHandle(h_script);
+				rc = 1;
 
 #else
 				// The *nix way.
 				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 +298,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 +307,112 @@ 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:
+
+            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"))
+            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 = wxT("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)
 {
-	LogMessage(wxString::Format(_("Creating job thread for job %s"), jid.c_str()), LOG_DEBUG);
+    LogMessage(std::string("JobThread(const std::string &jid, connInfo* serviceConnInfo) job thread job ") + jid, LOG_DEBUG);
 
 	runnable = false;
 	jobid = jid;
 
-	DBconn *threadConn = DBconn::Get(DBconn::GetBasicConnectString(), serviceDBname);
-	if (threadConn)
+    thConn = new DBconn(serviceConnInfo);
+    if (thConn)
 	{
-		job = new Job(threadConn, jobid);
+        job = new Job(thConn, jobid);
 
 		if (job->Runnable())
 			runnable = true;
+            m_stop = false;
 	}
 }
 
 
 JobThread::~JobThread()
 {
-	LogMessage(wxString::Format(_("Destroying job thread for job %s"), jobid.c_str()), LOG_DEBUG);
+  try {
+    stop();
+    LogMessage(std::string("Destroying job thread for job ") + jobid, LOG_DEBUG);
+    delete job;
+    delete thConn;
+  } catch(...) { LogMessage(std::string("Destroying job thread for job ") + jobid, LOG_ERROR); }
 }
 
+void JobThread::run()
+{
+    if (!m_stop) { // if statt while
+        std::cout << "JobThread::run() - Job execute" << std::endl;
+        job->Execute();
+        m_stop = false;
+    };
+}
 
-void *JobThread::Entry()
+void JobThread::stop()
 {
-	if (runnable)
-	{
-		job->Execute();
-		delete job;
-	}
+    m_stop = true; m_thread.join();
+}
 
-	return(NULL);
+void JobThread::start()
+{
+    std::cout << "JobThread::start()" << std::endl;
+    m_thread = std::thread(&JobThread::run, this);
+}
+
+bool JobThread::finished()
+{
+    if(!m_stop) return true;
+    else return false;
 }
diff --git a/misc.cpp b/misc.cpp
index da9c4ee..982607f 100644
--- a/misc.cpp
+++ b/misc.cpp
@@ -10,42 +10,45 @@
 //////////////////////////////////////////////////////////////////////////
 
 #include "pgAgent.h"
-#include "connection.h"
 
-#ifndef __WXMSW__
 #include <unistd.h>
-#endif
 
-// In unix.c or win32.c
-void usage(const wxString &executable);
+// In unix.cpp or win32.cpp
+void usage(const std::string &executable);
 
-wxString getArg(int &argc, char **&argv)
+std::string getArg(int &argc, char **&argv)
 {
-	wxString s;
+    std::string s;
 	if (argv[0][2])
-		s = wxString::FromAscii(argv[0] + 2);
+        s = std::string(argv[0] + 2);
 	else
 	{
 		if (argc >= 1)
 		{
 			argc--;
 			argv++;
-			s = wxString::FromAscii(argv[0]);
+            s = (argv[0]);
 		}
 		else
 		{
 			// very bad!
-			LogMessage(_("Invalid command line argument"), LOG_ERROR);
+            LogMessage(("Invalid command line argument"), LOG_ERROR);
 		}
 	}
 
 	return s;
 }
 
-
-void setOptions(int argc, char **argv, const wxString &executable)
+void setOptions(int argc, char **argv, connInfo *cInfo)
 {
-	while (argc-- > 0)
+    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);
+
+    temp.clear();
+
+    while (argc-- > 0)
 	{
 		if (argv[0][0] == '-')
 		{
@@ -53,21 +56,21 @@ void setOptions(int argc, char **argv, const wxString &executable)
 			{
 				case 't':
 				{
-					int val = atoi(getArg(argc, argv).mb_str(wxConvUTF8));
+                int val = atoi(getArg(argc, argv).c_str());
 					if (val > 0)
 						shortWait = val;
 					break;
 				}
 				case 'r':
 				{
-					int val = atoi(getArg(argc, argv).mb_str(wxConvUTF8));
+                    int val = atoi(getArg(argc, argv).c_str());
 					if (val >= 10)
 						longWait = val;
 					break;
 				}
 				case 'l':
 				{
-					int val = atoi(getArg(argc, argv).mb_str(wxConvUTF8));
+                    int val = atoi(getArg(argc, argv).c_str());
 					if (val >= 0 && val <= 2)
 						minLogLevel = val;
 					break;
@@ -93,17 +96,16 @@ void setOptions(int argc, char **argv, const wxString &executable)
 		}
 		else
 		{
-			if (connectString != wxT(""))
-				connectString += wxT(" ");
-			connectString += wxString::FromAscii(*argv);
-			if (**argv == '"')
-				connectString = connectString.substr(1, connectString.length() - 2);
+            temp = temp +" "+ std::string(*argv);
 		}
 		argv++;
 	}
+    LogMessage( std::string("DB connection: ") + temp, LOG_DEBUG);
+    if(!temp.empty()) {
+        if(! cInfo->setConnectionString(temp)) LogMessage( std::string("connection string error: ") + temp, LOG_ERROR);
+    } else LogMessage( std::string("No connection string"), LOG_ERROR);
 }
 
-
 void WaitAWhile(const bool waitLong)
 {
 	int count;
@@ -123,12 +125,11 @@ 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..8916b49 100644
--- a/pgAgent.cpp
+++ b/pgAgent.cpp
@@ -15,9 +15,6 @@
 #include <unistd.h>
 #endif
 
-wxString connectString;
-wxString serviceDBname;
-wxString backendPid;
 long longWait = 30;
 long shortWait = 5;
 long minLogLevel = LOG_ERROR;
@@ -26,101 +23,125 @@ 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;
-
-	LogMessage(_("Clearing zombies"), LOG_DEBUG);
-	rc = serviceConn->ExecuteVoid(wxT("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")
-		     );
-	}
-	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")
-		     );
-	}
-
+    char c_hostname[1024];
+    c_hostname[1023] = '\0';
+
+    LogMessage(("Clearing zombies"), LOG_DEBUG);
+    rc = serviceConn->ExecuteVoid("CREATE TEMP TABLE pga_tmp_zombies(jagpid int4)");
+
+    if (serviceConn->BackendMinimumVersion(9, 2))
+    {
+        rc = serviceConn->ExecuteVoid(
+             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(
+                 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())
 				{
-					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,45 @@ 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();
 	}
 	return 0;
 }
 
 
-void MainLoop()
+void MainLoop(connInfo* serviceConnInfo)
 {
 	int attemptCount = 1;
 
 	// 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);
+        DBconn *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 +210,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,32 +234,32 @@ 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
 			Initialized();
 #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);
-
+            MainRestartLoop(serviceConn);
+        } 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..82df2ab 100644
--- a/unix.cpp
+++ b/unix.cpp
@@ -14,69 +14,139 @@
 // *nix only!!
 #ifndef WIN32
 
-#include <wx/filename.h>
-#include <wx/ffile.h>
 #include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <time.h>
+#include <sys/stat.h>
 
-void usage(const wxString &executable)
+std::string CreateTempFileName(std::string prefix)
 {
-	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"));
+    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;
 }
 
-void LogMessage(wxString msg, int level)
+int Mkdir(std::string dirname, mode_t rights)
 {
-	wxFFile file;
-	if (logFile.IsEmpty())
-	{
-		file.Attach(stdout);
-	}
-	else
-	{
-		file.Open(logFile.c_str(), wxT("a"));
-	}
+    return mkdir(dirname.c_str(), rights);
+}
 
-	if (!file.IsOpened())
-	{
-		wxFprintf(stderr, _("Can not open the logfile!"));
-		return;
-	}
+int RemoveFile(std::string filename)
+{
+    return remove(filename.c_str());
+}
+
+/*
+int path_is_directory (const char* path)
+{
+    struct stat s_buf;
+
+    if (stat(path, &s_buf))
+        return 0;
+
+    return S_ISDIR(s_buf.st_mode);
+}
+*/
+int Rmdir(std::string dirname)
+{
+/*        DIR*            dp;
+        struct dirent*  ep;
+        char            p_buf[512] = {0};
+
+        dp = opendir(directory_name);
+
+        while ((ep = readdir(dp)) != NULL) {
+            sprintf(p_buf, "%s/%s", directory_name, ep->d_name);
+            if (path_is_directory(p_buf))
+                delete_folder_tree(p_buf);
+            else
+                unlink(p_buf);
+        }
+
+        closedir(dp);
+        rmdir(directory_name);
+*/
+    return rmdir(dirname.c_str());
+}
+
+int Chmod(std::string dirname, mode_t rights)
+{
+    return chmod(dirname.c_str(), rights);
+}
+
+void usage(const std::string &executable)
+{
+    std::cout << "Usage:\n" << std::endl;
+    std::cout << executable << " [options] <connect-string>\n"<< std::endl;
+    std::cout << "options:\n"<< std::endl;
+    std::cout << "-f run in the foreground (do not detach from the terminal)\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 << "-s <log file (messages are logged to STDOUT if not specified>\n"<< std::endl;
+    std::cout << "-l <logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>\n"<< std::endl;
+}
+
+//TODO - PHASE2 - Replace Func to OFSTREAMS like LOG / LOG_DEBUG / LOG_ERROR << MSG << std::endl;
+void LogMessage(std::string msg, int level)
+{
+    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()) {
+        of.open(logFile, 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 {
+        buf = std::cout.rdbuf();
+    }
+
+    std::ostream log(buf);
 
 	switch (level)
 	{
 		case LOG_DEBUG:
 			if (minLogLevel >= LOG_DEBUG)
-				file.Write(_("DEBUG: ") + msg + wxT("\n"));
+                log << buffer << "|DEBUG|" << msg  << std::flush << std::endl;
 			break;
 		case LOG_WARNING:
 			if (minLogLevel >= LOG_WARNING)
-				file.Write(_("WARNING: ") + msg + wxT("\n"));
+                log << buffer << "|WARNING|" << msg  << std::flush << std::endl;
 			break;
 		case LOG_ERROR:
-			file.Write(_("ERROR: ") + msg + wxT("\n"));
+            log << buffer << "|ERROR|" << msg  << std::flush << std::endl;
 			exit(1);
 			break;
 		case LOG_STARTUP:
-			file.Write(_("WARNING: ") + msg + wxT("\n"));
+            log << buffer << "|WARNING|" << msg  << std::flush << std::endl;
 			break;
 	}
-
-	if (logFile.IsEmpty())
-	{
-		file.Detach();
-	}
-	else
-	{
-		file.Close();
-	}
 }
 
 // Shamelessly lifted from pg_autovacuum...
@@ -87,7 +157,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,7 +166,7 @@ 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
@@ -106,27 +176,25 @@ static void daemonize(void)
 int main(int argc, char **argv)
 {
 	// Statup wx
-	wxInitialize();
-
-	wxString executable;
-	executable = wxString::FromAscii(argv[0]);
 
 	if (argc < 2)
 	{
-		usage(executable);
+        usage(std::string(argv[0]));
 		return 1;
 	}
 
 	argc--;
 	argv++;
 
-	setOptions(argc, argv, executable);
+    connInfo* serviceConnInfo = new connInfo();
+    setOptions(argc, argv, serviceConnInfo);
 
-	if (!runInForeground)
-		daemonize();
+    if (!runInForeground) daemonize();
 
-	MainLoop();
+    LogMessage( std::string("MainLOOP"), LOG_DEBUG);
+    MainLoop(serviceConnInfo);
 
+    delete serviceConnInfo;
 	return 0;
 }
 
diff --git a/win32.cpp b/win32.cpp
index 254f818..7cef778 100644
--- a/win32.cpp
+++ b/win32.cpp
@@ -14,8 +14,8 @@
 // This is for Win32 only!!
 #ifdef WIN32
 
-#include <wx/filename.h>
-#include <wx/config.h>
+//#include <wx/filename.h>
+//#include <wx/config.h>
 #include <process.h>
 
 // for debugging purposes, we can start the service paused
@@ -25,8 +25,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 +57,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 +105,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 +128,8 @@ void LogMessage(wxString msg, int level)
 
 unsigned int __stdcall threadProcedure(void *unused)
 {
-	MainLoop();
+    connInfo *serviceConnInfo = new connInfo();
+    MainLoop(serviceConnInfo);
 	return 0;
 }
 
@@ -139,7 +140,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 +186,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 +326,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 +334,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 +365,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);
 		}
@@ -370,28 +374,29 @@ bool installService(const wxString &serviceName, const wxString &executable,  co
 	}
 
 	// Setup the event message DLL
+//TODO - THST - Make the MS Way
 	wxRegKey *msgKey = new wxRegKey(wxT("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\") + serviceName);
 	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;
 
@@ -424,6 +429,7 @@ bool removeService(const wxString &serviceName)
 	}
 
 	// Remove the event message DLL
+//TODO - THST - Make the MS Way
 	wxRegKey *msgKey = new wxRegKey(wxT("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\") + serviceName);
 	msgKey->DeleteSelf();
 
@@ -432,28 +438,30 @@ bool removeService(const wxString &serviceName)
 
 
 
-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,9 +479,9 @@ void main(int argc, char **argv)
 	// Statup wx
 	wxInitialize();
 
-	wxFileName file = wxString::FromAscii(*argv++);
+    wxFileName file = std::string::FromAscii(*argv++);
 	file.MakeAbsolute();
-	wxString executable = file.GetFullPath();
+    std::string executable = file.GetFullPath();
 
 	if (argc < 3)
 	{
@@ -481,21 +489,21 @@ void main(int argc, char **argv)
 		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 +528,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 +543,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 +558,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);
 
