import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import rebelsky.compiler.misc.AdvCharStream;
import rebelsky.compiler.misc.StandardCharStream;
import rebelsky.compiler.parser.Node;
import rebelsky.compiler.parser.TreePrinter;
import rebelsky.pal.Computer;
import rebelsky.pal.InstructionSequence;

/**
 * Have lots of fun with a Stupid program.  Prints out the parse
 * tree, translates and prints out the PAL code, then executes
 * the PAL code.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of December 2002
 */
public class Stupid
{
  public static void main(String[] args) 
    throws Exception
  {
    String fname;

     // Determine the file name to use
    if (args.length == 0) 
      throw new Exception("Usage: java Stupid file.stupid");
    else 
      fname = args[0];

    // Prepare for output.
    PrintWriter out = new PrintWriter(System.out, true);

    // Create the character stream that the tokenizer will  use.
    AdvCharStream acs =
      new AdvCharStream(
        new StandardCharStream(
          new BufferedReader(
            new FileReader(fname))));

    // Create the tokenizer
    StupidTokenizer tokenizer = new StupidTokenizer(acs);

    // Build the parse tree
    StupidParser parser = new StupidParser();
    Node tree = parser.parse(tokenizer);

    // Print the tree.
    out.println("+------------+----------------------------------");
    out.println("| Parse Tree |");
    out.println("+------------+");
    TreePrinter.print(tree, out);

    // Translate the program.
    InstructionSequence code = StupidTranslator.translate(tree);

    // Set up the computer.
    Computer hal = new Computer(10000);
    hal.setCode(code);

    // Print the translated program.
    out.println("");
    out.println("+----------+------------------------------------");
    out.println("| PAL Code |");
    out.println("+----------+");
    hal.dump(out);

    // Run the translated program.
    out.println("");
    out.println("+---------------+-------------------------------");
    out.println("| Executing ... |");
    out.println("+---------------+");
    hal.run(true);

    // That's it, we're done.
    System.exit(0);
  } // main(String[])
} // class Stupid

