#! /bin/tcsh -f

echo "******************************"
echo "*  start spectra_target.csh  *"
echo "******************************"
date

setenv SAS_ODF ${data_dir}/${dir0}
setenv SAS_CCF ${data_dir}/${dir0}/ccf.cif
cifinsert calindexset=${data_dir}/${dir0}/ccf.cif sets=${SAS_CCFPATH}/EMOS1_CONTAMINATION_0001.CCF
cifinsert calindexset=${data_dir}/${dir0}/ccf.cif sets=${SAS_CCFPATH}/EMOS2_CONTAMINATION_0001.CCF
   set attitude=`ls $pps_archive_dir/$dir0/pps/*ATT*`
   set attitude_ctrl=`ls $pps_archive_dir/$dir0/pps/*ATT* | wc -l | awk '{print $1}'`
   if ($attitude_ctrl == 1 ) then
    set rev=`ftlist $attitude+0 K | grep "REVOLUT =" | sed -e "s/'/ /g"  | cut -d' ' -f4 | awk '{print $1}'`
   endif
echo "bash ${progr_dir}/asc_sum.sh ${dir0} ${data_dir}/${dir0} ${data_dir}/${dir0} ${pps_archive_dir}/${dir0}/pps ${ref} ${ros_asc_dir} ${att1} ${rev}" > ${data_dir}/${dir0}/asc_sum.csh
source ${data_dir}/${dir0}/asc_sum.csh
rm ${data_dir}/${dir0}/asc_sum.csh

if ( -r ${result_dir}/${dir0}/spectra_target) then
 echo "OK SPECTRA_TARGET DIR EXISTS"
else
 echo "MAKE SPECTRA_TARGET DIR"
 mkdir ${result_dir}/${dir0}/spectra_target
endif

set spec_dir = ${result_dir}/${dir0}/spectra_target 
set proc = $result_dir/$dir0/processed
#rm ${spec_dir}/*.ds
#rm ${spec_dir}/*.pha
cd ${spec_dir}/

if ( $DET == 1 || $DET == 01 || $DET == 02) then
cd ${data_dir}/${dir0}/
 rm list_M1.txt
 rm list_M2.txt
 rm list_M.txt
 set evS1 = `ls *MOS1_S*_ImagingEvts.ds*`
 set evS2 = `ls *MOS2_S*_ImagingEvts.ds*`
 set evU1 = `ls *MOS1_U*_ImagingEvts.ds*`
 set evU2 = `ls *MOS2_U*_ImagingEvts.ds*`

 set nS1 = `echo $evS1 | wc -l | awk '{print $1}'`
 set nS2 = `echo $evS2 | wc -l | awk '{print $1}'`
 set nU1 = `echo $evU1 | wc -l | awk '{print $1}'`
 set nU2 = `echo $evU2 | wc -l | awk '{print $1}'`
 if ($nS1 != 0) then
  echo "$evS1" >> list_M1.txt
  echo "$evS1" >> list_M.txt
 endif
 if ($nU1 != 0) then
  echo "$evU1" >> list_M1.txt
  echo "$evU1" >> list_M.txt
 endif
 if ($nS2 != 0) then
  echo "$evS2" >> list_M2.txt
  echo "$evS2" >> list_M.txt
 endif
 if ($nU2 != 0) then
  echo "$evU2" >> list_M2.txt
  echo "$evU2" >> list_M.txt
 endif

 cd ${spec_dir}/
 set exprEN="#XMMEA_EM&&(TIME >= 425069359.715)&&(TIME <= 425069674.854)"
