#!/bin/sh
# Stage D gate: Linas's recorded parses (A then C) -> count -> csetmarg must reproduce G0's state-D marginals
# exactly, and the check must FAIL on three broken inputs. Usage: check_d.sh <g0-run-dir> <scratch-dir>
set -e
cd "$(dirname "$0")"
R=$1; S=$2
gcc -O2 -o count count.c 2>/dev/null; gcc -O2 -o csetmarg csetmarg.c -lm 2>/dev/null
./count "$R/parses-A.tsv" "$R/parses-C.tsv" > "$S/d-counts.tsv"
python3 diffstate.py --counts-only "$R/state-C.tsv" "$S/d-counts.tsv" | head -1
./csetmarg "$S/d-counts.tsv" > "$S/d-ours.tsv"
python3 diffd.py "$R/state-D.tsv" "$S/d-ours.tsv" | head -1
echo "MATCH: PASS"
grep '^(Section ' "$S/d-counts.tsv" > "$S/d-sect.tsv"
sed '100d' "$S/d-sect.tsv" > "$S/m-drop.tsv"
awk -F'\t' 'BEGIN{OFS="\t"} NR==200{split($3,v," "); v[3]+=1; $3=v[1]" "v[2]" "v[3]} {print}' "$S/d-sect.tsv" > "$S/m-bump.tsv"
awk -F'\t' 'BEGIN{OFS="\t"} NR==300{sub(/^\(Section \(WordNode "[^"]*"\)/, "(Section (WordNode \"the\")", $1)} {print}' "$S/d-sect.tsv" > "$S/m-move.tsv"
for m in drop bump move; do
./csetmarg "$S/m-$m.tsv" > "$S/m-$m.out"
if python3 diffd.py "$R/state-D.tsv" "$S/m-$m.out" > "$S/m-$m.diff"; then echo "MUTATION $m: NOT CAUGHT"; exit 1; fi
echo "MUTATION $m: caught — $(head -1 "$S/m-$m.diff")"
done