module Main where

-- Compile with: ghc -package ghc-6.6 --make StopingRunStmt.hs

import qualified GHC
import qualified Outputable
import qualified Packages
import qualified PackageConfig
import DynFlags

import System.IO
import Control.Concurrent

path = "/usr/lib/ghc-6.6/"

main = do session <- initializeSession
          threadId <- forkIO $ GHC.runStmt session "let foo = do threadDelay 100000; putStrLn \"a\"; foo in foo" >> return ()
          threadDelay (10^6*1)
          putStrLn "Killing thread"
          killThread threadId -- the thread is not killed here. Only when the hole programs terminates, is the thresad killed.
          threadDelay (10^6*5)

initializeSession =
    do -- start a new interactive session using the path specified above
       session <- GHC.newSession GHC.Interactive (Just path)
       
       -- initialize the default packages
       dflags1 <- GHC.getSessionDynFlags session
       (dflags2, packageIds) <- Packages.initPackages dflags1
       GHC.setSessionDynFlags session dflags2{GHC.hscTarget=GHC.HscInterpreted}
       
       -- now the order of the statements is important:
       -- 1) load our modified prelude functions
       target <- GHC.guessTarget "MyPrelude.hs" Nothing
       GHC.addTarget session target
       -- this would unload the standard prelude if it had already been loaded
       GHC.load session GHC.LoadAllTargets
       
       -- 2) load the standard prelude
       let preludeModule  = GHC.mkModule (PackageConfig.stringToPackageId "base") (GHC.mkModuleName "Prelude")
       controlConcurrentModule <- GHC.findModule session (GHC.mkModuleName "Control.Concurrent") Nothing
       GHC.setContext session [] [preludeModule, controlConcurrentModule]
       
       -- 3) replace "putStrLn" and "getLine" with our modified versions
       -- replaceFunctions session
       return session

