 public class SQPool {
     
     private let path: String?
-    private let flags = SQDatabase.Flags.ReadWriteCreate
-    private var useID = 0
-    private var connPool: [SQDatabase] = []
+    private var connIndex = 1
+    private let flags = SQDatabase.Flag.ReadWriteCreate
+    private var connPool: [Int:SQDatabase] = [:]
     private var inUsePool: [Int:SQDatabase] = [:]
     
     // Queue for database write operations

        useWALMode()
    }
    
    public init(path: String?, withFlags flags: SQDatabase.Flags) {
        self.path = path
        self.flags = flags
        useWALMode()
    }
    
    deinit {
        useDeleteMode()
        connPool = []
        inUsePool = [:]
    }
    
    private func useWALMode() {
        let db = SQDatabase(path: path)
        db.openWithFlags(flags)
        db.query("PRAGMA journal_mode=WAL", withObjects: [])
        connPool.append(db)
    }
    
    private func useDeleteMode() {
        let (index, db) = getConnection()
        db.query("PRAGMA journal_mode=DELETE", withObjects: [])
        releaseConnection(index)
    }
    
    private func getConnection() -> (Int, SQDatabase) {
        var index = 0
        var db: SQDatabase?
        dispatch_sync(poolQueue, {
            self.useID++
            index = self.useID
            if self.connPool.isEmpty {
                let database = SQDatabase(path: self.path)
                database.openWithFlags(self.flags)
                self.inUsePool[self.useID] = database
                println("Using new connection: \(self.useID)")
                db = database
                return
            }
            let database = self.connPool.removeLast()
            self.inUsePool[self.useID] = database
            println("Using connection: \(self.useID)")
            db = database
            return
        })
        return (index, db!)
    }
    
    private func releaseConnection(index: Int) {
        dispatch_sync(poolQueue, {
            if self.connPool.count < self.maxSustainedConnections {
                println("Returning connection: \(index)")
                let database = self.inUsePool.removeValueForKey(index)!
                self.connPool.append(database)
                return
            }
            self.inUsePool[index] = nil

        releaseConnection(index)
    }
    
    public func writeAsync(closure: (SQDatabase)->Void) {
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {self.write(closure)})
    }
    
    public func read(closure: (SQDatabase)->Void) {
        let (index, db) = getConnection()
        closure(db)
        releaseConnection(index)
    }
    
    public func readAsync(closure: (SQDatabase)->Void) {
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {self.read(closure)})
    }
    
}
