open Parsing
open Lexing

type action = Bytecode | Compile | Semantic | Bypass | NoStl

let read_file filename = 
  let lines = ref [] in
  let chan = open_in filename in
  try
    while true; do
      lines := input_line chan :: !lines
    done; []
  with End_of_file ->
    close_in chan;
    List.rev !lines;; 

let check prog = Semantic.check_semantic prog in
   let arglength = Array.length Sys.argv in
   let action = if arglength > 2 then
   List.assoc Sys.argv.(1) [ 
			      ("-b", Bytecode);
			      ("-c", Compile);
			      ("-y", Bypass);
			      ("-n", NoStl);
               ("-s", Semantic)]
  else Compile in
     let lexbuf = 
     match action with
        | NoStl ->
         Lexing.from_string 
         (String.concat "\n" 
            (read_file Sys.argv.(arglength-1) ))
         | _ ->
         Lexing.from_string 
         (String.concat "\n" 
            (read_file Sys.argv.(arglength-1) @ read_file "stdlib/stl.cv")) in
     let program = try Parser.program Scanner.token lexbuf 
      with Parse_error -> raise (Failure("Syntax error in program at " 
        ^ string_of_int((Parsing.symbol_start_pos()).pos_cnum))) in
     match action with
      | NoStl ->
         check program;
         let listing =
            Bytecode.string_of_prog (Compile.translate program)
         in print_endline listing
      | Bypass -> 
         Execute.execute_prog (Compile.translate program)
      | Bytecode -> 
         check program;
         let listing =
            Bytecode.string_of_prog (Compile.translate program)
         in print_endline listing
      | Compile -> 
         check program;
         Execute.execute_prog (Compile.translate program)
      | Semantic ->
         check program
