startServer :: PortID -> PscEnvironment -> IO ()
startServer port env = withSocketsDo $ do
  sock <- listenOnLocalhost port
  runLogger (runReaderT (forever (loop sock)) env)
  where
    runLogger = runStdoutLoggingT . filterLogger (\_ _ -> confDebug (envConfiguration env))

    loop :: (PscIde m, MonadLogger m) => Socket -> m ()
    loop sock = do
      (cmd,h) <- acceptCommand sock
      case decodeT cmd of
        Just cmd' -> do
          result <- runExceptT (handleCommand cmd')
          $(logDebug) ("Answer was: " <> T.pack (show result))
          liftIO (hFlush stdout)
          case result of
            -- What function can I use to clean this up?
            Right r  -> liftIO $ T.hPutStrLn h (encodeT r)
            Left err -> liftIO $ T.hPutStrLn h (encodeT err)
        Nothing -> do
          $(logDebug) ("Parsing the command failed. Command: " <> cmd)
          liftIO $ T.hPutStrLn h (encodeT (GeneralError "Error parsing Command.")) >> hFlush stdout
      liftIO (hClose h)
startServer :: PortID -> PscEnvironment -> IO ()
startServer port env = withSocketsDo $ do
  sock <- listenOnLocalhost port
  runLogger (runReaderT (forever (loop sock)) env)
  where
    runLogger = runStdoutLoggingT . filterLogger (\_ _ -> confDebug (envConfiguration env))

    loop :: (PscIde m, MonadLogger m) => Socket -> m ()
    loop sock = do
      (cmd,h) <- acceptCommand sock
      case decodeT cmd of
        Just cmd' -> do
          result <- runExceptT (handleCommand cmd')
          $(logDebug) ("Answer was: " <> T.pack (show result))
          liftIO (hFlush stdout)
          case result of
            -- What function can I use to clean this up?
            Right r  -> liftIO $ T.hPutStrLn h (encodeT r)
            Left err -> liftIO $ T.hPutStrLn h (encodeT err)
        Nothing -> do
          $(logDebug) ("Parsing the command failed. Command: " <> cmd)
          liftIO $ T.hPutStrLn h (encodeT (GeneralError "Error parsing Command.")) >> hFlush stdout
      liftIO (hClose h)
startServer port env = withSocketsDo $ do
  sock <- listenOnLocalhost port
  runLogger (runReaderT (forever (loop sock)) env)
  where
    runLogger = runStdoutLoggingT . filterLogger (\_ _ -> confDebug (envConfiguration env))

    loop :: (PscIde m, MonadLogger m) => Socket -> m ()
    loop sock = do
      (cmd,h) <- acceptCommand sock
      case decodeT cmd of
        Just cmd' -> do
          result <- runExceptT (handleCommand cmd')
          $(logDebug) ("Answer was: " <> T.pack (show result))
          liftIO (hFlush stdout)
          case result of
            -- What function can I use to clean this up?
            Right r  -> liftIO $ T.hPutStrLn h (encodeT r)
            Left err -> liftIO $ T.hPutStrLn h (encodeT err)
        Nothing -> do
          $(logDebug) ("Parsing the command failed. Command: " <> cmd)
          liftIO $ T.hPutStrLn h (encodeT (GeneralError "Error parsing Command.")) >> hFlush stdout
      liftIO (hClose h)