# set exprEN="#XMMEA_EM"
# set exprEN="#XMMEA_EM&&(FLAG==0)"
 set Nflare = 1
 foreach ev (`cat ${data_dir}/${dir0}/list_M.txt`)
  if ( -e ${data_dir}/${dir0}/${ev} ) then
   set obsevt="${dir0}"
   set str=`echo ${ev} | cut -c 17-21`
   set str1=`echo ${ev} | cut -c 23-26`
   fkeypar ${data_dir}/${dir0}/${ev}+1 DATE-OBS
   set date = `pget fkeypar.par value`
   set date_obs=`echo ${date} | cut -c 2-11`
   if ($filter1 == "SP") then
    echo "evt file SP cleaned"
    set flarefile=`awk -v nr=$Nflare '{ if (NR == nr) print $1}' $proc/list_GTI_Flare.txt`
    if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
     echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME) && GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
     source $spec_dir/filt.csh
     rm $spec_dir/filt.csh
     echo "ATTENTION: The Soft Protons cleaned analysis is selected"
     echo "           It is filtered with Global HK Attitude GTI"
     echo "           It is filtered with GTI from EPIC flare background timeseries"
    else
     echo "/usr/bin/time -p evselect expression='GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
     source $spec_dir/filt.csh
     rm $spec_dir/filt.csh
     echo "ATTENTION: The Soft Protons cleaned analysis is selected"
     echo "           It is filtered with GTI from EPIC flare background timeseries"
    endif
   else
    echo "evt file not SP cleaned"
    if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
      echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh 
      source $spec_dir/filt.csh
      rm $spec_dir/filt.csh
      echo "ATTENTION: The Soft Protons not cleaned analysis is selected"
      echo "           It is filtered with Global HK Attitude GTI"
    else
      echo "ATTENTION: No filter is selected"
      cp ${data_dir}/${dir0}/${ev} ${spec_dir}/
    endif
   endif

   if ($spec_baryecentered == "yes") then
    echo ""
    echo "Starting to barycentered the file ${ev}..."
    echo ""
    echo "barycen withtable=yes table=${spec_dir}/${ev}:EVENTS timecolumn=TIME withsrccoordinates=no srcra=${target_RA} srcdec=${target_DEC} processgtis=yes processexposutables=yes time=0 ephemeris=DE405 -w ${warn}" > ${spec_dir}/bary.csh
    source ${spec_dir}/bary.csh
    rm ${spec_dir}/bary.csh
   else
    echo "Using event file not barycentered..."
   endif

#SRC
   echo ""
   echo "Starting to calculate the ${target_name} spectrum..."
   set filt = "${dir0}_src_${str}_${str1}_${date_obs}.ds"
   set src = "${dir0}_src_${str}_${str1}_${date_obs}.pha"
   set bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.pha"
   set filt_bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.ds"
   set arf = "${dir0}_arf_${str}_${str1}_${date_obs}.ds"
   set rmf = "${dir0}_rmf_${str}_${str1}_${date_obs}.ds"
   set X_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFXCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set Y_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFYCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set target_X = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set target_Y = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of ${target_name} (RA,Dec): ${target_RA} ${target_DEC}" 
   echo "direction of ${target_name} (X,Y): ${target_X} ${target_Y}"
   echo "radius of circle around ${target_name}: ${radius_spec_src}"
   echo ""

   echo "#! /bin/tcsh -f" > $spec_dir/src.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=12)&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
  # echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&(PATTERN<=12)&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
   source $spec_dir/src.csh
   rm $spec_dir/src.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${src} useodfatt=no
   echo "${src} done !"
   echo ""

#BKG
   echo ""
   echo "Starting to calculate the ${target_name} background..."
   if ($bkg_spec_pos == "no") then
    if ( ${str} == "EMOS1" ) then
     set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg_M1.txt | awk '{print $1}'`
     set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg_M1.txt | awk '{print $2}'`
    endif
    if ( ${str} == "EMOS2" ) then
     set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg_M2.txt | awk '{print $1}'`
     set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg_M2.txt | awk '{print $2}'`
    endif 
    #set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $1}'`
    #set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $2}'`
   endif
   set bkg_X = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set bkg_Y = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of background circle around ${target_name} (RA,Dec): ${bkg_RA} ${bkg_DEC}" 
   echo "direction of background circle around ${target_name} (X,Y): ${bkg_X} ${bkg_Y}"
   echo "radius of the background circle around ${target_name}: ${radius_spec_bkg}"
   echo ""
    
   echo "#! /bin/tcsh -f" > $spec_dir/bkg.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=12)&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
  # echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&(PATTERN<=12)&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
   source $spec_dir/bkg.csh
   rm $spec_dir/bkg.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${bkg} useodfatt=no
   echo "${bkg} done !"
   echo ""

#RMF ARF
    
   echo ""
   echo "Starting to calculate the rmf..."
   echo ""
   rmfgen spectrumset=${spec_dir}/${src} rmfset=${spec_dir}/${rmf}
   echo "${rmf}!"
   echo ""
   
   echo ""
   echo "Starting to calculate the arf..."
   echo ""
   arfgen spectrumset=${spec_dir}/${src} detmaptype=psf arfset=${spec_dir}/${arf} withrmfset=yes rmfset=${spec_dir}/${rmf} useodfatt=no
   echo "${arf} !"
   echo ""

