#! /usr/bin/ruby

require './tokenizer.rb'
require './checker.rb'
require './parser.rb'
require './translator.rb'


# takes the name of an IttyBitty program as a command line argument,
#    reads the file,
#    runs the ruby tokenizer and checker,
#    if it passes the checker it then runs the code
#       through the parser and translator
#       and displays the resulting C code


# process(code)
# -------------
# function to try tokenizing, checking, parsing, and translating an IttyBitty program,
#     displaying final results
# expects the source code as its parameter
def process(code)

   # get the token list
   tokenlist = tokenize(code)

   # try to check the given tokenlist
   check,pos = parseChecker(tokenlist)
   if check == false then
      puts "   parse checking failed"
   elsif pos < tokenlist.length then
      puts "   parse checking succeeded, but only #{pos}/#{tokenlist.length} tokens were parsed?"
   end

   # if it passed syntax checking, try to parse the given tokenlist
   if check then
      parsetree,pos = parse(tokenlist)
      # if parsing succeeded, try to translate the parse tree
      if parsetree != false then
         result = translate(parsetree, $ymtable)
         puts "#{result}"
      else
         puts "\n---not translating, failed in parser---\n"
      end
   else
      puts "not parsing (failed check)\n\n"
   end
end

# ===== get the filename as a command line argument,
#       read the file, and
#       process the code

# get the filename (command line argument or user input)
filename = ""
if ARGV.length < 1 then
   puts "correct use is  #{$0} filename"
   puts "please enter the desired filename now"
   filename = gets.chomp
else
   filename = ARGV[0]
end

# read the file contents into a variable and process
begin
   contents = ""
   fhandle = File.open(filename, "r")
   while !fhandle.eof? do
      contents += fhandle.readline
   end
   # process the file
   process(contents)
#rescue
#   puts "sorry, unable to process file #{filename}"
end

