module Main ( main )

where

import Prelude hiding ( catch )

import System.IO           ( hPrint, stderr )
import System.Exit         ( exitWith, ExitCode(ExitFailure) )
import System.Environment  ( getProgName )
import Control.Exception   ( catch )
import Control.Applicative ( (<$>) )
import Data.Version        ( showVersion )

-- this one is autogenerated by cabal
import Paths_hylores ( version )

import HyLoRes.FrontEnd.CommandLine ( getCmdLineParams, showHelp, usage )
import HyLoRes.Main                 ( runWithParams )
import HyLoRes.Core.Worker.Base     ( Result(SAT, UNSAT, INTERRUPTED) )

-- This function, replaces the lambda function that as 2nd arg of catch
-- Need it for ghc >=7
teste :: IOError -> IO a 
teste  e = do 	hPrint stderr (show e)
		exit r_RUNTIME_ERROR
	where r_RUNTIME_ERROR = 13

--main :: IO
main = do r <- runCmdLineVersion
                 `catch` teste
          --
          case r of
            Nothing          -> exit r_DID_NOT_RUN
            Just (SAT _)     -> exit r_SAT
            Just UNSAT       -> exit r_UNSAT
            Just INTERRUPTED -> exit r_TIMEOUT
    --
    where r_SAT           = 1
          r_UNSAT         = 2
          r_TIMEOUT       = 3
          r_DID_NOT_RUN   = 10
          r_RUNTIME_ERROR = 13

exit :: Int -> IO a
exit = exitWith . ExitFailure

runCmdLineVersion :: IO (Maybe Result)
runCmdLineVersion =
    do p_clp <- getCmdLineParams
       case p_clp of
         Left  err -> do putStrLn header
                         putStrLn err
                         hylores <- getProgName
                         putStrLn $ "Try `" ++ hylores ++ " --help' " ++
                                     "for more information"
                         return Nothing
         --
         Right clp -> if showHelp clp
                        then do putStrLn header
                                hylores <- getProgName
                                putStrLn $ usage (hylores ++ " [OPTIONS]")
                                putStrLn gpl_tag
                                return Nothing
                        --
                        else Just <$> runWithParams clp

header :: String
header = unlines ["HyLoRes " ++ showVersion version,
                  "C. Areces, D.Gorin and J. Heguiabehere. (c) 2002-2007."]

gpl_tag :: String
gpl_tag = unlines [
    "This program is distributed in the hope that it will be useful,",
    "but WITHOUT ANY WARRANTY; without even the implied warranty of",
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the",
    "GNU General Public License for more details."]