#GRPPHA
    
   echo ""
   echo "Starting to make GRPPHA..."
   echo ""
   grppha ${spec_dir}/${src} ${spec_dir}/${src}.new comm="group min $grppha_bin" tempc="exit" clobber=yes 
   echo "GRPPHA: ${spec_dir}/${src}.new in group min $grppha_bin"
   echo ""

   grppha ${src}.new ${src}.new2 comm="chkey backfile ${bkg} & chkey respfile ${rmf} & chkey ancrfile ${arf}" tempc="exit" clobber=yes 
  
   rm $spec_dir/grppha.in 
   rm $spec_dir/grppha1.in
   rm ${spec_dir}/${src}.new 
   rm ${spec_dir}/${src}
   mv ${spec_dir}/${src}.new2 ${spec_dir}/${src}
  endif
 set Nflare = ` expr $Nflare + 1`
 end
endif

if ( $DET == 03 ) then   
cd ${data_dir}/${dir0}/
 rm list_PN.txt
 set evpnS = `ls *PN00_S*_ImagingEvts.ds*`
 set evpnU = `ls *PN00_U*_ImagingEvts.ds*`
 set npnS = `echo $evpnS | wc -l | awk '{print $1}'`
 set npnU = `echo $evpnU | wc -l | awk '{print $1}'`
 if ($npnS != 0) then
  echo "$evpnS" >> list_PN.txt
 endif
 if ($npnU != 0) then
  echo "$evpnU" >> list_PN.txt
 endif

 cd ${spec_dir}/
 set exprEN="#XMMEA_EP&&(TIME >= 425069359.715)&&(TIME <= 425069674.854)"
# set exprEN="(PATTERN<=4)"
# set exprEN="#XMMEA_EP&&(FLAG==0)&&(PATTERN<=4)"
#2003max set exprEN="(PATTERN<=4)&&(PHASE in [0.1 : 0.35])"
#2003min set exprEN="(PATTERN<=4)&&(PHASE in [0.6 : 0.85])"
#2003half1 set exprEN="(PATTERN<=4)&&(PHASE in [0.35 : 0.6])"
#2003half2 set exprEN="(PATTERN<=4)&&(PHASE in [0.85 : 1] || PHASE in [0 : 0.1])"

#2014max set exprEN="(PATTERN<=4)&&(PHASE in [0.75 : 1])"
#2014min set exprEN="(PATTERN<=4)&&(PHASE in [0.25 : 0.5])"
#2014half1 set exprEN="(PATTERN<=4)&&(PHASE in [0 : 0.25])"
#2014half2 set exprEN="(PATTERN<=4)&&(PHASE in [0.5 : 0.75])"
 
 set Nflare = 1
 foreach ev (`cat ${data_dir}/${dir0}/list_PN.txt`)
  if ( -e ${data_dir}/${dir0}/${ev} ) then
   set obsevt="${dir0}"
   set str=`echo ${ev} | cut -c 17-21`
   set str1=`echo ${ev} | cut -c 23-26`
   fkeypar ${data_dir}/${dir0}/${ev}+1 DATE-OBS
   set date = `pget fkeypar.par value`
   set date_obs=`echo ${date} | cut -c 2-11`
   if ($filter1 == "SP") then
    echo "evt file SP cleaned"
    set flarefile=`awk -v nr=$Nflare '{ if (NR == nr) print $1}' $proc/list_GTI_Flare.txt`
    if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
     echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME) && GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
     source $spec_dir/filt.csh
     rm $spec_dir/filt.csh
     echo "ATTENTION: The Soft Protons cleaned analysis is selected"
     echo "           It is filtered with Global HK Attitude GTI"
     echo "           It is filtered with GTI from EPIC flare background timeseries"
    else
     echo "/usr/bin/time -p evselect expression='GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
     source $spec_dir/filt.csh
     rm $spec_dir/filt.csh
     echo "ATTENTION: The Soft Protons cleaned analysis is selected"
     echo "           It is filtered with GTI from EPIC flare background timeseries"
    endif
   else
    echo "evt file not SP cleaned"
    if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
      echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh 
      source $spec_dir/filt.csh
      rm $spec_dir/filt.csh
      echo "ATTENTION: The Soft Protons not cleaned analysis is selected"
      echo "           It is filtered with Global HK Attitude GTI"
    else
      echo "ATTENTION: No filter is selected"
      cp ${data_dir}/${dir0}/${ev} ${spec_dir}/
    endif
   endif

   if ($spec_baryecentered == "yes") then
    echo ""
    echo "Starting to barycentered the file ${ev}..."
    echo ""
    echo "barycen withtable=yes table=${spec_dir}/${ev}:EVENTS timecolumn=TIME withsrccoordinates=no srcra=${target_RA} srcdec=${target_DEC} processgtis=yes processexposutables=yes time=0 ephemeris=DE405 -w ${warn}" > ${spec_dir}/bary.csh
    source ${spec_dir}/bary.csh
    rm ${spec_dir}/bary.csh
   else
    echo "Using event file not barycentered..."
   endif

