import dedenc, os, wave

class Bank:
    def __init__(self):
        self.size = 16384
        self.list = []
    def insert(self, item, len):
        if len > self.size: return False
        else:
            self.size = self.size - len
            self.list.append(item)
            return True

def tcase(a):
    return a[0].upper() + a[1:]

dedpath = os.getcwd() + "/audio/ded/"
print("Generating all DEDs in {}...".format(dedpath))
filelist = os.listdir(dedpath)
lenlist = {}
for filename in filelist:
    if filename[-4:].lower() == ".wav":
        fl = wave.open(dedpath+filename, "rb")
        nf = fl.getnframes()
        ous = dedenc.wavtoded(fl.readframes(nf), fl.getframerate(), fl.getnchannels(), fl.getsampwidth())
        fl.close()
        lenlist[filename[:-4]] = len(ous)
        ouf = open(dedpath+filename[:-4]+".ded", "wb")
        ouf.write(ous)
        ouf.close()
        
banklist = [Bank()]
inpfile = sorted(lenlist, cmp=lambda x,y: cmp(lenlist[y], lenlist[x]))
while len(inpfile) > 0:
    inserted = False
    item = inpfile.pop(0)
    for i in banklist:
        inserted = i.insert(item, lenlist[item])
        if inserted: break
    if not inserted:
        newbank = Bank()
        inserted = newbank.insert(item, lenlist[item])
        if not inserted:
            raise OverflowError("{}'s cry is too big to fit in one bank.".format(tcase(item)))
        banklist.append(newbank)
listfile = open(dedpath+"files.asm","w")
listfile.write("; Auto-generated by dedgen.py\n")
seccount = 0
for i in banklist:
    seccount = seccount + 1
    listfile.write('\nSECTION "DED {0}", ROMX, BANK[DED_{0}]\n\n'.format(seccount))
    for j in i.list:
        listfile.write('{}DEDData:: INCBIN "audio/ded/{}.ded"\n'.format(tcase(j), j))
listfile.close()
print("{} DEDs generated and packed into {} banks.".format(len(lenlist), seccount))
