1 # TODO: "console %f", xxx
    2 # the place where I normally find 0xffff after an expression is 0x0500 followed by the string "xxx"
    3 # This implies that the 0xffff is actually an indication of combination.
    4 # Need to read it before finishing an expression.
    5 
    6 import os, sys
    7 import struct
    8 from StringIO import StringIO
    9 import defunc
   10 
   11 # Syntax: decompile <file>
   12 
   13 # All these values are
   14 bitHeader = (317, 0xFFFFFFFFL)
   15 
   16 def PrintHelp():
   17     fileName = os.path.split(sys.argv[0])[-1]
   18     print fileName, "<filename>"
   19 
   20 def DecompileFile(fileName):
   21     try:
   22         f = open(fileName, 'rb')
   23     except IOError:
   24         PrintHelp()
   25         print "** File not found:", fileName
   26         sys.exit()
   27 
   28     try:
   29         v = struct.unpack("LL", f.read(8))
   30         if v == bitHeader:
   31             defunc.Parse(f)
   32         else:
   33             print "** Not an APE file:", fileName, hex(v)
   34     except:
   35         f.close()
   36         raise
   37 
   38     f.close()
   39 
   40 if __name__ == '__main__':
   41     if len(sys.argv) != 2:
   42         PrintHelp()
   43         sys.exit()
   44 
   45     arg = sys.argv[1]
   46     if arg == "--all":
   47         # Ensure the "ape\" directory exists.
   48         if os.access("ape", os.F_OK) != 1:
   49             print os.path.split(sys.argv[0])[-1] +": ape sub-directory not found.."
   50             sys.exit()
   51         # Ensure the "apes\" directory exists.
   52         if os.access("apes", os.F_OK) != 1:
   53             os.makedirs("apes")
   54 
   55         oldStdout = sys.stdout
   56         for fileName in os.listdir("ape"):
   57             if fileName.endswith(".ape"):
   58                 oldStdout.write(fileName +".. ")
   59                 # Install our own stdout replacement.
   60                 out = sys.stdout = StringIO()
   61                 # Decompile the file catching the output.
   62                 try:
   63                     DecompileFile("ape\\"+ fileName)
   64                 except:
   65                     print
   66                     print "#### ERROR ERROR ERROR ####"
   67                     oldStdout.write(out.getvalue())
   68                     raise
   69                 s = out.getvalue()
   70                 out.close()
   71                 oldStdout.write(".. %s\n" % len(s))
   72 
   73                 f = open("apes\\"+ fileName +"s", 'w')
   74                 f.write(s)
   75                 f.close()
   76         sys.stdout = oldStdout
   77     else:
   78         DecompileFile(arg)