Index: include/debugger/frmDebugger.h
===================================================================
--- include/debugger/frmDebugger.h	(revision 8220)
+++ include/debugger/frmDebugger.h	(working copy)
@@ -10,13 +10,13 @@
 //////////////////////////////////////////////////////////////////////////
 
 ////////////////////////////////////////////////////////////////////////////////
-//	class frmDebugger
+//    class frmDebugger
 //
 //  frmDebugger manages the user interface for the workstation. This class
 //  manages the toolbar, menu, status bar, and top-level windows.  
 //
-//	This class also defines event handlers for a number of high-level events
-//	(such as window sizing and layout, and creation of new windows).
+//    This class also defines event handlers for a number of high-level events
+//    (such as window sizing and layout, and creation of new windows).
 //
 ////////////////////////////////////////////////////////////////////////////////
 
@@ -135,7 +135,7 @@
     void OnVarChange( wxGridEvent & event ); 
     void OnClose( wxCloseEvent & event );
     void OnExit( wxCommandEvent & event );
-	void OnSize( wxSizeEvent & event );
+    void OnSize( wxSizeEvent & event );
     void OnEraseBackground(wxEraseEvent& event);
     void OnHelp(wxCommandEvent& event);
     void OnContents(wxCommandEvent& event);
Index: include/debugger/dbgPgConn.h
===================================================================
--- include/debugger/dbgPgConn.h	(revision 8220)
+++ include/debugger/dbgPgConn.h	(working copy)
@@ -76,18 +76,23 @@
     PGconn *getConnection();                // Returns the libpq connection handle
     void Close();                           // Close this connection
     void Cancel();                          // Cancel any ongoing queries
+    void SetCancelConn();                   // Set connection for the Cancellation
+    void ResetCancelConn();                 // Reset cancellation connection
 
     void startCommand( const wxString &command, wxEvtHandler * caller, wxEventType eventType = wxEVT_NULL, dbgPgParams *params = NULL );    // Starts executing a command    
     void setNoticeHandler( PQnoticeProcessor handler, void * arg ); // Registers a NOTICE handler
     PGresult *waitForCommand( const wxString &command );            // Starts a command and waits for completion
+    void stopDebugging();
 
   private:
 
     void Init( const wxString &server, const wxString &database, const wxString &userName, const wxString &password, const wxString &port, int sslmode, bool startThread );
 
-    PGconn *m_pgConn;               // libpq connection handler
-    dbgPgThread *m_workerThread;    // Worker thread (this thread interacts with the server)
+    PGconn      *m_pgConn;                 // libpq connection handler
+    PGcancel    *m_cancelConn;             // libpq cancellation connection handler
+    dbgPgThread *m_workerThread;           // Worker thread (this thread interacts with the server)
     frmDebugger *m_frame;
+    wxMutex      m_pgcancelMutex;          // Mutex to serialize access to m_cancelConn
     int m_minorVersion, m_majorVersion;
     bool m_isEdb;
     bool m_isGreenplum;
Index: include/debugger/dbgPgThread.h
===================================================================
--- include/debugger/dbgPgThread.h	(revision 8220)
+++ include/debugger/dbgPgThread.h	(working copy)
@@ -62,6 +62,7 @@
     virtual void * Entry();
     void startCommand( const wxString &command, wxEvtHandler * caller, wxEventType eventType = wxEVT_NULL, dbgPgParams *params = NULL );
     void Die();
+    void clearAllCommands();
 	
 private:
 
Index: include/debugger/dlgDirectDbg.h
===================================================================
--- include/debugger/dlgDirectDbg.h	(revision 8220)
+++ include/debugger/dlgDirectDbg.h	(working copy)
@@ -50,6 +50,7 @@
     void setupParamWindow();
 	bool startDebugging();
     bool GetCancelled() { return m_cancelled; };
+	void CloseConnection();
 
 private:
 
Index: debugger/dbgPgConn.cpp
===================================================================
--- debugger/dbgPgConn.cpp	(revision 8220)
+++ debugger/dbgPgConn.cpp	(working copy)
@@ -44,13 +44,13 @@
 //    The constructor creates a new thread and connects to the specified server
 
 dbgPgConn::dbgPgConn(frmDebugger *frame, const wxString &server, const wxString &database, const wxString &userName, const wxString &password, const wxString &port, int sslmode)
-   : m_frame(frame)
+   : m_frame(frame), m_pgcancelMutex()
 {
     Init( server, database, userName, password, port, sslmode, true );
 }
 
 dbgPgConn::dbgPgConn(frmDebugger *frame, const dbgConnProp & props, bool startThread )