#SRC
   echo ""
   echo "Starting to calculate the ${target_name} spectrum..."
   set filt = "${dir0}_src_${str}_${str1}_${date_obs}.ds"
   set src = "${dir0}_src_${str}_${str1}_${date_obs}.pha"
   set bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.pha"
   set filt_bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.ds"
   set arf = "${dir0}_arf_${str}_${str1}_${date_obs}.ds"
   set rmf = "${dir0}_rmf_${str}_${str1}_${date_obs}.ds"
   set X_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFXCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set Y_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFYCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set target_X = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set target_Y = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of ${target_name} (RA,Dec): ${target_RA} ${target_DEC}" 
   echo "direction of ${target_name} (X,Y): ${target_X} ${target_Y}"
   echo "radius of circle around ${target_name}: ${radius_spec_src}"
   echo ""

   echo "#! /bin/tcsh -f" > $spec_dir/src.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=4)&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
  # echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
   source $spec_dir/src.csh
   rm $spec_dir/src.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${src} useodfatt=no
   echo "${src} done !"
   echo ""

#BKG
   echo ""
   echo "Starting to calculate the ${target_name} background..."
   if ($bkg_spec_pos == "no") then
    if ( ${str} == "EPN00" ) then
     set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg_PN.txt | awk '{print $1}'`
     set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg_PN.txt | awk '{print $2}'`
    endif 
    #set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $1}'`
    #set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $2}'`
   endif
   set bkg_X = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set bkg_Y = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of background circle around ${target_name} (RA,Dec): ${bkg_RA} ${bkg_DEC}" 
   echo "direction of background circle around ${target_name} (X,Y): ${bkg_X} ${bkg_Y}"
   echo "radius of the background circle around ${target_name}: ${radius_spec_bkg}"
   echo ""
    
   echo "#! /bin/tcsh -f" > $spec_dir/bkg.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=4)&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
#   echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
   source $spec_dir/bkg.csh
   rm $spec_dir/bkg.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${bkg} useodfatt=no
   echo "${bkg} done !"
   echo ""

#RMF ARF
    
   echo ""
   echo "Starting to calculate the rmf..."
   echo ""
   rmfgen spectrumset=${spec_dir}/${src} rmfset=${spec_dir}/${rmf}
   echo "${rmf}!"
   echo ""

   echo ""
   echo "Starting to calculate the arf..."
   echo ""
   arfgen spectrumset=${spec_dir}/${src} detmaptype=psf arfset=${spec_dir}/${arf} withrmfset=yes rmfset=${spec_dir}/${rmf} useodfatt=no
   echo "${arf} !"
   echo ""

#GRPPHA
    
   echo ""
   echo "Starting to make GRPPHA..."
   echo ""
   grppha ${spec_dir}/${src} ${spec_dir}/${src}.new comm="group min $grppha_bin" tempc="exit" clobber=yes 
   echo "GRPPHA: ${spec_dir}/${src}.new in group min $grppha_bin"
   echo ""

   grppha ${src}.new ${src}.new2 comm="chkey backfile ${bkg} & chkey respfile ${rmf} & chkey ancrfile ${arf}" tempc="exit" clobber=yes 
# grppha ${src}.new ${src}.new2 comm="chkey backfile ${bkg} & chkey respfile ${rmf} & chkey ancrfile ${arf} & chkey exp 3283" tempc="exit" clobber=yes 
# grppha ${bkg} ${bkg}.new2 comm="chkey exp 3283" tempc="exit" clobber=yes 
#2014  grppha ${src}.new ${src}.new2 comm="chkey backfile ${bkg} & chkey respfile ${rmf} & chkey ancrfile ${arf} & chkey exp 9392" tempc="exit" clobber=yes 
#2014 grppha ${bkg} ${bkg}.new2 comm="chkey exp 9392" tempc="exit" clobber=yes 
  
   rm $spec_dir/grppha.in 
   rm $spec_dir/grppha1.in
   rm ${spec_dir}/${src}.new 
   rm ${spec_dir}/${src}
   mv ${spec_dir}/${src}.new2 ${spec_dir}/${src}
