# -*- Mode: Python -*-

# blorb files are IFF
# just want a quick scan of what kind of stuff is in a blorb file.

import os.path
import struct
import sys

def u32 (f):
    n, = struct.unpack ('>L', f.read(4))
    return n

def u16 (f):
    n, = struct.unpack ('>H', f.read(2))
    return n

def four (f):
    return f.read(4)

def do (name, f):
    fun = globals()[name.decode ('ascii')]
    return fun (f)

def FORM (f):
    form_len = u32 (f)
    type_id = f.read(4)
    return do (type_id, f)

def IFRS (f):
    return do (four (f), f)

def RIdx (f):
    ridx_len = u32 (f)
    num = u32 (f)
    r = []
    for i in range (num):
        usage = four (f)
        number = u32 (f)
        start = u32 (f)
        r.append ((usage, number, start))
    return r

def IFZS (f):
    return do (four (f), f)

def IFhd (f):
    ch_len = u32 (f)
    what = four (f)
    import pdb; pdb.set_trace()

path = sys.argv[1]
base, ext = os.path.splitext (path)

f = open (path, 'rb')
l = do (four(f), f)

for kind, num, pos in l:
    if kind == b'Pict':
        f.seek (pos)
        kind = four (f)
        size = u32 (f)
        print (f' img: {kind} {size} bytes @{pos}')
    elif kind == b'Data':
        f.seek (pos)
        assert b'FORM' == four (f)
        data = FORM(f)
    elif kind == b'Exec':
        f.seek(pos)
        kind = four(f)
        size = u32 (f)
        print (f'exec: {kind} {size} bytes @{pos}')
        # extract the glul file
        o = open (base + '.glul', 'wb')
        o.write (f.read(size))
        o.close()