-   : m_frame(frame)
+   : m_frame(frame), m_pgcancelMutex()
 {
     Init(  props.m_host, props.m_database, props.m_userName, props.m_password, props.m_port, props.m_sslMode, startThread );
 }
@@ -58,6 +58,7 @@
 void dbgPgConn::Init( const wxString &server, const wxString &database, const wxString &username, const wxString &password, const wxString &port, int sslmode, bool startThread )
 {
     m_pgConn       = NULL;
+    m_cancelConn   = NULL;
     m_majorVersion = 0;
     m_minorVersion = 0;
     m_debuggerApiVersion = DEBUGGER_UNKNOWN_API;
@@ -308,6 +309,15 @@
     return( result );
 }
 
+void dbgPgConn::stopDebugging()
+{
+    // Clear all other commands before cancelling the current command
+    m_workerThread->clearAllCommands();
+
+    // Cancel the current command execution
+    Cancel();
+}
+
 ////////////////////////////////////////////////////////////////////////////////
 // setNoticeHandler()
 //
@@ -350,14 +360,15 @@
 
 void dbgPgConn::Cancel()
 {
+    m_pgcancelMutex.Lock();
     // Attempt to cancel any ongoing query
-    if (m_pgConn)
+    if (m_cancelConn)
     {
-        PGcancel *cancel = PQgetCancel(m_pgConn);
         char errbuf[256];
-        PQcancel(cancel, errbuf, sizeof(errbuf));
-        PQfreeCancel(cancel);
+        PQcancel(m_cancelConn, errbuf, sizeof(errbuf));
     }
+    m_pgcancelMutex.Unlock();
+    ResetCancelConn();
 }
 
 // Check the backend version
@@ -485,5 +496,37 @@
     return m_isGreenplum; 
 }
 
+void dbgPgConn::SetCancelConn(void)
+{
+    PGcancel   *oldCancelConn;
 
+    m_pgcancelMutex.Lock();
+    /* Free the old one if we have one */
+    oldCancelConn = m_cancelConn;
+    /* be sure handle_sigint doesn't use pointer while freeing */
+    m_cancelConn = NULL;
 
+    if (oldCancelConn != NULL)
+        PQfreeCancel(oldCancelConn);
+
+    m_cancelConn = PQgetCancel(m_pgConn);
+
+    m_pgcancelMutex.Unlock();
+}
+
+void dbgPgConn::ResetCancelConn(void)
+{
+    PGcancel   *oldCancelConn;
+
+    m_pgcancelMutex.Lock();
+    oldCancelConn = m_cancelConn;
+    /* be sure handle_sigint doesn't use pointer while freeing */
+    m_cancelConn = NULL;
+
+    if (oldCancelConn != NULL)
+       PQfreeCancel(oldCancelConn);
+
+    m_pgcancelMutex.Unlock();
+
+}
+
Index: debugger/ctlCodeWindow.cpp
===================================================================
--- debugger/ctlCodeWindow.cpp	(revision 8220)
+++ debugger/ctlCodeWindow.cpp	(working copy)
@@ -1260,7 +1260,10 @@
 
 void ctlCodeWindow::stopDebugging()
 {
-    m_dbgConn->startCommand( wxString::Format( m_commandAbortTarget, m_sessionHandle.c_str()), GetEventHandler(), RESULT_ID_ABORT_TARGET );
+    wxLogInfo( _("Stop Debugging"), _( "" ));
+    m_dbgConn->stopDebugging();
+    //m_dbgConn->startCommand( wxString::Format( m_commandAbortTarget, m_sessionHandle.c_str()), GetEventHandler(), RESULT_ID_ABORT_TARGET );
+    m_targetAborted = true;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
Index: debugger/dbgPgThread.cpp
===================================================================
--- debugger/dbgPgThread.cpp	(revision 8220)
+++ debugger/dbgPgThread.cpp	(working copy)
@@ -108,6 +108,12 @@
         m_owner.setNoticeHandler( noticeHandler, this );
 
         m_currentCommand = getNextCommand();
+        if (m_currentCommand == NULL)
+        {
+            Yield();
+            wxMilliSleep(10);
+            continue;
+        }
         wxString command = m_currentCommand->getCommand();
 
         wxLogInfo( wxT( "Executing: %s" ), command.c_str());
@@ -142,6 +148,7 @@
                 return this;
             }
 
