#!/usr/bin/env python3
"""Dump the SFNT table directory and the cmap mappings of oob.ttf
to confirm maxp.numGlyphs is small and cmap glyph IDs are out of range."""
import struct, sys

path = sys.argv[1] if len(sys.argv) > 1 else "oob.ttf"
d = open(path, "rb").read()
print("sfnt version:", hex(struct.unpack(">I", d[:4])[0]))
nt = struct.unpack(">H", d[4:6])[0]
print("numTables:", nt)
for i in range(nt):
    off = 12 + i * 16
    tag = d[off:off+4].decode()
    cks, toff, tlen = struct.unpack(">III", d[off+4:off+16])
    print(f"  {tag}  off={toff:5d}  len={tlen:5d}")
    if tag == "maxp":
        ng = struct.unpack(">H", d[toff+4:toff+6])[0]
        print(f"    -> maxp.numGlyphs = {ng}")
    if tag == "cmap":
        sub_off = toff + struct.unpack(">I", d[toff+8:toff+12])[0]
        fmt, slen, lang, sc2 = struct.unpack(">HHHH", d[sub_off:sub_off+8])
        seg = sc2 // 2
        p = sub_off + 14
        ends   = struct.unpack(f">{seg}H", d[p:p+2*seg]); p += 2*seg + 2
        starts = struct.unpack(f">{seg}H", d[p:p+2*seg]); p += 2*seg
        deltas = struct.unpack(f">{seg}H", d[p:p+2*seg])
        for s, e, dl in zip(starts, ends, deltas):
            if s == 0xFFFF:
                break
            gid = (s + dl) & 0xFFFF
            print(f"    -> U+{s:04X} -> glyph {gid}")
