#! /bin/tcsh -f

echo "**************************"
echo "*  start pileup_sum.csh  *"
echo "**************************"
date

cd $result_dir/
set det=$result_dir/$dir0/detection
cd $det/

setenv SAS_ODF $data_dir/$dir0
setenv SAS_CCF $data_dir/$dir0/ccf.cif

if ($pileup == "yes") then
 if ($DET == 1) then
   ftimgcalc a=A="$ExpDetectPrep"/ExpDetect_MOS1_Pileup_mask_"$b_tot".fits b=B="$ExpDetectPrep"/ExpDetect_MOS2_Pileup_mask_"$b_tot".fits expr="(A + B < 3. ? 0 : 1)" outfile="$ExpDetectPrep"/ExpDetect_Pileup_mask_"$b_tot".fits
    echo "OK: pileup mask sum done in energy band $b_tot"
 endif

 if ($DET == 01) then
    cp "$ExpDetectPrep"/ExpDetect_MOS1_Pileup_mask_"$b_tot".fits "$ExpDetectPrep"/ExpDetect_Pileup_mask_"$b_tot".fits
    echo "OK: pileup mask sum done in energy band $b_tot"
 endif

 if ($DET == 02) then
    cp "$ExpDetectPrep"/ExpDetect_MOS2_Pileup_mask_"$b_tot".fits "$ExpDetectPrep"/ExpDetect_Pileup_mask_"$b_tot".fits
    echo "OK: pileup mask sum done in energy band $b_tot"
 endif

 if ($DET == 03) then
    cp "$ExpDetectPrep"/ExpDetect_PN_Pileup_mask_"$b_tot".fits "$ExpDetectPrep"/ExpDetect_Pileup_mask_"$b_tot".fits
    echo "OK: pileup mask sum done in energy band $b_tot"
 endif
   
 if ($DET == 2) then
   ftimgcalc a=A="$ExpDetectPrep"/ExpDetect_MOS1_Pileup_mask_"$b_tot".fits b=B="$ExpDetectPrep"/ExpDetect_MOS2_Pileup_mask_"$b_tot".fits c=C="$ExpDetectPrep"/ExpDetect_PN_Pileup_mask_"$b_tot".fits expr="(A + B + C < 3. ? 0 : 1)" outfile="$ExpDetectPrep"/ExpDetect_Pileup_mask_"$b_tot".fits
    echo "OK: pileup mask sum done in energy band $b_tot"
 endif
else
 echo "the calculation of the sum of the pileup mask is not performed"
endif
cd $start_dir/

date
echo "stop pileup_sum.csh"
