#!/bin/tcsh

####################################################################################################
###                                                                                              ###
###  This is a sample script to correct a 3d+time dataset using a modified RETROICOR routine.    ###
###  It takes as input the original 3d+time dataset, the cardiovascular and respiratory phase    ###
###  information based on Glover, et al. and outputs the dataset corrected on a slice by slice   ###
###  basis.                                                                                      ### 
###                                                                                              ###
###  M.A. Smith										         ###
###  ----------------------------------------------------------------------------	         ###
###  9/15/05: RMB: modified to be script to invoke with command aruments                         ###
###  4/10/07: RMB: modified to remove mean from physio regressors                                ###
###  4/27/07: RMB: modified to find baseline (t^0) BRIK automatically                            ###
#################################################################################################### 

set DO_CLEANUP = 1
set DEBUG = 1
set TMP_FILE = tmp_@RETROICOR_output.txt

###### Command Line ######

echo $argv[1]
echo $argv[2]
echo $argv[3]
echo $argv[4]
echo $argv[5]

if ( ${#argv} != 5 ) then
   echo "Wrong number of arguments specified for @RETROICOR!"
   echo "Usage:"
   echo "   @RETROICOR <card_phase_prefix> <resp_phase_prefix> <in_prefix> <out_prefix> <ignore>"
   echo "      where:"
   echo "      <card_phase_prefix> = Prefix of cardiac physio file (after 1dCRphase) (e.g. card_phase_1.1D)"
   echo "      <resp_phase_prefix> = Prefix of respiration physio file (after 1dCRphase) (e.g. resp_phase_1.1D)"
   echo "      <in_prefix>  = Prefix of input dataset.  The dset to be corrected. "
   echo "      <out_prefix> = Prefix of output dataset.  What you want the corrected dset to be called."
   echo "      <ignore>     = Number of time points to ignore at the beginning."
   exit(-1)
endif

echo "=================================================================="
echo "Thank you for running @RETROICOR."
echo "Please note that outputs of intermediate programs"
echo "will not appear on screen. Therefore, errors may not"
echo "be immediately apparent. Outputs are stored in the file:"
echo "   tmp_@RETROICOR_output.txt"
echo "If you run into problems, check this file for error messages first."
echo "------------------------------------------------------------------"

set tsname       = $argv[1]       			# cardiovascular phase, 1D file
set tsname2      = $argv[2]       			# respiratory phase, 1D file
set Data         = $argv[3]           			# original dataset
set Filename     = $argv[4]           			# prefix for RETROICOR corrected dataset
set ignore       = $argv[5]				# number of timepoints to ignore
#set id           = $argv[6]                             # unique temporary id

echo "------------------------------"
echo "--- Reading File:" $Data

echo "##################################" >>& $TMP_FILE
echo "@RETROICOR script ran on:         " >>& $TMP_FILE
date                                      >>& $TMP_FILE
echo "----------------------------------" >>& $TMP_FILE

if (-e $Data+orig.HEAD ) then
   set Dset_params = `3dAttribute -name TAXIS_NUMS {$Data}+orig`
   set NT = $Dset_params[3]
   @ NT1  = $NT - 1
   
   
   set Dset_params2 = `3dAttribute -name DATASET_DIMENSIONS {$Data}+orig`
   #set NZ = $Dset_params[4]
   set NZ = $Dset_params2[5]
   if ($NZ < 1 ) then
      set NZ = 1
   endif
   @ NZ2  = $NZ - 1

   echo "--- NT:" $NT
   echo "--- NZ:" $NZ
else
   echo "Cannot find" {$Data}"+orig.HEAD"
   exit(-1)
endif



########### Do modified RETROICOR correction #################
set LL = ""
set LL2 = ""

foreach nz (`count 0 {$NZ2}`)

   echo "----------------------------"
   echo "---Processing slice: " $nz
    
   1deval -a {$tsname}.1D'['{$nz}']' -expr 'sin(a)' > tmp_{$tsname}_sin_{$nz}.1D 
   1deval -a {$tsname}.1D'['{$nz}']' -expr 'cos(a)' > tmp_{$tsname}_cos_{$nz}.1D
   1deval -a {$tsname}.1D'['{$nz}']' -expr 'sin(2*a)' > tmp_{$tsname}_sin2_{$nz}.1D
   1deval -a {$tsname}.1D'['{$nz}']' -expr 'cos(2*a)' > tmp_{$tsname}_cos2_{$nz}.1D
   
   1deval -a {$tsname2}.1D'['{$nz}']' -expr 'sin(a)' > tmp_{$tsname2}_sin_{$nz}.1D 
   1deval -a {$tsname2}.1D'['{$nz}']' -expr 'cos(a)' > tmp_{$tsname2}_cos_{$nz}.1D
   1deval -a {$tsname2}.1D'['{$nz}']' -expr 'sin(2*a)' > tmp_{$tsname2}_sin2_{$nz}.1D
   1deval -a {$tsname2}.1D'['{$nz}']' -expr 'cos(2*a)' > tmp_{$tsname2}_cos2_{$nz}.1D
      
   #--- Compute mean for each regressor and subtract
   #foreach p ($tsname $tsname2)
   #   foreach reg (sin cos sin2 cos2)
   #      set meanval = `1dsum tmp_{$p}_{$reg}_{$nz}.1D`
   #	 1deval -a tmp_{$p}_{$reg}_{$nz}.1D -expr "a-$meanval" > tmp_s_{$p}_{$reg}_{$nz}.1D
   #   end
   #end
   
    
   
   #echo "Cutup start..."
   
   3dZcutup \
      -keep {$nz} {$nz} \
      -prefix tmp_{$Data}_{$nz} \
      {$Data}+orig >>& $TMP_FILE
 
 
   #echo "...end"
   	

   3dDeconvolve \
	 -input tmp_{$Data}_{$nz}+orig \
	 -nfirst {$ignore} \
	 -bout \
	 -num_stimts 8 \
	 -stim_file 1 tmp_{$tsname}_sin_{$nz}.1D \
	 -stim_file 2 tmp_{$tsname}_cos_{$nz}.1D \
	 -stim_file 3 tmp_{$tsname}_sin2_{$nz}.1D \
	 -stim_file 4 tmp_{$tsname}_cos2_{$nz}.1D \
	 -stim_file 5 tmp_{$tsname2}_sin_{$nz}.1D \
	 -stim_file 6 tmp_{$tsname2}_cos_{$nz}.1D \
	 -stim_file 7 tmp_{$tsname2}_sin2_{$nz}.1D \
	 -stim_file 8 tmp_{$tsname2}_cos2_{$nz}.1D \
	 -tout -fout \
	 -errts tmp_{$Data}_corx_{$nz} \
	 -bucket tmp_Fit_{$Filename}_{$nz}  >>& $TMP_FILE

      #---- Find baseline BRIK
      set base_indx_1 = `3dinfo tmp_Fit_{$Filename}_{$nz}+orig | grep "Pol#0_Coef" | awk '{print substr($4,2)}'`
      #---- check to see if this is really a number.  set to null if not."
      set base_indx = `echo $base_indx_1 | awk '(( $1 + 0 ) == $1) {print $1}'`
      
      if ($base_indx == "" ) then
         echo "---Base Index was not found.  Set to zero by default."
	 set base_indx = 0
      endif
      
      if ($DEBUG != 0 ) then
         echo "---Base Index set to: $base_indx"
      endif
      
      3dcalc \
        -a tmp_Fit_{$Filename}_{$nz}+orig'['$base_indx']' \
	-b tmp_{$Data}_corx_{$nz}+orig \
	-expr 'a+b' \
	-prefix tmp_{$Filename}_{$nz}	>>& $TMP_FILE

   set LL = "$LL tmp_{$Filename}_{$nz}+orig.BRIK"
   #set LL2 = "$LL tmp_Fit_{$Filename}_{$nz}+orig.BRIK"
   
end

if ( $NZ2 != 0) then

   3dZcat \
      -prefix {$Filename} \
      $LL

   #3dZcat \
   #   -prefix Fit_{$Filename} \
   #   $LL2

else

    3dcalc -a tmp_{$Filename}_0000+orig -expr 'a' -prefix {$Filename}

endif

#--- KEEP FOR NOW ---#
if ($DO_CLEANUP == 1) then
   rm -f tmp_{$tsname}_sin_*.1D
   rm -f tmp_{$tsname}_cos_*.1D
   rm -f tmp_{$tsname}_sin2_*.1D
   rm -f tmp_{$tsname}_cos2_*.1D
   rm -f tmp_{$tsname2}_sin_*.1D
   rm -f tmp_{$tsname2}_cos_*.1D
   rm -f tmp_{$tsname2}_sin2_*.1D
   rm -f tmp_{$tsname2}_cos2_*.1D
   rm -f tmp_Fit_{$Filename}_*
   rm -f tmp_{$Filename}_*
   rm -f tmp_{$Data}_*
endif
