#!/usr/bin/env python3
# simKernalLoad.py - simulate the C64 KERNAL serial LOAD store loop ($F4F3..$F524) for a PRG whose
# load address overlaps zero page, so the stored bytes redirect the load pointer ($AE/$AF) itself.
import sys
data = open(sys.argv[1], "rb").read()
lo, hi = data[0], data[1]
mem = bytearray(65536)
mem[0xAE] = lo
mem[0xAF] = hi
mem[0x93] = 0          # LOAD (not VERIFY)
mem[0x01] = 0x37
regions = []           # list of (startAddr, fileOffset, length)
curStart = None
verifyMode = False
for i, b in enumerate(data[2:]):
    ptr = mem[0xAE] | (mem[0xAF] << 8)
    if mem[0x93] != 0:
        if not verifyMode:
            print(f"  ** VERIFY mode entered at file offset {i+2:#06x}, ptr={ptr:04x}")
            verifyMode = True
    else:
        if curStart is None or ptr != curStart[0] + curStart[2]:
            if curStart: regions.append(curStart)
            curStart = [ptr, i+2, 0]
        mem[ptr] = b
        curStart[2] += 1
        if ptr == 0x01:
            print(f"  ** wrote {b:#04x} to $01 at file offset {i+2:#06x}")
    # INC $AE ; BNE ; INC $AF
    mem[0xAE] = (mem[0xAE] + 1) & 0xFF
    if mem[0xAE] == 0:
        mem[0xAF] = (mem[0xAF] + 1) & 0xFF
if curStart: regions.append(curStart)
for s, off, n in regions:
    print(f"file offset {off:#06x} -> ${s:04x}-${s+n-1:04x} ({n} bytes)")
print(f"final pointer ${mem[0xAE] | (mem[0xAF]<<8):04x}, $01={mem[0x01]:#04x}, $90={mem[0x90]:#04x}")
open(sys.argv[2], "wb").write(mem)
