import struct, os
from collections import Counter

SRC = '/home/aria/kellogg_remake/raw/PCKELL.DAT'
OUT = '/home/aria/kellogg_remake/extracted_dat'
os.makedirs(OUT, exist_ok=True)

with open(SRC, 'rb') as f:
    data = f.read()

num_entries = struct.unpack_from('<H', data, len(data)-4)[0] + 1
offset = struct.unpack_from('<i', data, len(data)-8)[0]
index_offset = offset

entries = []
for i in range(num_entries):
    name_len = struct.unpack_from('<H', data, offset)[0]
    offset += 2
    filename = data[offset:offset+name_len].decode('ascii', errors='replace')
    offset += name_len
    e_offset = struct.unpack_from('<i', data, offset)[0]
    offset += 4
    entries.append([filename, e_offset])

for i, e in enumerate(entries):
    length = (entries[i+1][1] if i+1 < len(entries) else index_offset) - e[1]
    e.append(length)

ext_counter = Counter()
for filename, e_offset, length in entries:
    payload = data[e_offset:e_offset+length]
    with open(os.path.join(OUT, filename), 'wb') as out:
        out.write(payload)
    ext = os.path.splitext(filename)[1].upper()
    ext_counter[ext] += 1

print('Extracted', len(entries), 'files to', OUT)
for ext, cnt in sorted(ext_counter.items()):
    print(ext, cnt)
