--- pgAgent-NG/pgAgent.cpp	2013-09-11 09:30:03.522629835 +0200
+++ pgagent/pgAgent.cpp	2013-09-11 12:02:08.413191475 +0200
@@ -15,6 +15,9 @@
 #include <unistd.h>
 #endif
 
+wxString connectString;
+wxString serviceDBname;
+wxString backendPid;
 long longWait = 30;
 long shortWait = 5;
 long minLogLevel = LOG_ERROR;
@@ -23,125 +26,101 @@
 
 #ifndef __WXMSW__
 bool runInForeground = false;
-std::string logFile;
-
-#include <stdio.h>
-#include <stdlib.h>
+wxString logFile = wxEmptyString;
 #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("CREATE TEMP TABLE pga_tmp_zombies(jagpid int4)");
+	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")
+		     );
+	}
 
-    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(
-                 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")+
-
-                 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_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")
+
+		         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_job SET jobagentid=NULL, jobnextrun=NULL ")+
-                 std::string("  WHERE jobagentid IN (SELECT jagpid FROM pga_tmp_zombies);\n")+
+		         wxT("UPDATE pgagent.pga_job SET jobagentid=NULL, jobnextrun=NULL ")
+		         wxT("  WHERE jobagentid 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")
+		         wxT("DELETE FROM pgagent.pga_jobagent ")
+		         wxT("  WHERE jagpid IN (SELECT jagpid FROM pga_tmp_zombies);\n")
 		     );
 	}
 
-    rc = serviceConn->ExecuteVoid(std::string("DROP TABLE pga_tmp_zombies"));
+	rc = serviceConn->ExecuteVoid(wxT("DROP TABLE pga_tmp_zombies"));
 
-    // get Hostname
-    gethostname(c_hostname, 1023);
-    std::string hostname = c_hostname;
+	wxString hostname = wxGetFullHostName();
 
 	rc = serviceConn->ExecuteVoid(
-             std::string("INSERT INTO pgagent.pga_jobagent (jagpid, jagstation) SELECT pg_backend_pid(), '") + hostname + std::string("'"));
+	         wxT("INSERT INTO pgagent.pga_jobagent (jagpid, jagstation) SELECT pg_backend_pid(), '") + hostname + wxT("'"));
 	if (rc < 0)
 		return rc;
 
 	while (1)
 	{
-        LogMessage(("Checking for jobs to run"), LOG_DEBUG);
+		bool foundJobToExecute = false;
+
+		LogMessage(_("Checking for jobs to run"), LOG_DEBUG);
 		DBresult *res = serviceConn->Execute(
-                            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"));
+		                    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"));
 
 		if (res)
 		{
 			while(res->HasData())
 			{
-                std::string jobid = res->GetString(std::string("jobid"));
+				wxString jobid = res->GetString(wxT("jobid"));
 
-                JobThread *jt = new JobThread(jobid, serviceConn->getConnInfo());
+				JobThread *jt = new JobThread(jobid);
 
 				if (jt->Runnable())
 				{
-                    // start the Threading Job
-                    jt->start();
-                    // remember the Thread Job
-                    jtListe.insert(jt);
+					jt->Create();
+					jt->Run();
+					foundJobToExecute = true;
 				}
 				else
 				{
@@ -149,8 +128,8 @@
 					// "internal error" status in the joblog table, to leave
 					// a trace of fact that we tried to launch the job.
 					DBresult *res = serviceConn->Execute(
-                        std::string("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ")+
-                        std::string("VALUES (nextval('pgagent.pga_joblog_jlgid_seq'), ") + jobid + std::string(", 'i')"));
+						wxT("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ")
+						wxT("VALUES (nextval('pgagent.pga_joblog_jlgid_seq'), ") + jobid + wxT(", 'i')"));
 					if (res)
 						delete res;
 
@@ -163,45 +142,45 @@
 			}
 
 			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);
 		}
-        // clear JobThreads when idle or every loop?!
-        ClearJobThreads();
+		if (!foundJobToExecute)
+			DBconn::ClearConnections();
 	}
 	return 0;
 }
 
 
