#!/usr/bin/env python3
"""Extract files from GENSE.FLD archive.

Format (little-endian):
  offset 0x00: 8 bytes  magic "FLDF0100"
  offset 0x08: u32      file count (e.g. 377)
  offset 0x0C: entries, 20 bytes each:
      [12] filename (NUL-padded, lowercase, e.g. "map_a1.cns")
      [ 4] u32 offset (absolute, from start of archive)
      [ 4] u32 size
  Body: raw payloads concatenated, starting at offset 0x0C + count*20.
"""
import os, struct, sys

def extract(src, dst):
    d = open(src, 'rb').read()
    assert d[:8] == b'FLDF0100', f'bad magic: {d[:8]!r}'
    n = struct.unpack('<I', d[8:12])[0]
    os.makedirs(dst, exist_ok=True)
    for i in range(n):
        e = d[12 + i*20: 12 + i*20 + 20]
        name = e[:12].split(b'\0', 1)[0].decode('latin1')
        off, size = struct.unpack('<II', e[12:20])
        with open(os.path.join(dst, name), 'wb') as f:
            f.write(d[off:off+size])
    print(f'extracted {n} files from {src} -> {dst}/')

if __name__ == '__main__':
    src = sys.argv[1] if len(sys.argv) > 1 else 'GENSE.FLD'
    dst = sys.argv[2] if len(sys.argv) > 2 else 'extract_fld'
    extract(src, dst)
