connect :: IrcConfig       -- ^ Configuration
           -> Bool         -- ^ Run in a new thread
           -> Bool         -- ^ Print debug messages
           -> IO (Either IOError MIrc) -- ^ IrcServer instance
connect config threaded debug = try $ do
  (when debug $
    B.putStrLn $ "Connecting to " `B.append` B.pack (cAddr config))

  h <- connectTo (cAddr config) (PortNumber $ fromIntegral $ cPort config)
  hSetBuffering h NoBuffering

  cmdChan <- newChan

  server <- toServer config h cmdChan debug
  -- Initialize connection with the server
  _ <- greetServer server

  -- Create a new MVar
  res <- newMVar server

  -- Start the loops, listen and exec cmds
  if threaded
    then do listenId <- forkIO (listenLoop res)
            _ <- forkIO (execCmdsLoop res)
            modifyMVar_ res (\srv -> return $ srv {sListenThread = Just listenId})
            return res
    else do listenLoop res
            return res

-- |Sends a QUIT command to the server.
connect :: IrcConfig       -- ^ Configuration
           -> Bool         -- ^ Run in a new thread
           -> Bool         -- ^ Print debug messages
           -> IO (Either IOError MIrc)
connect config threaded debug = try $ do
  (when debug $
    B.putStrLn $ "Connecting to " `B.append` B.pack (cAddr config))

  h <- connectTo (cAddr config) (PortNumber $ fromIntegral $ cPort config)
  hSetBuffering h NoBuffering

  cmdChan <- newChan

  server <- toServer config h cmdChan debug
  -- Initialize connection with the server
  _ <- greetServer server

  -- Create a new MVar
  res <- newMVar server

  -- Start the loops, listen and exec cmds
  if threaded
    then do listenId <- forkIO (listenLoop res)
            _ <- forkIO (execCmdsLoop res)
            modifyMVar_ res (\srv -> return $ srv {sListenThread = Just listenId})
            return res
    else do listenLoop res
            return res

-- |Sends a QUIT command to the server.
connect config threaded debug = try $ do
  (when debug $
    B.putStrLn $ "Connecting to " `B.append` B.pack (cAddr config))

  h <- connectTo (cAddr config) (PortNumber $ fromIntegral $ cPort config)
  hSetBuffering h NoBuffering

  cmdChan <- newChan

  server <- toServer config h cmdChan debug
  -- Initialize connection with the server
  _ <- greetServer server

  -- Create a new MVar
  res <- newMVar server

  -- Start the loops, listen and exec cmds
  if threaded
    then do listenId <- forkIO (listenLoop res)
            _ <- forkIO (execCmdsLoop res)
            modifyMVar_ res (\srv -> return $ srv {sListenThread = Just listenId})
            return res
    else do listenLoop res
            return res

-- |Sends a QUIT command to the server.