#! /bin/tcsh -f

echo "******************************"
echo "*  start barycenter_evt.csh  *"
echo "******************************"
date


set ENERGY_FILTER="(PI in [200:12000])"
set att1=`ls $data_dir/$dir0/*AttHk*`
set att1_ctrl=`ls $data_dir/$dir0/*AttHk* | wc -l | awk '{print $1}'`
if ( $att1_ctrl == 1 ) then
 echo "OK: the attitude file $att1 exists"
 echo "Start to create Global Hk file"
 tabgtigen expression="\!isNull(DAHFPNT) && DAHFPNT < 3.0/60.0" gtiset="$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits postfraction=0 prefraction=0 table="$att1":ATTHK -w "$warn" -V "$verb"
 set GTI_FILTER="GTI(${data_dir}/${dir0}/${dir0}_GlobalHK-Attitude_GTI.fits, TIME)"
 chmod 766 "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits
else
 echo "ERROR: the attitude file $att1 does not exist"
 echo "ERROR: the attitude file $att1 does not exist" >> $log_dir/messages.log
endif

echo ""
echo "Starting to filter the $data_dir/$dir0/$ev2 with the selection: ${GTI_FILTER} && ${ENERGY_FILTER}..."
echo ""
echo "/usr/bin/time -p evselect expression='${GTI_FILTER} && ${ENERGY_FILTER}' filteredset=${data_dir}/${dir0}/raw.ds table=${data_dir}/${dir0}/${ev2}:EVENTS updateexposure=true withfilteredset=Y -w "$warn" -V "$verb"" > ${data_dir}/${dir0}/filt.csh
source ${data_dir}/${dir0}/filt.csh
rm ${data_dir}/${dir0}/filt.csh

echo ""
echo "Starting to barycenter the $data_dir/$dir0/${ev2}..."
echo ""
echo "barycen withtable=yes table=${data_dir}/${dir0}/raw.ds:EVENTS processgtis=yes processexposutables=yes ephemeris=DE405 -w ${warn}" > ${data_dir}/${dir0}/bary.csh
source ${data_dir}/${dir0}/bary.csh
rm ${data_dir}/${dir0}/bary.csh

if (-e ${data_dir}/${dir0}/raw.ds) then
 cp ${data_dir}/${dir0}/raw.ds ${data_dir}/${dir0}/${ev2}
 rm ${data_dir}/${dir0}/raw.ds
endif
