# NOTE: On some systems, you may need:
#   export LD_PRELOAD=/usr/lib64/libtinfo.so.5
# before running this script.

# xsim_run.tcl - Vivado xsim compilation and simulation script for PolyMul
#
# Compiles all PolyMul RTL sources plus dependencies, then testbench,
# and runs simulation.
# Run from the project root: ~/Dev/mlkem/
#
# Prerequisites:
#   source /opt/Xilinx/Vivado/2019.2/settings64.sh
#
# Usage examples:
#   # Run poly_mul_sync testbench
#   xsim poly_mul_sim -R
#
#   # Step-by-step:
#   vivado -mode batch -source xsim_run.tcl

# ================================================================
# Configuration
# ================================================================
set NTT_DIR    sync_rtl/ntt
set PM_DIR     sync_rtl/poly_mul
set TB_DIR     sync_rtl/poly_mul/TB

# ================================================================
# Step 1: Compile dependency sources (ntt/barrett_mul)
# ================================================================
puts "=== Compiling RTL dependencies ==="

# Barrett modular multiplier (shared dependency from ntt/)
xvlog -sv ${NTT_DIR}/barrett_mul.v

# ================================================================
# Step 2: Compile PolyMul sources
# ================================================================
puts "=== Compiling PolyMul RTL sources ==="

# Basecase multiplier (instantiates barrett_mul)
xvlog -sv ${PM_DIR}/basecase_mul.v

# PolyMul zeta ROM
xvlog -sv ${PM_DIR}/poly_mul_zeta_rom.v

# PolyMul sync top (instantiates basecase_mul + poly_mul_zeta_rom)
xvlog -sv ${PM_DIR}/poly_mul_sync.v

# ================================================================
# Step 3: Compile testbench
# ================================================================
puts "=== Compiling testbench ==="

# File-based vector testbench for poly_mul_sync
xvlog -sv ${TB_DIR}/tb_poly_mul_xsim.v

# ================================================================
# Step 4: Elaborate (xelab)
# ================================================================
puts "=== Elaborating snapshot ==="

xelab tb_poly_mul_xsim -s poly_mul_sim --timescale 1ns/1ps

# ================================================================
# Step 5: Run simulation
# ================================================================
puts ""
puts "=== Running poly_mul_sync test ==="
xsim poly_mul_sim -R

puts ""
puts "=== Simulation complete ==="
