#!/usr/bin/env bash
# runInMameCyclesCalypsi.sh — cycle-bench a Calypsi raw binary.
# Loads <code.raw> at $1000 and jumps to <entry> (hex addr from
# Calypsi's --list-file, look for `__program_start = HHHHHH`).
# Markers and per-iter math identical to runInMameCycles.sh.

set -euo pipefail
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BIN="$1"
ENTRY="$2"
ITERS="${3:-100}"
CLOCK_HZ=1023000
SECS=8

LUA_PATH=$(mktemp --suffix=.lua)
trap 'rm -f "$LUA_PATH"' EXIT

LUA_BODY=$(cat <<LUA
local frame = 0
local loaded = false
local start_t = nil
local done_t = nil
emu.register_frame_done(function()
    frame = frame + 1
    local cpu = manager.machine.devices[":maincpu"]
    local mem = cpu.spaces["program"]
    if frame == 30 and not loaded then
        local f = io.open("__BIN__", "rb")
        if not f then print("BIN-MISSING"); manager.machine:exit(); return end
        local data = f:read("*all"); f:close()
        for i = 1, #data do
            local addr = 0x001000 + i - 1
            if not (addr >= 0x00C000 and addr < 0x00D000) then
                mem:write_u8(addr, data:byte(i))
            end
        end
        loaded = true
        cpu.state["PC"].value = 0x__ENTRY__
        cpu.state["PB"].value = 0x00
        cpu.state["DB"].value = 0x00
        cpu.state["D"].value  = 0x00
        cpu.state["P"].value  = 0x34
        cpu.state["E"].value  = 1
        cpu.state["S"].value  = 0x01FF
        print(string.format("MAME-LOADED bytes=%d entry=\$%04x", #data, 0x__ENTRY__))
        return
    end
    if not loaded then return end
    if not start_t and mem:read_u16(0x025000) == 0xa1a1 then
        start_t = emu.time()
    end
    if start_t and not done_t and mem:read_u16(0x025002) == 0xa2a2 then
        done_t = emu.time()
        local delta = done_t - start_t
        local cyc = delta * __CLOCK__
        local per_call = cyc / __ITERS__
        print(string.format("MAME-CYCLES iters=__ITERS__ delta_us=%.3f total_cyc=%.0f cyc_per_call=%.2f",
              delta * 1e6, cyc, per_call))
        manager.machine:exit()
    end
end)
LUA
)
LUA_BODY="${LUA_BODY//__BIN__/$BIN}"
LUA_BODY="${LUA_BODY//__ENTRY__/$ENTRY}"
LUA_BODY="${LUA_BODY//__CLOCK__/$CLOCK_HZ}"
LUA_BODY="${LUA_BODY//__ITERS__/$ITERS}"
printf '%s\n' "$LUA_BODY" > "$LUA_PATH"

OUT=$(SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy timeout 60 mame apple2gs \
    -rompath "$PROJECT_ROOT/tools/mame/roms" \
    -plugins -autoboot_script "$LUA_PATH" \
    -video none -sound none -nothrottle -seconds_to_run "$SECS" 2>&1 | grep "^MAME-")
echo "$OUT"
if echo "$OUT" | grep -q "MAME-CYCLES"; then exit 0; fi
exit 1
