#-------------------------------------------------------------------------------
# Name:        Dungeon Keeper Gold Audio *.DAT
# Purpose:     Extract Archive
#
# Author:      Eric Van Hoven
#
# Created:     30/08/2017 
# Copyright:   (c) Eric Van Hoven 2017
# Licence:     MIT License
#-------------------------------------------------------------------------------

from inc_noesis import *


def registerNoesisTypes():
    handle = noesis.register("Dungeon Keeper Gold Audio", ".dat")
    noesis.setHandlerExtractArc(handle, datExtractArc)
    return 1

def datExtractArc(fileName, fileLen, justChecking):
    with open(fileName, "rb") as fs:
        if justChecking:
            return 1



        fs.seek(-0x4, 2)
        EOT = noeUnpack("<I", fs.read(4))[0]
        fs.seek(EOT, 0)
        fs.read(4) #uint 0
        check = noeUnpack("<I", fs.read(4))[0]

        if check == 0x1:
            fs.read(0xA) #first null skip
            fs.read(0x20) #0xFF skip

        else:
            fs.read(0x30) #0xFF skip

        SOT = (noeUnpack("<I", fs.read(4))[0]) + 0x20


        fs.seek(SOT, 0)

        while True:

            if SOT == EOT:
                break
            else:
                fileName = noeStrFromBytes(noeParseToZero(fs.read(0x12)))
                offset = noeUnpack("<I", fs.read(4))[0]
                fs.read(4) #uint 0
                size = noeUnpack("<I", fs.read(4))[0]
                SOT += 0x20
                fs.seek(offset, 0)
                print("Writing", fileName)
                rapi.exportArchiveFile(fileName, fs.read(size))
                fs.seek(SOT, 0)

    return 1







