#!/usr/bin/python

from subprocess import Popen, PIPE
import sys, code, readline, re, struct, traceback

class DisasmConsole(code.InteractiveConsole):
  def __init__(self, local=None, filename="<console>"):
    code.InteractiveConsole.__init__(self, local, filename)
    readline.parse_and_bind("tab: complete")

  def push(self, line):
    if "quit" in line:
      sys.exit(0)
    lines = re.sub("[^0-9a-fA-Fx ]", "", line).rstrip().split(" ")
    if len(lines) < 1 or not sum(map(lambda x:len(x), lines))/len(lines) == 2 or re.search("^[0-9a-fA-F\\n ]+$", line) == None:
      print "Error: Invalid Syntax"
      return
    try:
      open("/tmp/temp.disasm", "w").write("".join(map(lambda x:struct.pack("B", x), map(lambda x: int(x, 16), lines))))
      p = Popen(["ndisasm", "-b", "32", "/tmp/temp.disasm"], stdout=PIPE)
      while 1:
        l = p.stdout.readline()
        if not l:
          break
        print l.rstrip()
      p.wait()
    except:
      print "Unknown Error(is syntax ok?)"
      print traceback.format_exc()
      print lines
      return
disasm_console = DisasmConsole()
sys.ps1 = "(disasm) >>> "
sys.ps2 = "--------> "
disasm_console.interact("### Welcome to DisAssembler Console ###")