#   mv ${spec_dir}/${bkg}.new2 ${spec_dir}/${bkg}
  endif
 set Nflare = ` expr $Nflare + 1`
 end
endif

if ( $DET == 2 ) then   
 cd ${data_dir}/${dir0}/
 rm list_M_PN.txt
 set evS1 = `ls *MOS1_S*_ImagingEvts.ds*`
 set evS2 = `ls *MOS2_S*_ImagingEvts.ds*`
 set evU1 = `ls *MOS1_U*_ImagingEvts.ds*`
 set evU2 = `ls *MOS2_U*_ImagingEvts.ds*`
 set evpnS = `ls *PN00_S*_ImagingEvts.ds*`
 set evpnU = `ls *PN00_U*_ImagingEvts.ds*`
 
 set nS1 = `echo $evS1 | wc -l | awk '{print $1}'`
 set nS2 = `echo $evS2 | wc -l | awk '{print $1}'`
 set nU1 = `echo $evU1 | wc -l | awk '{print $1}'`
 set nU2 = `echo $evU2 | wc -l | awk '{print $1}'`
 set npnS = `echo $evpnS | wc -l | awk '{print $1}'`
 set npnU = `echo $evpnU | wc -l | awk '{print $1}'`
 if ($nS1 != 0) then
  echo "$evS1" >> list_M_PN.txt
 endif
 if ($nS2 != 0) then
  echo "$evS2" >> list_M_PN.txt
 endif
 if ($nU1 != 0) then
  echo "$evU1" >> list_M_PN.txt
 endif
 if ($nU2 != 0) then
  echo "$evU2" >> list_M_PN.txt
 endif
 if ($npnS != 0) then
  echo "$evpnS" >> list_M_PN.txt
 endif
 if ($npnU != 0) then
  echo "$evpnU" >> list_M_PN.txt
 endif
 cd ${spec_dir}/
 set Nflare = 1
 foreach ev (`cat ${data_dir}/${dir0}/list_M_PN.txt`)
  if ( -e ${data_dir}/${dir0}/${ev} ) then
   set obsevt="${dir0}"
   set str=`echo ${ev} | cut -c 17-21`
   set str1=`echo ${ev} | cut -c 23-26`
   fkeypar ${data_dir}/${dir0}/${ev}+1 DATE-OBS
   set date = `pget fkeypar.par value`
   set date_obs=`echo ${date} | cut -c 2-11`
   if ( ${str} == "EMOS1" || ${str} == "EMOS2") then
   # set exprEN="#XMMEA_EM"
   #298587693.547-298587813.442
   #WP2 T1 set exprEN="#XMMEA_EM&&(TIME > 298587693.547)&&(TIME < 298587813.442)"
   set exprEN="#XMMEA_EM&&(TIME > 243664302.174)&&(TIME < 243664509.232)"
   # set exprEN="#XMMEA_EM&&(TIME > 425069359)&&(TIME < 425069675)"
   # set exprEN="#XMMEA_EM&&(TIME >= 425069359.715)&&(TIME <= 425069674.854)"
   # set exprEN="#XMMEA_EM"
   # set exprEN="#XMMEA_EM&&(FLAG==0)"
    if ($filter1 == "SP") then
     echo "evt file SP cleaned"
     set flarefile=`awk -v nr=$Nflare '{ if (NR == nr) print $1}' $proc/list_GTI_Flare.txt`
     if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
      echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME) && GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
      source $spec_dir/filt.csh
      rm $spec_dir/filt.csh
      echo "ATTENTION: The Soft Protons cleaned analysis is selected"
      echo "           It is filtered with Global HK Attitude GTI"
      echo "           It is filtered with GTI from EPIC flare background timeseries"
     else
      echo "/usr/bin/time -p evselect expression='GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
      source $spec_dir/filt.csh
      rm $spec_dir/filt.csh
      echo "ATTENTION: The Soft Protons cleaned analysis is selected"
      echo "           It is filtered with GTI from EPIC flare background timeseries"
     endif
    else
     echo "evt file not SP cleaned"
     if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
      echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh 
      source $spec_dir/filt.csh
      rm $spec_dir/filt.csh
      echo "ATTENTION: The Soft Protons not cleaned analysis is selected"
      echo "           It is filtered with Global HK Attitude GTI"
     else
      echo "ATTENTION: No filter is selected"
      cp ${data_dir}/${dir0}/${ev} ${spec_dir}/
     endif
    endif
  
   if ($spec_baryecentered == "yes") then
    echo ""
    echo "Starting to barycentered the file ${ev}..."
    echo ""
    echo "barycen withtable=yes table=${spec_dir}/${ev}:EVENTS timecolumn=TIME withsrccoordinates=no srcra=${target_RA} srcdec=${target_DEC} processgtis=yes processexposutables=yes time=0 ephemeris=DE405 -w ${warn}" > ${spec_dir}/bary.csh
    source ${spec_dir}/bary.csh
    rm ${spec_dir}/bary.csh
   else
    echo "Using event file not barycentered..."
   endif

