#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
NMAX="${1:-20000}"
WORKDIR="${2:-$ROOT/work/exact_counts}"
THREADS="${OMP_NUM_THREADS:-$(nproc)}"
KMAX=$((NMAX / 2))

mkdir -p "$WORKDIR/residues" "$WORKDIR/output"
rm -f "$WORKDIR/residues"/*.txt "$WORKDIR/check_prime.txt"

g++ -O3 -march=native -mavx2 -fopenmp \
  "$ROOT/code/exact_counts/nimxor_walsh_avx2.cpp" \
  -o "$WORKDIR/nimxor_walsh_avx2"

while read -r modulus; do
  [[ -z "$modulus" ]] && continue
  OMP_NUM_THREADS="$THREADS" \
    "$WORKDIR/nimxor_walsh_avx2" \
    "$NMAX" "$modulus" "$WORKDIR/residues/$modulus.txt"
done < "$ROOT/code/exact_counts/moduli_example_17.txt"

python3 "$ROOT/code/exact_counts/reconstruct_exact_counts.py" \
  --residue-dir "$WORKDIR/residues" \
  --total-size-max "$NMAX" \
  --output-dir "$WORKDIR/output"

CHECK_PRIME="$(grep -v '^#' "$ROOT/code/exact_counts/check_prime.txt" | head -n 1)"
OMP_NUM_THREADS="$THREADS" \
  "$WORKDIR/nimxor_walsh_avx2" \
  "$NMAX" "$CHECK_PRIME" "$WORKDIR/check_prime.txt"

{
  python3 "$ROOT/code/exact_counts/verify_check_prime.py" \
    --counts "$WORKDIR/output/oeis_A048833_k0_k${KMAX}.txt" \
    --residue-file "$WORKDIR/check_prime.txt" \
    --prime "$CHECK_PRIME"

  if (( NMAX <= 20000 )); then
    python3 "$ROOT/code/exact_counts/compare_compact_counts.py" \
      --candidate "$WORKDIR/output/oeis_A048833_k0_k${KMAX}.txt" \
      --reference "$ROOT/data/counts/oeis_A048833_k0_k10000.txt" \
      --max-index "$KMAX"
  fi
} | tee "$WORKDIR/output/run_verification.txt"

printf 'Output written to %s\n' "$WORKDIR/output"
