require_relative "./run.rb"

if i=ARGV.index("--")
  input = ARGV[i+1..-1]
  ARGV[i..-1] = []
else
  input = STDIN
end

if ["-v", "--version"].any?{|option| ARGV.delete(option) }
  puts Version
  exit
end

pretty_print = ["-p", "--pretty_print"].any?{|option| ARGV.delete(option) }
engine = ["-e", "--engine"].any?{|option| ARGV.delete(option) }

def usage
  raise IogiiError.new "usage: ruby #$0 -v,--version | [-p,--pretty_print] [-e,--engine] <filename.iog> [-- rawargs*]"
end

begin
  usage if ARGV.size == 0

  unknown_options = ARGV.select{|a| a[0] == "-" }
  if !unknown_options.empty?
    STDERR.puts "unknown options: " + unknown_options*" "
    usage
  end

  raise IogiiError.new "mustn't give more than one file arg" if ARGV.size > 1

  if ARGV.size == 1
    begin
      program = IO.binread(ARGV[0])
    rescue SystemCallError => e
      raise IogiiError.new "cannot read file '#{ARGV[0]}'\n#{e.message}"
    end
  end

  run_and_do_io(program, input, pretty_print, engine)
rescue IogiiError => e
  STDERR.puts e.message
  exit(1)
rescue => e
  STDERR.puts "This is an internal iogii error, please report it!\n".red
  raise e
end