#SRC
   echo ""
   echo "Starting to calculate the ${target_name} spectrum..."
   set filt = "${dir0}_src_${str}_${str1}_${date_obs}.ds"
   set src = "${dir0}_src_${str}_${str1}_${date_obs}.pha"
   set bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.pha"
   set filt_bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.ds"
   set arf = "${dir0}_arf_${str}_${str1}_${date_obs}.ds"
   set rmf = "${dir0}_rmf_${str}_${str1}_${date_obs}.ds"
   set X_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFXCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set Y_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFYCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set target_X = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set target_Y = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of ${target_name} (RA,Dec): ${target_RA} ${target_DEC}" 
   echo "direction of ${target_name} (X,Y): ${target_X} ${target_Y}"
   echo "radius of circle around ${target_name}: ${radius_spec_src}"
   echo ""

   echo "#! /bin/tcsh -f" > $spec_dir/src.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=12)&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
  # echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&(PATTERN<=12)&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
   source $spec_dir/src.csh
   rm $spec_dir/src.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${src} useodfatt=no
   echo "${src} done !"
   echo ""

#BKG
   echo ""
   echo "Starting to calculate the ${target_name} background..."
   if ($bkg_spec_pos == "no") then
    #set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $1}'`
    #set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $2}'`
    if ( ${str} == "EMOS1" ) then
     set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg_M1.txt | awk '{print $1}'`
     set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg_M1.txt | awk '{print $2}'`
    endif
    if ( ${str} == "EMOS2" ) then
     set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg_M2.txt | awk '{print $1}'`
     set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg_M2.txt | awk '{print $2}'`
    endif 
   endif
   set bkg_X = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set bkg_Y = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of background circle around ${target_name} (RA,Dec): ${bkg_RA} ${bkg_DEC}" 
   echo "direction of background circle around ${target_name} (X,Y): ${bkg_X} ${bkg_Y}"
   echo "radius of the background circle around ${target_name}: ${radius_spec_bkg}"
   echo ""
    
   echo "#! /bin/tcsh -f" > $spec_dir/bkg.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=12)&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
  # echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&(PATTERN<=12)&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=15 withspecranges=true specchannelmin=0 specchannelmax=11999 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
   source $spec_dir/bkg.csh
   rm $spec_dir/bkg.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${bkg} useodfatt=no
   echo "${bkg} done !"
   echo ""

#RMF ARF
    
   echo ""
   echo "Starting to calculate the rmf..."
   echo ""
   rmfgen spectrumset=${spec_dir}/${src} rmfset=${spec_dir}/${rmf}
   echo "${rmf}!"
   echo ""

   echo ""
   echo "Starting to calculate the arf..."
   echo ""
   arfgen spectrumset=${spec_dir}/${src} detmaptype=psf arfset=${spec_dir}/${arf} withrmfset=yes rmfset=${spec_dir}/${rmf} useodfatt=no
   echo "${arf} !"
   echo ""

