import io
data = open(r"C:/Users/vikto/Documents/Claude/rt-4d/radio-spi-dump.bin","rb").read()
out=io.open(r"C:/Users/vikto/Documents/Claude/rt-4d/analyze/out12.txt","w",encoding="utf-8")

def render(off):
    lines=[]
    for r in range(16):
        line=""
        for cb in range(2):
            b=data[off+r*2+cb]
            for bit in range(8):
                line += "#" if (b>>bit)&1 else "."
        lines.append(line)
    return lines

# find best global alignment offset (0..31) that maximizes clean glyphs across 0x198000..0x242000
# metric: fraction of glyphs whose first & last rows are blank-ish and have connected mass
import statistics
def glyph_score(off):
    g=data[off:off+32]
    if all(b==0 for b in g) or all(b==0xff for b in g): return None
    rows=[(g[2*r]|(g[2*r+1]<<8)) for r in range(16)]
    setbits=sum(bin(x).count('1') for x in rows)
    if setbits<8 or setbits>200: return 0
    # top & bottom rows mostly empty is typical
    edge = (bin(rows[0]).count('1')<=3) + (bin(rows[15]).count('1')<=3)
    return edge

best=None
for align in range(0,32,2):
    base=0x198000+0x4000+align  # start well past pinyin table
    scores=[]
    for g in range(2000):
        off=base+g*32
        s=glyph_score(off)
        if s is not None: scores.append(s)
    if scores:
        avg=sum(scores)/len(scores)
        if best is None or avg>best[1]:
            best=(align,avg)
out.write("best align offset within 32: %r\n"%(best,))

# count non-empty 32-byte glyph cells in whole region for a glyph-count estimate
region=data[0x19c000:0x242000]
ng=len(region)//32
nonempty=0
for g in range(ng):
    cell=region[g*32:g*32+32]
    if any(b not in (0,0xff) for b in cell): nonempty+=1
out.write("region 0x19c000-0x242000: %d 32-byte cells, %d non-empty (~glyphs)\n"%(ng,nonempty))
out.write("A GB2312 full font would be ~7000-8000 glyphs.\n")
out.close()
print("done")
