
(* For running the thing from toplevel; probably an exportable
   main () eventually.  - Tom 7 *)

structure Top =
struct

  exception Done

    fun run _ =
      let
	fun gsec t = LargeInt.toInt (Time.toSeconds (Timer.checkRealTimer t))

        val tmr = Timer.startRealTimer ()


        val secs = 
	  (case Params.docommandline () of
            nil => 179
          | [i] => Option.getOpt (Int.fromString i, 179)) 
            handle _ =>
              let in
                print "this program takes one or no arguments. usage:\n";
		print (Params.usage ());
                raise Done
              end

	fun guardl e =
		((secs - gsec tmr) < 20) andalso
		    (Print.linearoutput e; raise Done)

	fun guardt e =
		((secs - gsec tmr) < 20) andalso
		    (Print.treeoutput e; raise Done)

        val exp =  (Tokenize.tokenize (FStream.stdin ()))
	
	val exp = (guardl exp; ToTree.totree exp)
	val nexp = (guardt exp; ReEncode.optimize exp)
	val exp = if Print.sizet nexp > Print.sizet exp then exp else nexp
	val exp = (guardt exp; WhiteSpace.optimize exp)
	val exp = (guardt exp; RedundantTags.optimize exp)
	val exp = (guardt exp; Useless.useless exp)
	val exp = (guardt exp; Hoist.optimize exp)


      in
	Print.treeoutput exp
      end handle e => (TextIO.output(TextIO.stdErr, exnMessage e);
			TextIO.output(TextIO.stdErr, " = (exn)done\n"))

end

