#!/bin/bash
set -e

# E2E test for point sources with Crab-like spectra with X-IFU 
# Setup: Scale exposure time inverse to flux, 1 ks for 1 mcrab
# Output: Histograms over GRADING, N_XT, 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_infoc_20240605.xml
RA=0.00
Dec=0.00
###

for fluxfac in 1 10 100
do
  let "exposure = 1000 / ${fluxfac}"

  srcfile="${simput_dir}crab/mcrab_RA0.00Dec0.00.fits[SRC_CAT][col FLUX=FLUX*${fluxfac}, *]"
  
  evtfile=evt_${fluxfac}.fits

  ### Simulation
  $SIXTE/bin/sixtesim \
    XMLFile=${xml} \
    RA=${RA} Dec=${Dec} \
    Exposure=${exposure} \
    Prefix=${output_dir} \
    Simput="${srcfile}" \
    EvtFile=${evtfile} \
    Background=y \
    doCrosstalk=all \
    clobber=y \
    chatter=0 \
    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_fluxscale
    simdata_dir=${output_dir}

    for col in E_XT N_XT GRADING
    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
