#!/usr/bin/env bash
# Regenerate compare/ artifacts: for each *.c, produce both
# <name>.ours.s (our backend) and <name>.calypsi.lst (Calypsi listing).
# Run from the project root or anywhere; uses absolute paths.

set -eu

PROJECT_ROOT="/home/scott/claude/llvm816"
COMPARE_DIR="$PROJECT_ROOT/compare"
OUR_CLANG="$PROJECT_ROOT/tools/llvm-mos-build/bin/clang"
OUR_SYSROOT="$PROJECT_ROOT/runtime"
CALYPSI_CC="$PROJECT_ROOT/tools/calypsi/usr/local/lib/calypsi-65816-5.16/bin/cc65816"

OURS_FLAGS=(--target=w65816 --sysroot="$OUR_SYSROOT" -O2 -S)
# --64bit-doubles for fair FP comparison (Calypsi default is 32-bit doubles).
CALYPSI_FLAGS=(--speed -O 2 --64bit-doubles)

cd "$COMPARE_DIR"

for c in *.c; do
    base="${c%.c}"
    echo "build: $base"
    "$OUR_CLANG"   "${OURS_FLAGS[@]}"   "$c" -o "$base.ours.s"
    "$CALYPSI_CC" "${CALYPSI_FLAGS[@]}" "$c" -o "/tmp/$base.calypsi.elf" \
        --list-file "$base.calypsi.lst"
    rm -f "/tmp/$base.calypsi.elf"
done

# Per-file instruction-count summary.
printf '\n%-25s %8s %8s %8s\n' "test" "ours" "calypsi" "ratio"
printf '%-25s %8s %8s %8s\n' "----" "----" "-------" "-----"
for c in *.c; do
    base="${c%.c}"
    ours_n=$(grep -cE \
        '^\s+(lda|sta|jsl|jsr|adc|sbc|cmp|sec|clc|sep|rep|inc|dec|bra|brl|bcs|bcc|beq|bne|bmi|bpl|asl|lsr|rol|ror|stz|stx|sty|ldx|ldy|tax|txa|tay|tya|tsc|tcs|tdc|tcd|pha|pla|phx|plx|phy|ply|php|plp|pea|pei|rtl|rts|xba|xce|tsb|trb|bit|and|ora|eor|cop|brk|wai|stp|nop)\b' \
        "$base.ours.s" || true)
    cal_n=$(grep -cE '^\s+\\ [0-9a-f]+ [0-9a-f][0-9a-f]' "$base.calypsi.lst" || true)
    if [ "$cal_n" -gt 0 ]; then
        ratio=$(awk -v a="$ours_n" -v b="$cal_n" 'BEGIN{printf "%.2fx", a/b}')
    else
        ratio="n/a"
    fi
    printf '%-25s %8s %8s %8s\n' "$base" "$ours_n" "$cal_n" "$ratio"
done
