import struct
data=open("content/VIDEO/GEO/TSPHERE.BGF","rb").read()
# find SV_MATERIAL (0x2030) and 0x2031 strings, and any ascii material refs
def parse(p,end,depth=0):
    while p+3<=end:
        tw=struct.unpack_from("<H",data,p)[0]; p+=2
        cid=tw&0x2fff; lw=4 if(tw&0x8000)else(2 if(tw&0x4000)else 1)
        if p+lw>end:return
        ln=data[p] if lw==1 else(struct.unpack_from("<H",data,p)[0] if lw==2 else struct.unpack_from("<I",data,p)[0])
        p+=lw
        if p+ln>end:return
        if cid in (0x2030,0x2031,0x2008,0x11):
            s=data[p:p+ln]
            txt=''.join(chr(b) if 32<=b<127 else '.' for b in s)
            print(f"{'  '*depth}tag={hex(cid)} len={ln} str='{txt}'")
        if cid in {0x3,0x70,0x40,0x41,0x42,0x46,0x48,0x10,0x20,0x30}: parse(p,p+ln,depth+1)
        p+=ln
        if cid==0x5: break
parse(8,len(data))
# also list all ascii strings in the file
print("\n=== all ascii runs >=4 ===")
import re
for m in re.finditer(rb'[ -~]{4,}', data):
    print(" ",m.group().decode())
