(* 
 File: Files.sml

 File handling for the PEPA Workbench
*)

structure Files :> Files =
struct

  val job = ref ""

  fun jobName () = !job

  fun checkForOptions commentString = 
    let 
      val format = implode o map Char.toLower o 
                   List.filter Char.isAlpha o explode
      fun option opt = String.isPrefix opt (format commentString) 
    in
      if option "maple" then
         Options.setSolver Options.Maple else
      if option "matlab" then
         Options.setSolver Options.Matlab else
      if option "mathematica" then
         Options.setSolver Options.Mathematica else
      if option "nohashing" then
         Options.setNohashing ()
      else ()
    end

  fun setFile s = job := s

  fun readFile s =
    let 
      val reverse = implode o rev o explode
      fun hasext s = String.isPrefix "apep." (reverse s)
      val f = TextIO.openIn s handle _ => 
	TextIO.openIn (s^".pepa") handle _ =>
	  if hasext s
	  then Error.fatal_error ("Cannot open \"" ^ s ^ "\"")
	  else Error.fatal_error ("Cannot open \"" ^ s ^ "\" or \"" ^ 
					   s ^ ".pepa\"")

      val c = ref (SOME #" ")
      val r = ref [] : char list ref 

      fun prepend (ref NONE) = ()
        | prepend (ref (SOME c)) = r := c :: !r
    in
      job := s;
      while (c := TextIO.input1 f; !c <> NONE) do
	if !c = SOME #"%" (* Added comment syntax *)
	then checkForOptions (TextIO.inputLine f)
	else prepend c;
      TextIO.closeIn f;
      rev (!r)
    end

end;
