#!/usr/bin/env python
# -*- coding: utf_8 -*-


import struct
import os



path_BaseDirectory = "J:\\GITSU\\"
unpack_file = "D:\\Program Files (x86)\\Nexon\\gits\\appdata\\Data\\worldEnv.dat"

print ("Directory:  "+path_BaseDirectory)

r_bytes = [0, 0, 0, 0, 0, 0, 0, 0]
r_bytes_l = [0xDD, 0x88, 0x55, 0x22, 0x14, 0, 0, 0]

dat_file = open(unpack_file, 'rb')

dat_file.seek(0,os.SEEK_END)
dat_file_size=dat_file.tell()
dat_file.seek(0,os.SEEK_SET)

file_name = ""
previouse_offset = 0

print  ("dat_file_size: " + str(dat_file_size))

while ( dat_file.tell() <  dat_file_size):

    if (r_bytes == r_bytes_l):
        back_offset = dat_file.tell()
        dat_file.seek(0x12,os.SEEK_CUR)
        file_name_size = struct.unpack('I', dat_file.read(4))[0]
        if (file_name_size < 0xFF):
            if (file_name != "") : ##читаем файл
                back_offset2 = dat_file.tell()
                (dirName, fileName) = os.path.split(path_BaseDirectory + file_name)
                if ((os.path.exists(dirName) ) == False):
                    os.makedirs(dirName)
                file_size = back_offset - 8 - previouse_offset
                dat_file.seek(previouse_offset,os.SEEK_SET)
                byte_data=dat_file.read(file_size)
                Ufile = open((path_BaseDirectory + file_name), 'wb')
                Ufile.write(byte_data)
                Ufile.close()
                dat_file.seek(back_offset2,os.SEEK_SET)
            file_name =   dat_file.read(file_name_size)
            print("File discriptor offset: " + str(back_offset - 8) + " " +file_name)
            previouse_offset = dat_file.tell()
            r_bytes = [0, 0, 0, 0, 0, 0, 0, 0]
        else:
            dat_file.seek(back_offset,os.SEEK_SET)
    else:
        i = 0
        while (i < 7) :
            r_bytes[i] = r_bytes[i+1]
            i += 1
        r_bytes[7] = file_name_size = struct.unpack('B', dat_file.read(1))[0]
       ## print(r_bytes)



back_offset = dat_file.tell()
(dirName, fileName) = os.path.split(path_BaseDirectory + file_name)
if ((os.path.exists(dirName) ) == False):
    os.makedirs(dirName)
file_size = back_offset - previouse_offset
dat_file.seek(previouse_offset,os.SEEK_SET)
byte_data=dat_file.read(file_size)
Ufile = open((path_BaseDirectory + file_name), 'wb')
Ufile.write(byte_data)
Ufile.close()










