# -------------------------------
# Vitis HLS 2022 — end-to-end script
# ZCU102 (xczu9eg-ffvb1156-2-e) example
# Steps: C-sim → C-synth → Export RTL (IP)
# Exits on first error with message.
# -------------------------------

##### USER SETTINGS (edit these) #####
set PROJ_NAME     siso_test
set TOP_FUNC      siso              ;# your HLS top function name
set SRC_FILES     [list src/siso.cpp]
set TB_FILES      [list src/siso_tb.cpp]  ;# optional but recommended
set SOLUTION      sol1
set PART_NAME     xczu9eg-ffvb1156-2-e     ;# ZCU102; change to -2-i if you use industrial
set CLOCK_PERIOD  10.0                      ;# ns (5.0ns = 200 MHz)
# Optional args passed to the testbench main():
set CSIM_ARGV     {}                       ;# e.g. {1024 0}
# Export options:
set RTL_LANG      verilog                  ;# or vhdl
set EXPORT_DIR    export                ;# relative to project directory
#######################################

# ----- helpers -----
# ----- helpers -----
proc _ok {label}    { puts "OK: $label" }

proc _fail {label e} {
  puts stderr "FAIL: $label\n  Reason: $e"
  exit 1
}

proc run_step {label body} {
  puts "\n=== $label ==="
  if {[catch {uplevel 1 $body} err]} { _fail $label $err } else { _ok $label }
}


# Clean start: put everything under a fresh project
run_step "Create/Reset Project" {
  if {[file exists $PROJ_NAME]} { file delete -force $PROJ_NAME }
  open_project -reset $PROJ_NAME
  set_top $TOP_FUNC
  if {[llength $SRC_FILES] == 0} { error "No SRC_FILES specified." }
  add_files $SRC_FILES
  if {[llength $TB_FILES] > 0} { add_files -tb $TB_FILES }
}

# Create/Reset solution, set device/clock
run_step "Open Solution & Set Part/Clock" {
  open_solution -reset $SOLUTION
  set_part $PART_NAME
  create_clock -period $CLOCK_PERIOD -name default
}

# C Simulation (self-checking TB recommended)
#run_step "C Simulation" {
#  if {[llength $TB_FILES] == 0} {
#    puts "⚠️  No testbench files provided; skipping csim."
#  } else {
#    if {[llength $CSIM_ARGV] > 0} {
#      csim_design -O -clean -argv $CSIM_ARGV
#    } else {
#      csim_design -O -clean
#    }
#  }
#}

# C Synthesis
run_step "C Synthesis" {
  csynth_design
  # Optional: sanity check report exists
  set rpt "solution1/syn/report/${TOP_FUNC}_csynth.rpt"
  if {![file exists $rpt]} {
    # location varies with solution name; try dynamic path:
    set rpt [file join [pwd] $SOLUTION syn report "${TOP_FUNC}_csynth.rpt"]
  }
  if {![file exists $rpt]} { puts "ℹ️  csynth report not found (pathing may differ); continuing." }
}

# Export RTL as IP for Vivado/Vitis
run_step "Export RTL (IP Catalog)" {
  file mkdir $EXPORT_DIR
  export_design -format ip_catalog -rtl $RTL_LANG -output $EXPORT_DIR
}

puts "\n🎉 All steps completed successfully."
exit 0

