"""
    Author: 
    
    DeobfuscateGameBootstrap.py:
        Python script for deobfuscating System 2x6 game bootstraps
"""

import sys

def DeObfuscate(pInput, pOutput):

    inpOffset = 0
    outOffset = 0

    # Loop and deobfuscate.
    blockId = pInput[inpOffset]
    inpOffset += 1
    if blockId == 0:
        pass
        
    if blockId >= 2:
        print("block id: 0x%x" % blockId)
        while blockId != 0:
        
            pBlockPtr = inpOffset + 1
            while blockId >= 2:
            
                if (blockId & 1) == 1:
                
                    pOutput[outOffset] = pInput[inpOffset]
                    blockId = blockId >> 1
                    inpOffset = pBlockPtr
                    
                    pBlockPtr += 1
                    outOffset += 1
                    
                else:
                
                    a = pInput[inpOffset]
                    b = pInput[pBlockPtr]
                    
                    c = (a << 8) | b
                    d = c & 0x7FF
                    e = c >> 11
                    
                    if d == 0:
                        d = 0x800
                        
                    pCopyPtr = outOffset - d
                    
                    d = e & 0x1F
                    if d == 0:
                        d = 0x20
                        
                    inpOffset = pBlockPtr + 1
                    blockId = blockId >> 1
                    pBlockPtr += 2
                    
                    for i in range(d):
                        if outOffset >= len(pOutput) or pCopyPtr >= len(pOutput):
                            print("%d (%d) | %d (%d) | %d (%d)" % (outOffset, len(pOutput), pCopyPtr, len(pOutput), i, d))
                    
                        pOutput[outOffset] = pOutput[pCopyPtr]
                        pCopyPtr += 1
                        outOffset += 1
                    
            blockId = pInput[inpOffset]
            inpOffset = pBlockPtr
            
            print("block id: 0x%x" % blockId)
            
        print("bytes copied: %d" % outOffset)
        
    return outOffset


def main():

    # Open the input file and read the file into memory.
    f = open(sys.argv[1], 'rb')
    unk = f.read(4)
    inputData = f.read()
    f.close()
    
    # Deobfuscate the input buffer.
    outputData = bytearray(len(inputData) * 4)
    length = DeObfuscate(inputData, outputData)
    
    # Write the deobfuscated data to file.
    f = open(sys.argv[1] + "_dec", 'wb')
    f.write(outputData[0:length])
    f.close()
    
    
if __name__ == '__main__':
    main()
    