import os, sys, subprocess

#(16*16)+8=264
def get_titleid_from_encrypted_rom(file):
    with open(file, "rb") as f:
        f.seek(264)
        titleid = ""
        for x in range(0, 8):
            titleid = f.read(1).encode("hex") + titleid #Reverse
        return titleid.upper()

def get_titleid_from_id(id):
    for child in root:
        if (child.find('id').text == id):
            return child.find('titleid').text

for file in os.listdir("../Encrypted"):
    if file.endswith(".3ds") or file.endswith(".3DS"):
        titleid = get_titleid_from_encrypted_rom("../Encrypted/" + file)
        if (os.path.isfile("../Encrypted/" + file)==False or os.path.isfile("./xorpad/" + titleid + ".Main.exheader.xorpad")==False or os.path.isfile("./xorpad/" + titleid + ".Main.exefs_norm.xorpad")==False or os.path.isfile("./xorpad/" + titleid + ".Main.romfs.xorpad")==False):
            print "Error: xorpad not found for " + file


for file in os.listdir("../Encrypted"):
    if file.endswith(".3ds") or file.endswith(".3DS"):
        titleid = get_titleid_from_encrypted_rom("../Encrypted/" + file)
        FNULL = open(os.devnull, 'w')    #use this if you want to suppress output to stdout from the subprocess
        args = './xorer.exe "' + os.path.abspath("../Encrypted/" + file) + '" -e "' + os.path.abspath("./xorpad/" + titleid + ".Main.exheader.xorpad") + '" -x "' + os.path.abspath("./xorpad/" + titleid + ".Main.exefs_norm.xorpad") + '" -7 "' + os.path.abspath("./xorpad/" + titleid + ".Main.exefs_7x.xorpad") + '" -r "' + os.path.abspath("./xorpad/" + titleid + ".Main.romfs.xorpad") + '" -o "' + os.path.abspath("../Decrypted/" + file[:-4] + " Decrypted.3ds") + '"'
        print args
        subprocess.call(args, stdout=FNULL, stderr=FNULL, shell=False)
        sys.argv[1:] = []

