#!/bin/bash
set -e

# E2E test for different crosstalk types
# Setup: Defocussed crab-like source ran with different crosstalk
#        mechanisms switched on
# Output: Histograms over N_XT and E_XT

# NOTE: running this script with the option -r runs it in reference mode,
# generating new reference data

# Reference simulation done with
# * Tool: sixtesim
# * SIXTE 3.2.0, commit 29e9f9a8185
# * SIMPUT 2.7.1, commit 4a44dc02ae9

### Setup
. ./data/scripts/setup/setup_e2e.sh

# get mode in which we're running
refmode=0
while getopts ":r" arg
do
  case "$arg" in
    r)
      refmode=1
  esac
done


if [ $refmode == 1 ]
then
  echo "Running in reference mode"
  output_dir=reference_output/
else
  echo "Running in test mode"
  output_dir=output/
fi

mkdir -p $output_dir

# Simulation parameters
xml_dir=${SIXTE_TESTDATA}/instruments/athena-xifu
xml=${xml_dir}/xifu_nofilt_defoc_20240605.xml
RA=0.00
Dec=0.00
###

fluxfac=100
let "exposure = 1000 / ${fluxfac}"
srcfile="${simput_dir}crab/mcrab_RA0.00Dec0.00.fits[SRC_CAT][col FLUX=FLUX*${fluxfac}, *]"

for xt_type in therm tdm_prop tdm_der all
do

  evtfile=evt_${xt_type}_xt.fits

  ### Simulation
  $SIXTE/bin/sixtesim \
    XMLFile=${xml} \
    RA=${RA} Dec=${Dec} \
    Exposure=${exposure} \
    Prefix=${output_dir} \
    Simput="${srcfile}" \
    EvtFile=${evtfile} \
    Background=y \
    doCrosstalk=${xt_type} \
    clobber=y \
    chatter=3 \
    Seed=1

  ./make_hists.sh ${output_dir}/${evtfile}

  rm ${output_dir}/${evtfile}

  if [ $refmode == 0 ]
  then
    ### compare to reference data
    echo "Comparing to reference files"
    refdata_dir=./data/refdata/e2e_athena-xifu_xttypes
    simdata_dir=${output_dir}

    for col in E_XT N_XT
    do
      ftdiff \
        infile1=${refdata_dir}/${evtfile}_${col} \
        infile2=${simdata_dir}/${evtfile}_${col}
    done
  fi

done

if [ $refmode == 0 ]
then
  # cleanup
  rm -rf ${output_dir}
fi

printf "\n%s executed successfully\n" "${0}"
exit 0