#GRPPHA
    
   echo ""
   echo "Starting to make GRPPHA..."
   echo ""
   grppha ${spec_dir}/${src} ${spec_dir}/${src}.new comm="group min $grppha_bin" tempc="exit" clobber=yes 
   echo "GRPPHA: ${spec_dir}/${src}.new in group min $grppha_bin"
   echo ""

   grppha ${src}.new ${src}.new2 comm="chkey backfile ${bkg} & chkey respfile ${rmf} & chkey ancrfile ${arf}" tempc="exit" clobber=yes 
  
   rm $spec_dir/grppha.in 
   rm $spec_dir/grppha1.in
   rm ${spec_dir}/${src}.new 
   rm ${spec_dir}/${src}
   mv ${spec_dir}/${src}.new2 ${spec_dir}/${src}
   endif

   if ( ${str} == "EPN00") then
  #  set exprEN="#XMMEA_EP"
   set exprEN="#XMMEA_EP&&(TIME > 243664302.174)&&(TIME < 243664509.232)"
   #WP2 T1 set exprEN="#XMMEA_EP&&(TIME > 298587693.547)&&(TIME < 298587813.442)"
   # set exprEN="#XMMEA_EP&&(TIME > 425069359)&&(TIME < 425069675)"
   # set exprEN="#XMMEA_EP&&(PATTERN<=4)"
   # set exprEN="#XMMEA_EP&&(FLAG==0)&&(PATTERN<=4)"
   if ($filter1 == "SP") then
    echo "evt file SP cleaned"
    set flarefile=`awk -v nr=$Nflare '{ if (NR == nr) print $1}' $proc/list_GTI_Flare.txt`
    if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
     echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME) && GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
     source $spec_dir/filt.csh
     rm $spec_dir/filt.csh
     echo "ATTENTION: The Soft Protons cleaned analysis is selected"
     echo "           It is filtered with Global HK Attitude GTI"
     echo "           It is filtered with GTI from EPIC flare background timeseries"
    else
     echo "/usr/bin/time -p evselect expression='GTI("$proc"/$flarefile,TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh
     source $spec_dir/filt.csh
     rm $spec_dir/filt.csh
     echo "ATTENTION: The Soft Protons cleaned analysis is selected"
     echo "           It is filtered with GTI from EPIC flare background timeseries"
    endif
   else
    echo "evt file not SP cleaned"
    if ( -e "$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits) then
      echo "/usr/bin/time -p evselect expression='GTI("$data_dir"/"$dir0"/"$dir0"_GlobalHK-Attitude_GTI.fits, TIME)' filteredset=${spec_dir}/${ev} imagebinning=binSize imagedatatype=Int32 keepfilteroutput=Y table=${data_dir}/${dir0}/${ev}:EVENTS updateexposure=true withfilteredset=Y withimagedatatype=true withimageset=N writedss=true xcolumn=X ximagebinsize=80 ycolumn=Y yimagebinsize=80 -w "$warn" -V "$verb"" > $spec_dir/filt.csh 
      source $spec_dir/filt.csh
      rm $spec_dir/filt.csh
      echo "ATTENTION: The Soft Protons not cleaned analysis is selected"
      echo "           It is filtered with Global HK Attitude GTI"
    else
      echo "ATTENTION: No filter is selected"
      cp ${data_dir}/${dir0}/${ev} ${spec_dir}/
    endif
   endif

   if ($spec_baryecentered == "yes") then
    echo ""
    echo "Starting to barycentered the file ${ev}..."
    echo ""
    echo "barycen withtable=yes table=${spec_dir}/${ev}:EVENTS timecolumn=TIME withsrccoordinates=no srcra=${target_RA} srcdec=${target_DEC} processgtis=yes processexposutables=yes time=0 ephemeris=DE405 -w ${warn}" > ${spec_dir}/bary.csh
    source ${spec_dir}/bary.csh
    rm ${spec_dir}/bary.csh
   else
    echo "Using event file not barycentered..."
   endif

#SRC
   echo ""
   echo "Starting to calculate the ${target_name} spectrum..."
   set filt = "${dir0}_src_${str}_${str1}_${date_obs}.ds"
   set src = "${dir0}_src_${str}_${str1}_${date_obs}.pha"
   set bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.pha"
   set filt_bkg = "${dir0}_bkg_${str}_${str1}_${date_obs}.ds"
   set arf = "${dir0}_arf_${str}_${str1}_${date_obs}.ds"
   set rmf = "${dir0}_rmf_${str}_${str1}_${date_obs}.ds"
   set X_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFXCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set Y_REF=`ftlist ${data_dir}/${dir0}/${ev}'[0]' K include=REFYCRVL | cut -d'=' -f2 | cut -d'/' -f1`
   set target_X = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set target_Y = `echo ${X_REF} ${Y_REF} ${target_RA} ${target_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of ${target_name} (RA,Dec): ${target_RA} ${target_DEC}" 
   echo "direction of ${target_name} (X,Y): ${target_X} ${target_Y}"
   echo "radius of circle around ${target_name}: ${radius_spec_src}"
   echo ""

   echo "#! /bin/tcsh -f" > $spec_dir/src.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=4)&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
  # echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&((X,Y) IN circle (${target_X},${target_Y},${radius_spec_src})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${src} filteredset=${spec_dir}/${filt} withfilteredset=Y" >> $spec_dir/src.csh
   source $spec_dir/src.csh
   rm $spec_dir/src.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${src} useodfatt=no
   echo "${src} done !"
   echo ""

#BKG
   echo ""
   echo "Starting to calculate the ${target_name} background..."
   if ($bkg_spec_pos == "no") then
    #set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $1}'`
    #set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg.txt | awk '{print $2}'`
    if ( ${str} == "EPN00" ) then
     set bkg_RA = `cat ${ref}/REG_BKG/${dir0}_bkg_PN.txt | awk '{print $1}'`
     set bkg_DEC = `cat ${ref}/REG_BKG/${dir0}_bkg_PN.txt | awk '{print $2}'`
    endif 
   endif
   set bkg_X = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $1}'`  
   set bkg_Y = `echo ${X_REF} ${Y_REF} ${bkg_RA} ${bkg_DEC} | awk -f ${progr_dir}/RADEC2XY.awk | awk '{print $2}'`  
   echo ""
   echo "image center (RA,Dec): ${X_REF} ${Y_REF}"
   echo "direction of background circle around ${target_name} (RA,Dec): ${bkg_RA} ${bkg_DEC}" 
   echo "direction of background circle around ${target_name} (X,Y): ${bkg_X} ${bkg_Y}"
   echo "radius of the background circle around ${target_name}: ${radius_spec_bkg}"
   echo ""
    
   echo "#! /bin/tcsh -f" > $spec_dir/bkg.csh
  # echo "evselect table=${spec_dir}/${ev} expression='(PI in ["$bmin_spec":"$bmax_spec"])&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
   echo "evselect table=${spec_dir}/${ev} expression='(PATTERN<=4)&&((X,Y) IN circle (${bkg_X},${bkg_Y},${radius_spec_bkg})) && "$exprEN"' withspectrumset=true energycolumn=PI spectralbinsize=5 withspecranges=true specchannelmin=0 specchannelmax=20479 spectrumset=${spec_dir}/${bkg} filteredset=${spec_dir}/${filt_bkg} withfilteredset=Y" >> $spec_dir/bkg.csh
   source $spec_dir/bkg.csh
   rm $spec_dir/bkg.csh

   echo ""
   echo "Starting to make the backscale..."
   echo ""
   backscale spectrumset=${spec_dir}/${bkg} useodfatt=no
   echo "${bkg} done !"
   echo ""

