#!/usr/bin/env python3
# dumpSectors.py - split a D64 image into per-track raw sector dumps and report allocation.
import sys, os

SECTORS_PER_TRACK = [21]*17 + [19]*7 + [18]*6 + [17]*5   # tracks 1..35

def trackOffset(track):
    return sum(SECTORS_PER_TRACK[:track-1]) * 256

def main():
    img  = open(sys.argv[1], "rb").read()
    outDir = sys.argv[2]
    os.makedirs(outDir, exist_ok=True)
    bam = img[trackOffset(18):trackOffset(18)+256]
    report = []
    for track in range(1, 36):
        nSec  = SECTORS_PER_TRACK[track-1]
        base  = trackOffset(track)
        data  = img[base:base+nSec*256]
        open(f"{outDir}/track{track:02d}.bin", "wb").write(data)
        entry = bam[4+(track-1)*4 : 4+(track-1)*4+4]
        freeCount = entry[0]
        bits = entry[1] | (entry[2]<<8) | (entry[3]<<16)
        used = [s for s in range(nSec) if not (bits >> s) & 1]
        nonZero = [s for s in range(nSec) if any(data[s*256:(s+1)*256])]
        report.append(f"track {track:2d}: free={freeCount:2d} usedSectors={len(used):2d} nonZeroSectors={len(nonZero):2d} used={used}")
        for s in range(nSec):
            open(f"{outDir}/t{track:02d}s{s:02d}.bin", "wb").write(data[s*256:(s+1)*256])
    open(f"{outDir}/allocation.txt", "w").write("\n".join(report) + "\n")
    print("\n".join(report))
    # disk name and id from BAM
    print("disk name:", bam[0x90:0xA0], "id:", bam[0xA2:0xA4], "dos:", bam[0xA5:0xA7])

main()
