-----------------------------------------------------------------------------
-- |
-- Module      :
-- Copyright   :  (c) Don Stewart 2007
-- License     :  BSD3-style (see LICENSE)
-- 
-- Maintainer  :  dons@cse.unsw.edu.au
-- Stability   :  stable
-- Portability :  not portable (uses concurrency)
--
-----------------------------------------------------------------------------

module Process (run) where

import System.Process
import System.Exit
import System.IO
import System.Process
import Control.Concurrent (forkIO, newEmptyMVar, putMVar, takeMVar)
import qualified Control.Exception as C

run :: FilePath -> [String] -> String -> IO String
run file args input = C.handle (\e -> return (show e)) $ do

    (inp,out,err,pid) <- runInteractiveProcess file args Nothing Nothing
    hPutStr inp input >> hClose inp

    output <- hGetContents out
    errput <- hGetContents err

    outMVar <- newEmptyMVar
    errMVar <- newEmptyMVar

    forkIO (C.evaluate (length output) >> putMVar outMVar ())
    forkIO (C.evaluate (length errput) >> putMVar errMVar ())

    takeMVar outMVar
    takeMVar errMVar

    e <- C.catch
            (waitForProcess pid)
            (\_ -> return ExitSuccess)

    return (output ++ errput)
