         mutex.lock()
         readyToWrite = false
         mutex.unlock()
-        outputStream?.delegate = nil
-        inputStream?.delegate = nil
-        if let stream = inputStream {
-            CFReadStreamSetDispatchQueue(stream, nil)
-            stream.close()
-        }
-        if let stream = outputStream {
-            CFWriteStreamSetDispatchQueue(stream, nil)
-            stream.close()
-        }
-        outputStream = nil
-        inputStream = nil
+        cleanupStream()
     }
     
 }

            stream.close()
        }
        outputStream = nil
        certValidated = false
        doDisconnect(error)
    }
    
    ///handles the incoming bytes and sending them to the proper processing method

    //disconnect the stream object
    private func disconnectStream(error: NSError?) {
        writeQueue.waitUntilAllOperationsAreFinished()
        cleanupStream()
        doDisconnect(error)
    }
    
    private func cleanupStream() {
        outputStream?.delegate = nil
        inputStream?.delegate = nil
        if let stream = inputStream {
            CFReadStreamSetDispatchQueue(stream, nil)
            stream.close()