+            m_owner.SetCancelConn();
             int ret = PQiSendQueryPreparedOut(m_owner.getConnection(), 
                                                 stmt.mb_str(wxConvUTF8),
                                                 params->nParams,
@@ -151,6 +158,7 @@
                                                 1);
             if (ret != 1)
             {
+                m_owner.ResetCancelConn();
                 wxLogError(_( "Couldn't execute the callable statement: %s" ), stmt.c_str());
                 PQclear(res);
                 return this;
@@ -165,7 +173,7 @@
         	{
         		if (die || TestDestroy())
         		{
-        		    PQrequestCancel(m_owner.getConnection());
+                            m_owner.Cancel();
         		    return this;
         	    }
         			
@@ -193,6 +201,7 @@
         	    PQclear(dummy);
                 result = PQiGetOutResult(m_owner.getConnection());
         	}
+            m_owner.ResetCancelConn();
         }
         else
         {
@@ -202,11 +211,13 @@
         	// Note that this is all async code as far as libpq is concerned to
         	// ensure we can always bail out when required, without leaving threads
         	// hanging around.
+            m_owner.SetCancelConn();
             int ret = PQsendQuery(m_owner.getConnection(), command.mb_str(wxConvUTF8));
         	
             if (ret != 1)
             {
                 wxLogError(_( "Couldn't execute the query (%s): %s" ), command.c_str(), wxString(PQerrorMessage(m_owner.getConnection()), *conv).c_str());
+                m_owner.ResetCancelConn();
                 return this;
             }
         	
@@ -215,6 +226,7 @@
         	{
         		if (die || TestDestroy())
         		{
+                        m_owner.Cancel();
         		    PQrequestCancel(m_owner.getConnection());
         		    return this;
         	    }
@@ -237,6 +249,7 @@
         			
                 result = part;
         	}
+                m_owner.ResetCancelConn();
         	
 #if defined (__WXMSW__) || (EDB_LIBPQ)
         }
@@ -346,6 +359,12 @@
 
     wxLogInfo( wxT( "%d commands in queue" ), m_commandQueue.GetCount());
 
+    if (m_commandQueue.GetCount() == 0)
+    {
+        m_queueMutex.Unlock();
+        return NULL;
+    }
+
     ThreadCommandList::Node * node = m_commandQueue.GetFirst();
         
     result = node->GetData();
@@ -356,3 +375,15 @@
 
     return( result );
 }
+
+void dbgPgThread::clearAllCommands()
+{
+    m_queueMutex.Lock();
+    while (!m_commandQueue.IsEmpty())
+    {
+        ThreadCommandList::Node * node = m_commandQueue.GetFirst();
+        m_commandQueue.DeleteNode( node );
+    }
+    m_queueMutex.Unlock();
+}
+
Index: debugger/dlgDirectDbg.cpp
===================================================================
--- debugger/dlgDirectDbg.cpp	(revision 8220)
+++ debugger/dlgDirectDbg.cpp	(working copy)
@@ -400,16 +400,10 @@
     if (grdParams)
     {
         grdParams->Destroy();
-        delete grdParams;
     }
 
     // Close the debugger (proxy) connection
-    if (m_conn)
-    {
-        m_conn->Close();
-        delete m_conn;
-        m_conn = NULL;
-    }
+	CloseConnection();
 
 	// Closing frmMain from here leads to recursive call
     // to OnClose function on windows
@@ -431,6 +425,15 @@
     }
 }
 
+void dlgDirectDbg::CloseConnection()
+{
+    if (m_conn)
+    {
+        m_conn->Close();
+        delete m_conn;
+        m_conn = NULL;
+    }
+}
 ////////////////////////////////////////////////////////////////////////////////
 // activateDebugger()
 //
Index: debugger/frmDebugger.cpp
===================================================================
--- debugger/frmDebugger.cpp	(revision 8220)
+++ debugger/frmDebugger.cpp	(working copy)
@@ -377,16 +377,22 @@
 
 void frmDebugger::OnClose( wxCloseEvent & event )
 {
-    if (m_standaloneDebugger)
-    {
+    if (m_standaloneDirectDbg)
+	{
+        m_standaloneDirectDbg->CloseConnection();
+		m_standaloneDirectDbg = NULL;
+	}
+	if (m_standaloneDebugger)
+	{
         m_standaloneDebugger->OnClose( event );
-        if (event.GetVeto())
-            return;
+		m_standaloneDebugger->Destroy();
+        m_standaloneDebugger = NULL;
+	}
 
-        delete m_standaloneDebugger;
-        m_standaloneDebugger = NULL;
-    }
-    event.Skip();
+    if (event.GetVeto())
+        return;
+
+	event.Skip();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
