#!/usr/bin/python

#
# dis_prettify.py
# Author: Lars Thomas Denstad <larsde@redloop.com>
#
# This is a small utility to beautify
# disassembly output from VP-code.
#
# Best result if you use:
#
# $ dis -a -s source.00 | dis_prettify.py
#
# History
#     2000-10-21 - larsde - created
#     2000-10-22 - larsde - extended tag-match
#
# License
#     dis_prettify.py is released under
#     GNU GPL version 2.0 or newer.
#

import fileinput, re, string

source = []
tagnames = {}
qcalls = {}

re_tag = re.compile(r"^(?P<tagname>[0-9_]*[a-zA-Z0-9_]*):")
re_qcall = re.compile(r"\s*__tmp:=savetextq __qcall_q, (?P<num>.*)(?P<flags>[0-9][0-9]), (?P<call>.*)")
re_dcb = re.compile(r"""\s*dc.b ['"](?P<data>.*?)["']""") 

for line in fileinput.input():
    line = line[:len(line)-1]
    source.append(line)

current_tag = ""

for l in source:

    if current_tag != "":
        m = re_dcb.match(l)
        if m != None:
            tmp = m.group('data')
            tmp = string.replace(tmp, " ", "_")
            tmp = string.replace(tmp, ":", "")
            tmp = string.replace(tmp, ".", "")
            tmp = string.replace(tmp, ";", "")
            tagnames[current_tag] = current_tag + '_' + tmp
        current_tag = ""
    
    m = re_qcall.match(l)
    if m != None:
        qcalls[m.group('num')] = [m.group('call'), m.group('flags')]
    
    m = re_tag.match(l)
    if m != None:
        current_tag = m.group(1)

# That was collection, now to do some replacements

for l in source:
    tmpline = l
    for call in qcalls.keys():
        original = "qcl " + call
        new = "qcall " + qcalls[call][0]
        tmpline = string.replace(tmpline, original, new)
    if (string.find(tmpline, "ccl ")) != -1:
        for call in qcalls.keys():
            original = "arh " + call
            new = qcalls[call][0]
            tmpline = string.replace(tmpline, original, new)
            tmpline = string.replace(tmpline, "ccl ", "ncall ")
            tmpline = string.replace(tmpline, "(ld.p [", "")
            tmpline = string.replace(tmpline, "+$00])", "")
    
    for tag in tagnames.keys():
        if (string.find(tmpline, ";tag")) == -1 and (string.find(tmpline, tag)) != -1:
            tmpline = tmpline + " ; " + tagnames[tag]
            break
        tmppatt = tag[0:len(tag)-1]
        if (string.find(tmpline, " " + tag)) > 0:
            tmpline = tmpline + " ; " + tagnames[tag]
            break
        

    print tmpline