-void MainLoop(connInfo* serviceConnInfo)
+void MainLoop()
 {
 	int attemptCount = 1;
 
 	// OK, let's get down to business
 	do
 	{
-        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);
+		LogMessage(_("Creating primary connection"), LOG_DEBUG);
+		DBconn *serviceConn = DBconn::InitConnection(connectString);
 
 		if (serviceConn && serviceConn->IsValid())
 		{
+			serviceDBname = serviceConn->GetDBname();
+
 			// Basic sanity check, and a chance to get the serviceConn's PID
-            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'"));
+			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'"));
 			if (res)
 			{
-                std::string val = res->GetString(std::string("count"));
+				wxString val = res->GetString(wxT("count"));
 
-                if (val == std::string("0"))
-                    LogMessage(("Could not find the table 'pgagent.pga_job'. Have you run pgagent.sql on this database?"), LOG_ERROR);
+				if (val == wxT("0"))
+					LogMessage(_("Could not find the table 'pgagent.pga_job'. Have you run pgagent.sql on this database?"), LOG_ERROR);
 
-                serviceConnInfo->backendPid = res->GetString(std::string("pid"));
+				backendPid = res->GetString(wxT("pid"));
 
 				delete res;
 				res = NULL;
@@ -210,23 +189,23 @@
 			// Check for particular version
 
 			bool hasSchemaVerFunc = false;
-            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 = ''                                     ");
+			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 = ''                                     ");
 
 			res = serviceConn->Execute(sqlCheckSchemaVersion);
 
 			if (res)
 			{
-                if (res->IsValid() && res->GetString(0) == std::string("1"))
+				if (res->IsValid() && res->GetString(0) == wxT("1"))
 					hasSchemaVerFunc = true;
 				delete res;
 				res = NULL;
@@ -234,32 +213,32 @@
 
 			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);
 			}
 
-            std::string strPgAgentSchemaVer = serviceConn->ExecuteScalar(std::string("SELECT pgagent.pgagent_schema_version()"));
-            std::stringstream currentPgAgentVersion;
-            currentPgAgentVersion <<  PGAGENT_VERSION_MAJOR;
-            if (strPgAgentSchemaVer != currentPgAgentVersion.str())
+			wxString strPgAgentSchemaVer = serviceConn->ExecuteScalar(wxT("SELECT pgagent.pgagent_schema_version()"));
+			wxString currentPgAgentVersion;
+			currentPgAgentVersion.Printf(_("%d"), PGAGENT_VERSION_MAJOR);
+			if (strPgAgentSchemaVer != currentPgAgentVersion)
 			{
-                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);
+				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);
 			}
 
 #ifdef WIN32
 			Initialized();
 #endif
-            MainRestartLoop(serviceConn);
-        } else {
-            std::stringstream log;
-            log << "Couldn't create the primary connection (attempt " << attemptCount << "):" << serviceConn->GetLastError() << "" << std::endl;
-            LogMessage(log.str(), LOG_STARTUP);
-        }
+			MainRestartLoop(serviceConn);
+		}
+
+		LogMessage(wxString::Format(_("Couldn't create the primary connection (attempt %d): %s"), attemptCount, serviceConn->GetLastError().c_str()), LOG_STARTUP);
+		DBconn::ClearConnections(true);
+
 		// Try establishing primary connection upto MAXATTEMPTS times
 		if (attemptCount++ >= (int)MAXATTEMPTS)
 		{
-            LogMessage(std::string("Stopping pgAgent: Couldn't establish the primary connection with the database server."), LOG_ERROR);
+			LogMessage(wxString::Format(_("Stopping pgAgent: Couldn't establish the primary connection with the database server.")), LOG_ERROR);
 		}
 		WaitAWhile();
 	}
