import java.io.*;

public class TextDebugger extends Debugger {

	public TextDebugger() {
		super();
		Size = 0;
	}

	public void LoadProgram(String fn) {
		super.LoadProgram(fn);
		Size = (new CompiledProgram(fn)).Size();
	}

	public void Debug() {
		int c, n;

		for(;;) {
			System.out.println();
			DisplayStateStackInstructionAndFileRegisters();
			System.out.print(">");
			try {
				c = System.in.read();
			}
			catch(IOException e) {
				c = -1;
				System.out.println("IOException");
				return;
			}

			switch(c) {
				case 't' : Trace(); break;
				case 'd' : DisplayFileRegisters(); break;
				case 'q' : return;
				case 'b' : c = read(); n = ReadNumber();
						if((n == -1) || (c == 'd')) {
							DisplayBreakpoints();
							break;
						}
						if(IsBreakpoint(n))
							RemoveBreakpoint(n);
						else
							SetBreakpoint(n);
						break;
				case 'r' : Run(); break;
				case 'a' : Animate(); break;
				case 'u' : System.out.println(pic.FlashMemory().Display(Size)); break;
				default : break;
			}

			try {
				System.in.skip(1000);
			}
			catch(IOException e) {
				c = -1;
				System.out.println("IOException");
				return;
			}
		}
	}

	protected int ReadNumber() {
		int r = 0, c;
		String s = "0x0";
		for(;;) {
			c = read();
			if(c == -1) return -1;
			if(Character.isWhitespace((char)c)) {
//				System.out.println(s);
				return Integer.decode(s).intValue();
			}
			s += (char)c;
		}
	}

	protected int read() {
		int c;
		try {
			c = System.in.read();
		}
		catch(IOException e) {
			System.out.println("IOException");
			return -1;
		}
		return c;
	}

// Display methods
	public void DisplayFileRegisters() {
		String s[] = pic.FileRegisters().Display();
		int i;
		for(i = 0 ; i < s.length ; i++)
			System.out.print(s[i] + "\t");
		System.out.println();
	}

	public void DisplayFlash() {
		String s[] = pic.FlashMemory().Display();
		int i;
		for(i = 0 ; i < s.length ; i++)
			System.out.print(s[i] + "\t");
		System.out.println();
	}

	public void DisplayState() {
		String s[] = pic.DisplayState();
		int i;
		for(i = 0 ; i < s.length ; i++)
			System.out.println(s[i]);
	}

	public void DisplayInstruction() {
		System.out.println(pic.DisplayInstruction());
	}

	public void DisplayBreakpoints() {
		String s[] = pic.DisplayBreakpoints();
		int i;
		for(i = 0 ; i < s.length ; i++)
			System.out.println(s[i]);
	}

	protected int Size;
}