#RMF ARF
    
   echo ""
   echo "Starting to calculate the rmf..."
   echo ""
   rmfgen spectrumset=${spec_dir}/${src} rmfset=${spec_dir}/${rmf}
   echo "${rmf}!"
   echo ""

   echo ""
   echo "Starting to calculate the arf..."
   echo ""
   arfgen spectrumset=${spec_dir}/${src} detmaptype=psf arfset=${spec_dir}/${arf} withrmfset=yes rmfset=${spec_dir}/${rmf} useodfatt=no
   echo "${arf} !"
   echo ""

#GRPPHA
    
   echo ""
   echo "Starting to make GRPPHA..."
   echo ""
   grppha ${spec_dir}/${src} ${spec_dir}/${src}.new comm="group min $grppha_bin" tempc="exit" clobber=yes 
   echo "GRPPHA: ${spec_dir}/${src}.new in group min $grppha_bin"
   echo ""

   grppha ${src}.new ${src}.new2 comm="chkey backfile ${bkg} & chkey respfile ${rmf} & chkey ancrfile ${arf}" tempc="exit" clobber=yes 
  
   rm $spec_dir/grppha.in 
   rm $spec_dir/grppha1.in
   rm ${spec_dir}/${src}.new 
   rm ${spec_dir}/${src}
   mv ${spec_dir}/${src}.new2 ${spec_dir}/${src}
   endif
  endif
 set Nflare = ` expr $Nflare + 1`
 end
endif
cd ${start_dir}/

date
echo " stop spectra_target.csh "
