#! /bin/tcsh -f

echo "************************"
echo "*  start cat_trans.csh *"
echo "************************"
date

cd $result_dir/
set prod_dir=$result_dir/$dir0/WP4products
if ($type_stringa == "binfixed") then
 if (-r $prod_dir/BIN) then
  set prod_dirbin = $prod_dir/BIN
 else
  set prod_dirbin = $prod_dir/BIN
  mkdir $prod_dirbin
 endif
endif
if ($type_stringa == "bayesian") then
 if (-r $prod_dir/BAYESIAN) then
  set prod_dirbin = $prod_dir/BAYESIAN
 else
  set prod_dirbin = $prod_dir/BAYESIAN
  mkdir $prod_dirbin
 endif
endif

if ($type_stringa == "bayesian") then
 set filter3xmm="$result_dir"/"$dir0"/filter/full_bin
 rm "$an_dir"/trans_box.txt
#Change the filtered*.txt adding the instrument flag
 echo "Adding the instrument flag..."
 source $progr_dir/instrument_flag.csh
endif

set ctrl_no_trans = 0
cd $an_dir

if (-e emllist_trans.txt) then
 rm emllist_trans.txt
endif
if (-e "$an_dir"/"$dir0"_1trans.txt) then
   echo ""$an_dir"/"$dir0"_1trans.txt exists"
   set ctrl_trans=`wc -l "$an_dir"/"$dir0"_1trans.txt | awk '{print $1}'`
   if ($ctrl_trans == 2) then
     echo "WARNING: there are not transient sources in the $an_dir/"$dir0"_1trans.txt"
     echo "WARNING: there are not transient sources in the $an_dir/"$dir0"_1trans.txt BINFIXED" >> $log_dir/messages.log
     echo "WARNING: no transients are detected for the observation $dir0" >> $prod_dir_final/NO_TRANSIENT.txt
   else
    set ntrans = 1 
    foreach trans_list (`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk '{print $1}'`)
     set n_tim_int=`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk -v nr=$ntrans '{ if (NR == nr) print $15}' | wc | awk '{print $3}'`
     echo $n_tim_int >> $an_dir/n_tim_int.txt 
    set ntrans = ` expr $ntrans + 1`
    end
   endif
   set max_n_tim_int=`cat $an_dir/n_tim_int.txt | sort -nr | awk 'NR == 1 {print $1}'`  
   rm $an_dir/n_tim_int.txt
endif

if (-e "$an_dir"/"$dir0"_1trans.txt) then
   echo ""$an_dir"/"$dir0"_1trans.txt exists"
   set ctrl_trans=`wc -l "$an_dir"/"$dir0"_1trans.txt | awk '{print $1}'`
   if ($ctrl_trans == 2) then
     echo "WARNING: there are not transient sources in the $an_dir/"$dir0"_1trans.txt"
     echo "WARNING: there are not transient sources in the $an_dir/"$dir0"_1trans.txt BINFIXED" >> $log_dir/messages.log
     set ctrl_no_trans = 1
   else
    set ctrl_trigger_out=0
    set ctrl_trigger_in=0
    
    #Optimised_flare_GTI
    ls -1 $result_dir/$dir0/processed/*Optimised_flare_GTI_* > $an_dir/list_Optimised_flare_GTI.txt
    set N=`cat $an_dir/list_Optimised_flare_GTI.txt | wc -l | awk '{print $1}'`
    if ( $N != 0 ) then
     mgtime ""$etm"list_Optimised_flare_GTI.txt" Optimised_flare_GTI.fits OR indates="-"
     rm $an_dir/list_Optimised_flare_GTI.txt
     echo "OK: Optimised flare GTIs exist"
    else
     echo "WARNING: no Optimised flare GTIs exist"
    endif
    set ntrans = 1 
    foreach trans_list (`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk '{print $1}'`)
     echo "Transient: $ntrans"
     set ctrl_SPclean = 0
     set ctrl_SPclean_merge = 0
     if ($type_stringa == "binfixed") then
      set tsts=`echo $trans_list | cut -d'.' -f1 | cut -d'_' -f3 | awk '{print $1}'`
     endif
     if ($type_stringa == "bayesian") then
      set tsts=`echo $trans_list | cut -d'_' -f3 | cut -d'.' -f-3 | awk '{print $1}'`
     endif
     set id_trans=`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk -v nr=$ntrans '{ if (NR == nr) print int($13)}'`
     set n_timbin=`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk -v nr=$ntrans '{ if (NR == nr) print int($14)}'`
     set tim_int=`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk -v nr=$ntrans '{ if (NR == nr) print $15}'`
     
     ##tstart e tstop
     set n_timbin_ctrl=1
     while($n_timbin_ctrl <= $n_timbin)
      set n_timbin_tstart=`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk -v nr=$ntrans '{ if (NR == nr) print $15}' | cut -d'-' -f$n_timbin_ctrl | cut -d',' -f2`
      set n_timbin_tstop=`grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk -v nr=$ntrans '{ if (NR == nr) print $15}' | cut -d',' -f$n_timbin_ctrl | cut -d'-' -f2`
      echo $n_timbin_tstart >> "$an_dir"/timbin_tstart_"$ntrans".txt
      echo $n_timbin_tstop >> "$an_dir"/timbin_tstop_"$ntrans".txt
      echo $n_timbin_tstart $n_timbin_tstop >> "$an_dir"/timbin_"$ntrans".txt
     set n_timbin_ctrl = `expr $n_timbin_ctrl + 1`
     end
     echo "T_START 50D sec" > "$an_dir"/column_timbin_tstart.txt
     echo "T_STOP 50D sec" > "$an_dir"/column_timbin_tstop.txt
    
    ##calculate SPclean_flag
      echo "START D sec" > "$an_dir"/column_timbin.txt
      echo "STOP D sec" >> "$an_dir"/column_timbin.txt
      echo "fcreate $an_dir/column_timbin.txt $an_dir/timbin_$ntrans.txt $an_dir/GTI_t$ntrans.fits clobber=yes" >> $an_dir/fcreate.csh
      source $an_dir/fcreate.csh
      rm $an_dir/fcreate.csh
      rm $an_dir/timbin_$ntrans.txt
      mgtime "GTI_t$ntrans.fits,GTI_t$ntrans.fits" tmp_gti.fits OR indates="-"
      mv tmp_gti.fits GTI_t$ntrans.fits
      if (-e $an_dir/GTI_t$ntrans.fits) then
       echo "fcalc GTI_t$ntrans.fits GTI_DELTA_t$ntrans.fits DELTA_T 'STOP-START' clobber=yes" > $an_dir/fcalc.csh
       source $an_dir/fcalc.csh
       rm $an_dir/fcalc.csh
      endif
      if (-e $an_dir/GTI_DELTA_t$ntrans.fits) then
       echo "fcalc GTI_DELTA_t$ntrans.fits GTI_SUM_DELTA_t$ntrans.fits SUM_DELTA_T 'accum(DELTA_T)' clobber=yes" > $an_dir/fcalc.csh
       source $an_dir/fcalc.csh
       rm $an_dir/fcalc.csh
       rm $an_dir/GTI_DELTA_t$ntrans.fits
      endif
      if (-e $an_dir/GTI_SUM_DELTA_t$ntrans.fits) then
       fkeypar $an_dir/GTI_SUM_DELTA_t$ntrans.fits+1 NAXIS2
       set delta_rows = `pget fkeypar.par value`
       set GTI_SUM=`ftlist GTI_SUM_DELTA_t$ntrans.fits+1 T columns='SUM_DELTA_T' rows="$delta_rows" rownum="no" colheader="no"`
       echo "Cumulative sum of time bin intervals for the transient: $GTI_SUM sec"
       set ctrl_SPclean = 1
      endif

      if (-e $an_dir/GTI_t$ntrans.fits && -e $an_dir/Optimised_flare_GTI.fits) then
       echo "Starting GTI merge for the transient $ntrans..."
       mgtime "GTI_t$ntrans.fits,Optimised_flare_GTI.fits" GTI_merge_t"$ntrans".fits AND indates="-"
       fkeypar $an_dir/GTI_merge_t"$ntrans".fits+1 NAXIS2
       set merge_rows = `pget fkeypar.par value`
      else
       set merge_rows = 0
      endif
      if ($merge_rows == 0) then
       set GTI_merge_SUM = 0
       echo "Cumulative sum of time bin intervals merged: $GTI_merge_SUM sec"
       set ctrl_SPclean_merge = 1
      else
       if (-e $an_dir/GTI_merge_t"$ntrans".fits) then
        echo "fcalc GTI_merge_t"$ntrans".fits GTI_merge_DELTA_t$ntrans.fits DELTA_T 'STOP-START' clobber=yes" > $an_dir/fcalc.csh
        source $an_dir/fcalc.csh
        rm $an_dir/fcalc.csh
       endif
       if (-e $an_dir/GTI_merge_DELTA_t$ntrans.fits) then
        echo "fcalc GTI_merge_DELTA_t$ntrans.fits GTI_merge_SUM_DELTA_t$ntrans.fits SUM_DELTA_T 'accum(DELTA_T)' clobber=yes" > $an_dir/fcalc.csh
        source $an_dir/fcalc.csh
        rm $an_dir/fcalc.csh
        rm $an_dir/GTI_merge_DELTA_t$ntrans.fits
       endif
       if (-e $an_dir/GTI_merge_SUM_DELTA_t$ntrans.fits) then
        fkeypar $an_dir/GTI_merge_SUM_DELTA_t$ntrans.fits+1 NAXIS2
        set delta_rows = `pget fkeypar.par value`
        set GTI_merge_SUM=`ftlist GTI_merge_SUM_DELTA_t$ntrans.fits+1 T columns='SUM_DELTA_T' rows="$delta_rows" rownum="no" colheader="no"`
        echo "Cumulative sum of time bin intervals merged: $GTI_merge_SUM sec"
        set ctrl_SPclean_merge = 1
       endif
      endif
      if ($ctrl_SPclean == 1 && $ctrl_SPclean_merge == 1) then
       set SPclean_flag=`echo $GTI_merge_SUM $GTI_SUM | awk '{printf("%.3f \n",$1/$2)}'`
       echo "SP clean flag for the transient $ntrans : $SPclean_flag"
      endif
      
      echo "*****************************SP FLAG STATISTIC*****************************"
      echo " TRANS: $ntrans"
      echo " SUM OF TIME BIN INTERVALS OF TRANSIENT (sec): $GTI_SUM"
      echo " N. TIME BIN INTERVALS MERGED: $merge_rows"
      echo " SUM OF TIME BIN INTERVALS OF TRANSIENT AND GTI FLARE MERGED (sec): $GTI_merge_SUM"
      echo " SP CLEAN FLAG: $SPclean_flag"
      echo "***************************************************************************"

     ##single transient catalogue
     echo "Start to make the single trans catalogue"
     if (-e $an_dir/emllist_"$tsts".fits) then
     fkeypar $an_dir/emllist_"$tsts".fits+1 NAXIS2
     set emllist_rows = `pget fkeypar.par value`
     if ($emllist_rows != 0) then
      if ($DET == 1 || $DET == 2) then
       fselect $an_dir/emllist_"$tsts".fits+1 $an_dir/emllist_trans"$ntrans"_partial.fits ML_ID_SRC.eq."$id_trans" CLOBBER=yes 
       if (-e $an_dir/emllist_trans"$ntrans"_partial.fits) then
        echo "emllist_trans"$ntrans"_partial.fits+1" >> $an_dir/emllist_trans.txt
        cp "$dir0"_1_"$tsts"_trans"$ntrans".reg "$dir0"_1_"$tsts"_trans"$ntrans"_bkg.reg $prod_dirbin
       else
        echo "$an_dir/emllist_trans"$ntrans"_partial.fits does not exist"
       endif
      else
       fselect $an_dir/emllist_"$tsts".fits+1 $an_dir/emllist_trans"$ntrans"_partial.fits ML_ID_SRC.eq."$id_trans".and.ID_INST.ne.0 CLOBBER=yes 
       echo "emllist_trans"$ntrans"_partial.fits+1" >> $an_dir/emllist_trans.txt
       cp "$dir0"_1_"$tsts"_trans"$ntrans".reg "$dir0"_1_"$tsts"_trans"$ntrans"_bkg.reg $prod_dirbin
      endif
      
      #png
      echo "Start to make the png image"
      if ($plot0 == 1) then
       if (-e "$an_dir"/emllist_trans"$ntrans"_partial.fits) then
        if ($type_stringa == "bayesian") then
         echo "Start to make the bayesian box region file"
         grep "$dir0" "$an_dir"/"$dir0"_1trans.txt | awk -v nr=$ntrans '{ if (NR == nr) print $15}' | tr , '\n' > "$an_dir"/intervalT_trans"$ntrans".txt
         set N_intervalT = 1
         foreach intervalT (`cat "$an_dir"/intervalT_trans"$ntrans".txt`)
          echo "Interval $N_intervalT for trans"$ntrans""
          set newtsts=`echo ${intervalT} | sed -e "s/-/ /g"`
          set degRA_DEC=`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | wc -l`
         if ($degRA_DEC == 1) then
          echo "The time bin ${intervalT} is not degenerate in boxRA and boxDEC"
          set INST=`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | awk '{print $6}'`
          set boxRA=`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | awk '{print $1}'`
          set boxDEC=`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | awk '{print $2}'`
          echo "fk5" > $an_dir/bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$degRA_DEC".reg
          echo "box(${boxRA},${boxDEC},${regionsize}${vir},${regionsize}${vir},0)" >> $an_dir/bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$degRA_DEC".reg
          cp "$an_dir"/bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$degRA_DEC".reg $prod_dirbin
          #check trans in the bayesian box
          echo "Start to check if the transient "$ntrans" is inside of the bayesian box"
          set RA_trans=`ftlist "${an_dir}/emllist_trans${ntrans}_partial.fits[col RA]" T rows=1 colheader=no | awk '{print $2}'`
          set DEC_trans=`ftlist "${an_dir}/emllist_trans${ntrans}_partial.fits[col DEC]" T rows=1 colheader=no | awk '{print $2}'`
          set boxreg_sys=`echo ${regionsize} ${region_sys} | awk '{printf("%.4f \n",(($1+$2)/3600))}'`
          set diffRA_box_trans=`echo ${RA_trans} ${boxRA} ${boxDEC} | awk '{printf("%.4f \n",sqrt((cos($3)*($2-$1))^2))}'`
          set diffDEC_box_trans=`echo ${DEC_trans} ${boxDEC} | awk '{printf("%.4f \n",sqrt(($2-$1)^2))}'`
          set boxreg_sys_int=`echo $boxreg_sys 10000 | awk '{print int($1*$2)}'`
          set diffRA_box_trans_int=`echo $diffRA_box_trans 10000 | awk '{print int($1*$2)}'`
          set diffDEC_box_trans_int=`echo $diffDEC_box_trans 10000 | awk '{print int($1*$2)}'`
          echo "RAbox-RAtrans (deg): $diffRA_box_trans" 
          echo "DECbox-DECtrans (deg): $diffDEC_box_trans" 
          echo "Box (deg): $boxreg_sys"
          if ( "$diffRA_box_trans_int" > "$boxreg_sys_int" || "$diffDEC_box_trans_int" > "$boxreg_sys_int" ) then
           echo "$dir0 trans$ntrans is outside of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$degRA_DEC".reg box"
           echo "$dir0 trans$ntrans $newtsts $RA_trans $DEC_trans is outside of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$degRA_DEC".reg box ($boxRA $boxDEC) $INST" >> "$an_dir"/trans_box.txt
           set ctrl_trigger_out=0
          else
           echo "$dir0 trans$ntrans is INSIDE of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$degRA_DEC".reg box"
           echo "$dir0 trans$ntrans $newtsts $RA_trans $DEC_trans is INSIDE of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$degRA_DEC".reg ($boxRA $boxDEC) $INST" >> "$an_dir"/trans_box.txt
           set ctrl_trigger_in=1
          endif
         else
          echo "The time bin ${intervalT} is degenerate in boxRA and boxDEC"
          set N_deg_RA_DEC = 1
          foreach ctrl_deg_RA_DEC (`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | awk '{print $1}'`)
           set INST=`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | awk -v nr=$N_deg_RA_DEC '{ if (NR == nr) print $6}'`
           set boxRA=`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | awk -v nr=$N_deg_RA_DEC '{ if (NR == nr) print $1}'`
           set boxDEC=`grep -h "${newtsts}" ${filter3xmm}/filtered*_res.txt | awk -v nr=$N_deg_RA_DEC '{ if (NR == nr) print $2}'`
           echo "fk5" > $an_dir/bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$N_deg_RA_DEC".reg
           echo "box(${boxRA},${boxDEC},${regionsize}${vir},${regionsize}${vir},0)" >> $an_dir/bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$N_deg_RA_DEC".reg
           cp $an_dir/bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$N_deg_RA_DEC".reg $prod_dirbin
           #check trans in the bayesian box
           echo "Start to check if the transient "$ntrans" is inside of the bayesian box (deg"$N_deg_RA_DEC")"
           set RA_trans=`ftlist "${an_dir}/emllist_trans${ntrans}_partial.fits[col RA]" T rows=1 colheader=no | awk '{print $2}'`
           set DEC_trans=`ftlist "${an_dir}/emllist_trans${ntrans}_partial.fits[col DEC]" T rows=1 colheader=no | awk '{print $2}'`
           set boxreg_sys=`echo ${regionsize} ${region_sys} | awk '{printf("%.4f \n",(($1+$2)/3600))}'`
           set diffRA_box_trans=`echo ${RA_trans} ${boxRA} ${boxDEC} | awk '{printf("%.4f \n",sqrt((cos($3)*($2-$1))^2))}'`
           set diffDEC_box_trans=`echo ${DEC_trans} ${boxDEC} | awk '{printf("%.4f \n",sqrt(($2-$1)^2))}'`
           set boxreg_sys_int=`echo $boxreg_sys 10000 | awk '{print int($1*$2)}'`
           set diffRA_box_trans_int=`echo $diffRA_box_trans 10000 | awk '{print int($1*$2)}'`
           set diffDEC_box_trans_int=`echo $diffDEC_box_trans 10000 | awk '{print int($1*$2)}'`
           echo "RAbox-RAtrans (deg): $diffRA_box_trans" 
           echo "DECbox-DECtrans (deg): $diffDEC_box_trans" 
           echo "Box (deg): $boxreg_sys"
           if ( "$diffRA_box_trans_int" > "$boxreg_sys_int" || "$diffDEC_box_trans_int" > "$boxreg_sys_int" ) then
            echo "$dir0 trans$ntrans (deg"$N_deg_RA_DEC") is outside of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$N_deg_RA_DEC".reg box"
            echo "$dir0 trans$ntrans (deg"$N_deg_RA_DEC") $newtsts $RA_trans $DEC_trans is outside of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$N_deg_RA_DEC".reg box ($boxRA $boxDEC) $INST" >> "$an_dir"/trans_box.txt
            set ctrl_trigger_out=0
           else
            echo "$dir0 trans$ntrans (deg"$N_deg_RA_DEC") is INSIDE of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$N_deg_RA_DEC".reg box"
            echo "$dir0 trans$ntrans (deg"$N_deg_RA_DEC") $newtsts $RA_trans $DEC_trans is INSIDE of the bayesian_box_trans"$ntrans"_int"$N_intervalT"_deg"$N_deg_RA_DEC".reg box ($boxRA $boxDEC) $INST" >> "$an_dir"/trans_box.txt
            set ctrl_trigger_in=1
           endif
          set N_deg_RA_DEC = `expr $N_deg_RA_DEC + 1`
          end
         endif
        endif
        echo "#! /bin/tcsh -f" > $an_dir/implot.csh
        echo "implot device="$dir0"_"$tsts"_trans"$ntrans".PNG/PNG expression='' thickness=3 set="$an_dir"/"$dir0"_1_"$tsts".img srclisttab="$an_dir"/emllist_trans"$ntrans"_partial.fits withsrclisttab=yes -w "$warn" -V "$verb"" >> $an_dir/implot.csh
        source $an_dir/implot.csh
        cp "$an_dir"/"$dir0"_"$tsts"_trans"$ntrans".PNG $prod_dirbin
        rm $an_dir/implot.csh
       else
        echo ""$an_dir"/emllist_trans"$ntrans"_partial.fits does not exist"
       endif
      endif
      if ($ctrl_trigger_out == 0 && $ctrl_trigger_in == 0) then
       set ctrl_trigger=0
      else
       set ctrl_trigger=1
      endif

     ##add columns trans_id and tstart-tstop in the single transient catalogue
      if (-e "$an_dir"/emllist_trans"$ntrans"_partial.fits) then
       fkeypar $an_dir/emllist_trans"$ntrans"_partial.fits+1 NAXIS2
       set trans_rows = `pget fkeypar.par value`
       rm $an_dir/tran.txt
       set col = 1
       while($col <= $trans_rows)
        echo "$dir0 $ntrans $n_timbin $SPclean_flag $ctrl_trigger" >> $an_dir/tran.txt
       set col = ` expr $col + 1`
       end
       echo "OBS_ID 10A" > $an_dir/column.txt
       echo "T_ID I" >> $an_dir/column.txt
       echo "N_TIME_BIN I" >> $an_dir/column.txt
       echo "SPclean_FLAG E" >> $an_dir/column.txt
       echo "TRIGGER_FLAG I" >> $an_dir/column.txt
       echo "fcreate $an_dir/column.txt $an_dir/tran.txt $an_dir/tran.fits clobber=yes" > $an_dir/fcreate.csh
       echo "fcreate $an_dir/column_timbin_tstart.txt $an_dir/timbin_tstart_$ntrans.txt $an_dir/timbin_tstart_$ntrans.fits clobber=yes" >> $an_dir/fcreate.csh
       echo "fcreate $an_dir/column_timbin_tstop.txt $an_dir/timbin_tstop_$ntrans.txt $an_dir/timbin_tstop_$ntrans.fits clobber=yes" >> $an_dir/fcreate.csh
       source $an_dir/fcreate.csh
       rm $an_dir/fcreate.csh
       echo "ftpaste $an_dir/tran.fits+1 $an_dir/timbin_tstart_$ntrans.fits+1 $an_dir/tran_tstart.fits clobber=yes" > $an_dir/ftpaste.csh
       source $an_dir/ftpaste.csh
       echo "ftpaste $an_dir/tran_tstart.fits+1 $an_dir/timbin_tstop_$ntrans.fits+1 $an_dir/tran_tstart_tstop.fits clobber=yes" > $an_dir/ftpaste.csh
       source $an_dir/ftpaste.csh
       echo "ftpaste $an_dir/tran_tstart_tstop.fits+1 $an_dir/emllist_trans"$ntrans"_partial.fits+1 $an_dir/emllist_trans"$ntrans"_partial.fits clobber=yes" > $an_dir/ftpaste.csh
       source $an_dir/ftpaste.csh
       rm $an_dir/ftpaste.csh
       rm $an_dir/tran.fits
       rm $an_dir/tran.txt
       rm $an_dir/column.txt
       rm $an_dir/tran_tstart.fits
       rm $an_dir/tran_tstart_tstop.fits
       rm $an_dir/timbin_tstart_"$ntrans".txt
       rm $an_dir/timbin_tstop_"$ntrans".txt
      endif

      if (-e "$dir0"_1_"$tsts".ds) then
       cp "$dir0"_1_"$tsts".PNG $prod_dirbin/"$dir0"_1_"$tsts"_ALL_trans"$ntrans".PNG 
       cp "$dir0"_1_"$tsts".reg $prod_dirbin/"$dir0"_1_"$tsts"_ALL_trans"$ntrans".reg 
       cp "$dir0"_1_"$tsts".list "$dir0"_1_"$tsts".out $prod_dirbin
       gzip -c "$dir0"_1_"$tsts".bkgimg > $prod_dirbin/"$dir0"_1_"$tsts"_trans"$ntrans".bkgimg.gz
       gzip -c "$dir0"_1_"$tsts".expimg > $prod_dirbin/"$dir0"_1_"$tsts"_trans"$ntrans".expimg.gz
       gzip -c "$dir0"_1_"$tsts".img > $prod_dirbin/"$dir0"_1_"$tsts"_trans"$ntrans".img.gz
      else
       cp "$dir0"_1_"$tsts".PNG $prod_dirbin/"$dir0"_1_"$tsts"_ALL_trans"$ntrans".PNG 
       cp "$dir0"_1_"$tsts".reg $prod_dirbin/"$dir0"_1_"$tsts"_ALL_trans"$ntrans".reg 
       cp "$dir0"_1_"$tsts".list "$dir0"_1_"$tsts".out $prod_dirbin
       gzip -c "$dir0"_1_"$tsts".bkgimg > $prod_dirbin/"$dir0"_1_"$tsts"_trans"$ntrans".bkgimg.gz
       gzip -c "$dir0"_1_"$tsts".expimg > $prod_dirbin/"$dir0"_1_"$tsts"_trans"$ntrans".expimg.gz
       gzip -c "$dir0"_1_"$tsts".img > $prod_dirbin/"$dir0"_1_"$tsts"_trans"$ntrans".img.gz
      endif
     endif
     endif
    set ctrl_trigger_out=0
    set ctrl_trigger_in=0
    set ntrans = ` expr $ntrans + 1`
    end
    if ($type_stringa == "bayesian") then
     cp "$an_dir"/trans_box.txt $prod_dirbin
    endif

    ##final transients catalogue
    echo "Start to make the global catalogue of transients in the observation "$dir0""
    if (-e "$an_dir"/emllist_trans.txt) then
     echo "fmerge infiles=""$etm""$an_dir"/emllist_trans.txt" outfile="$an_dir/"$dir0"_emllist_transient.fits" columns="-" clobber=yes" > $an_dir/fmerge.csh
     source $an_dir/fmerge.csh
     cp "$an_dir"/"$dir0"_emllist_transient.fits $prod_dirbin
     rm $an_dir/fmerge.csh
     rm $an_dir/emllist_trans*_partial.fits
     rm $an_dir/emllist_trans.txt
     rm "$an_dir"/column_timbin_tstart.txt
     rm "$an_dir"/column_timbin_tstop.txt
    else
     echo ""$an_dir"/emllist_trans.txt does not exist"
     set ctrl_no_trans = 1
     echo "WARNING: no transients are detected for the observation $dir0" >> $prod_dir_final/NO_TRANSIENT.txt
    endif
   endif
else
 echo "The file "$an_dir"/"$dir0"_1trans.txt does not exist"
 set ctrl_no_trans = 1
endif
cd $start_dir/
date
echo "stop cat_trans.csh"
