#!/bin/tcsh -f

set CurDir = $PWD

if ("$1" == '' || "$1" == '-h' || "$1" == '-help' || "$2" == '') then
	goto USAGE
endif

goto PARSE_COMMAND
Ret_PARSE_COMMAND:

goto CHECK_PROGRAMS
Ret_CHECK_PROGRAMS:

goto SET_VARIABLES
Ret_SET_VARIABLES:

goto CHECK_EXISTENCE
Ret_CHECK_EXISTENCE:

goto DOWNSAMPLE
Ret_DOWNSAMPLE:

goto STRIP_EXP_VOL
Ret_STRIP_EXP_VOL:

goto ALIGN_CENTERS
Ret_ALIGN_CENTERS:

goto RESAMPLE
Ret_RESAMPLE:

goto REGISTER
Ret_REGISTER:

echo "Done."
goto END


PARSE_COMMAND:
	
   #continue parsing for new options
   set followers = ()
   set alli_opt = ""
   set skstr_opt = ""
   set folinterp = NN
   set cleanup = 1
   set Narg = $#
   set cnt = 1
   set cropt = '-coarserot'
   set prefix = ''
   set UseWarp = 0
   set clpbelow = ''
   set SA_in = ''
   set EA_in = ''
   set DownSample = 0
   set StripSkull = 0
   set okchangeview = 0
   set no_center = 1;	
   set OutResOpt = ""
   while ($cnt <= $Narg)
		set donext = 1;
      if ($donext && "$argv[$cnt]" == "-dxyz") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need value after -dxyz"
            goto END
			else
            @ cnt ++
            set DownSample = "$argv[$cnt]"
            if ( ! `ccalc -i "ispositive($DownSample - 0.3)"` || \
                 ! `ccalc -i "ispositive(4 - $DownSample)"` ) then
               echo "Error: Bad value for dxyz ($argv[$cnt])"
               echo ""
               goto END
            endif
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-out_dxyz") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need value after -out_dxyz"
            goto END
			else
            @ cnt ++
            set OutResOpt = "$argv[$cnt]"
            if ( ! `ccalc -i "ispositive($OutResOpt - 0.1)"` || \
                 ! `ccalc -i "ispositive(4 - $OutResOpt)"` ) then
               echo "Error: Bad value for out_dxyz ($argv[$cnt])"
               echo ""
               goto END
            endif
            set OutResOpt = "-mast_dxyz $OutResOpt "
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-EA_clip_below") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need Zmm after -EA_clip_below"
            goto END
			else
            @ cnt ++
            set clpbelow = "$argv[$cnt]"
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-prefix") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need a string after -prefix"
            goto END
			else
            @ cnt ++
            set prefix = `@GetAfniPrefix "$argv[$cnt]"`
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-surf_anat") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need a volume after -surf_anat"
            goto END
			else
            @ cnt ++
            set SA_in = "$argv[$cnt]"
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-exp_anat") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need a volume after -exp_anat"
            goto END
			else
            @ cnt ++
            set EA_in = "$argv[$cnt]"
            set donext = 0	
         endif	
      endif
     
      if ($donext && "$argv[$cnt]" == "-wd") then
         set UseWarp = 1;		
         set donext = 0		
      endif
      
      if ($donext && "$argv[$cnt]" == "-al") then
         set UseWarp = 2;		
         set donext = 0		
      endif
      
      if ($donext && "$argv[$cnt]" == "-al_opt") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need parameter(s) after -al_opt"
            goto END
			else
            @ cnt ++
            set alli_opt = "$argv[$cnt]"		
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-skull_strip_opt") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need parameter(s) after -skull_strip_opt"
            goto END
			else
            @ cnt ++
            set skstr_opt = "$argv[$cnt]"		
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-align_centers") then
         set no_center = 0;		
         set donext = 0		
      endif
      
      if ($donext && "$argv[$cnt]" == "-ok_change_view") then
         set okchangeview = 1;		
         set donext = 0		
      endif
      
      if ($donext && "$argv[$cnt]" == "-strip_skull") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need a parameter after -strip_skull"
            goto END
			else
            @ cnt ++
            if ("$argv[$cnt]" == "exp_anat") then
               set StripSkull = 1;
            else if ("$argv[$cnt]" == "both") then
               set StripSkull = 3;
            else if ("$argv[$cnt]" == "surf_anat") then
               set StripSkull = 2;
            else
               echo "Acceptable options for -strip_skull are:"
               echo "'exp_anat' or 'surf_anat' or 'both'"
               goto END
            endif
        endif		
        set donext = 0		
      endif
      
      if ($donext && "$argv[$cnt]" == "-surf_anat_followers") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need at least a volume after -surf_anat_followers"
            goto END
			else
            @ cnt ++
            set followers = ($argv[$cnt-])
            foreach fol ($followers)
               set exx = `@CheckForAfniDset $fol`
               if ( $status) then
                  echo "Error follower dset $fol cannot be found"
                  echo "Note that option -surf_anat_followers must be "
                  echo "the last one on the command line"
                  goto END
               endif
               if ( $exx < 2) then
                  echo "Error follower dset $fol appears not to be a dset"
                  echo "Note that option -surf_anat_followers must be "
                  echo "the last one on the command line"
                  goto END
               endif
            end
            set cnt = `expr $cnt + $#followers - 1`
            set donext = 0	
         endif	
      endif
      
      if ($donext && "$argv[$cnt]" == "-followers_interp") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need an interpolation kernel after -followers_interp"
            goto END
			else
            @ cnt ++
            set folinterp = $argv[$cnt]
            if (  $folinterp != NN  && \
                  $folinterp != linear  && \
                  $folinterp != cubic  && \
                  $folinterp != quintic  ) then
               echo "Interpolation kernel $folinterp is not recognized"
               echo "Choose one of: NN, linear, cubic, or quintic"
               echo ""
               goto END
            endif
         endif
         set donext = 0		
      endif
          
      if ($donext && "$argv[$cnt]" == "-ncr") then
         set cropt = '';		
         set donext = 0		
      endif
      
      if ($donext && "$argv[$cnt]" == "-keep_tmp") then
         set cleanup = 0;		
         set donext = 0		
      endif
      
      #ADD NO NEW OPTIONS BELOW THIS LINE
      
      if ($donext == 1 && $cnt == 1) then
	      set EA_in = "$argv[$cnt]"
         echo "Note: Guessing that '$EA_in' is the experiment anatomy."
         echo "Better use -exp_anat flag in your command."
	      echo ""
         set donext = 0
      endif      
      
      if ($donext == 1 && $cnt == 2) then
         set SA_in = "$argv[$cnt]"
         echo ""
         echo "Note: Guessing that '$SA_in' is the surface anatomy."
         echo "Better use -surf_anat flag in your command."
	      echo ""
         set donext = 0
      endif         

      if ($donext == 1 && $cnt == 3) then
         #probably the dxyz parameter
         set DownSample = $argv[$cnt]
         if ("$DownSample" =~ *[^0-9]*) then
            echo "Error: Option '$argv[$cnt]' not understood"
            echo ""
            goto END
         endif
         if ($DownSample < 0.3 || $DownSample > 4) then
            echo "Error: Option '$argv[$cnt]' not understood"
            echo ""
            goto END
         endif
         set donext = 0
      endif
      if ($donext == 1) then
         echo "Error: Option or parameter '$argv[$cnt]' not understood"
         goto END
      endif
      
		@ cnt ++
	end
   
   if ("$SA_in" == "" || "$EA_in" == "") then 
      echo "Error: Failed to find surface and/or experiment anatomies on command line."
      goto END
   else
         set ExpAnatPrefix = `@GetAfniPrefix $EA_in`
	      set ExpAnatView = `@GetAfniView $EA_in`
	      set SurfAnatPrefix = `@GetAfniPrefix $SA_in` 
         set SurfAnatView = `@GetAfniView $SA_in` 
	      set SurfAnatPath = $SA_in:h
	      if ($SurfAnatPath == $SA_in:t) then 
		      #no path given
		      set SurfAnatPath = .
	      endif
   endif
   
	goto Ret_PARSE_COMMAND

SET_VARIABLES:
	set ExpAnat = $ExpAnatPrefix$ExpAnatView
	set SurfAnat = $SurfAnatPrefix$SurfAnatView
	set Resampled = 0 #flag set when resampling is done
	set SkullStripped = 0
   goto Ret_SET_VARIABLES


DOWNSAMPLE:
	set Skip = 0
	if ($DownSample != 0) then
		echo "Downsampling ..."
		cd $SurfAnatPath
		set tmpPrefix = $SurfAnatPrefix"_"$DownSample"mm"
		if (-f $tmpPrefix$SurfAnatView.BRIK) then
			echo ""
			echo "Warning: $tmpPrefix$SurfAnatView exists in $SurfAnatPath"
			echo "Enter O/S/Q to Overwrite/Skip/Quit:"
			set sel = $<
			if ("$sel" == 'O' || "$sel" == 'o') then
				rm -f $tmpPrefix$SurfAnatView.BRIK $tmpPrefix$SurfAnatView.HEAD
			endif
			if ("$sel" == 'S' || "$sel" == 's') then
				echo "Skipping downsampling, existing data set $DownSample will be used"
				set Skip = 1
			endif
			if ("$sel" == 'Q' || "$sel" == 'q') then
				echo "Quitting ..."
				goto END
			endif
			echo ""
		endif
		if ($Skip == 0) then
			echo "running: adwarp -force -prefix $tmpPrefix -apar $SurfAnat -dpar $SurfAnat -dxyz $DownSample -resam Cu"
			adwarp -force -prefix $tmpPrefix -apar $SurfAnat -dpar $SurfAnat -dxyz $DownSample -resam Cu
			if(!(-f $tmpPrefix$SurfAnatView.BRIK || -f $tmpPrefix$SurfAnatView.BRIK.gz || -f $tmpPrefix$SurfAnatView.BRIK.Z || -f $tmpPrefix$SurfAnatView.BRIK.bz2 )) then
				goto NO_DOWNGOOD_BADBAD
			endif
			
		endif
		set SurfAnatPrefix = $tmpPrefix
		set SurfAnat = $SurfAnatPrefix$SurfAnatView
		cd $CurDir
	endif
	goto Ret_DOWNSAMPLE

STRIP_EXP_VOL:
   #strip skull off of EXP_VOL
   set Skip = 0
   cd $CurDir
   if ($StripSkull == 1 || $StripSkull == 3 ) then
      set ExpAnat_NoSkullPrefix = $ExpAnatPrefix"_ns"
      set ExpAnat_NoSkull = $ExpAnatPrefix"_ns"$ExpAnatView
      echo "Stripping exp vol ..."
      if (`@CheckForAfniDset $ExpAnat_NoSkull` > 0) then
         echo ""
		   echo "Warning: $ExpAnat_NoSkull exists in $CurDir"
		   echo "Enter O/S/Q to Overwrite/Skip/Quit:"
		   set sel = $<
		   if ("$sel" == 'O' || "$sel" == 'o') then
			   rm -f $ExpAnat_NoSkull.BRIK* $ExpAnat_NoSkull.HEAD
		   endif
		   if ("$sel" == 'S' || "$sel" == 's') then
			   echo "Skipping stripping, existing data set "
            echo " $ExpAnat_NoSkull will be used"
			   set Skip = 1
		   endif
		   if ("$sel" == 'Q' || "$sel" == 'q') then
			   echo "Quitting ..."
			   goto END
		   endif
		   echo ""
	   endif
      if ($Skip == 0) then
         3dSkullStrip -input $ExpAnat -prefix $ExpAnat_NoSkull $skstr_opt
         if (`@CheckForAfniDset $ExpAnat_NoSkull` < 2) then
            goto NO_SS
         endif
      endif
      set ExpAnatPrefix = $ExpAnat_NoSkullPrefix
	   set ExpAnat = $ExpAnat_NoSkull
	   set SkullStripped = 1
   endif
	if ($StripSkull == 2 || $StripSkull == 3 ) then
      set Skip = 0
      set SurfAnat_NoSkullPrefix = $SurfAnatPrefix"_ns"
      set SurfAnat_NoSkull = $SurfAnatPrefix"_ns"$SurfAnatView
      echo "Stripping surf vol ..."
      if (`@CheckForAfniDset $SurfAnatPath/$SurfAnat_NoSkull` > 0) then
         echo ""
		   echo "Warning: $SurfAnatPath/$SurfAnat_NoSkull exists in $CurDir"
		   echo "Enter O/S/Q to Overwrite/Skip/Quit:"
		   set sel = $<
		   if ("$sel" == 'O' || "$sel" == 'o') then
			   rm -f $SurfAnatPath/$SurfAnat_NoSkull.BRIK* $SurfAnatPath/$SurfAnat_NoSkull.HEAD
		   endif
		   if ("$sel" == 'S' || "$sel" == 's') then
			   echo "Skipping stripping, existing data set $SurfAnatPath/$SurfAnat_NoSkull will be used"
			   set Skip = 1
		   endif
		   if ("$sel" == 'Q' || "$sel" == 'q') then
			   echo "Quitting ..."
			   goto END
		   endif
		   echo ""
	   endif
      if ($Skip == 0) then
         3dSkullStrip -input $SurfAnatPath/$SurfAnat -prefix $SurfAnatPath/$SurfAnat_NoSkull $skstr_opt
         if (`@CheckForAfniDset $SurfAnatPath/$SurfAnat_NoSkull` < 2) then
            goto NO_SS
         endif
      endif
      set SurfAnatOri = $SurfAnat
      set SurfAnatPrefix = $SurfAnat_NoSkullPrefix
	   set SurfAnat = $SurfAnat_NoSkull
	   set SkullStripped = 2
   endif
   goto Ret_STRIP_EXP_VOL

ALIGN_CENTERS:
   if ($no_center == 0) then
      echo "Calculating center shift..."
      rm -f $ExpAnatPrefix"_shft$ExpAnatView."* >& /dev/null
      @Align_Centers -base $SurfAnatPath/$SurfAnat.HEAD \
                     -dset $ExpAnat.HEAD 
      set mpref = $ExpAnatPrefix
      set center_mat = $mpref"_shft.1D"
      if ( ! -f $center_mat) then
         echo "Failed to create shift matrix"
         goto END
      endif
      set ExpAnatPrefixOrig = $ExpAnatPrefix
      set ExpAnatPrefix = $ExpAnatPrefixOrig"_shft"
      set ExpAnatOrig = $ExpAnat
      set ExpAnat = $ExpAnatPrefix$ExpAnatView
   else
      #Nothing really...
      set ExpAnatOrig = $ExpAnat
      set ExpAnatPrefixOrig = $ExpAnatPrefix
   endif
   goto Ret_ALIGN_CENTERS
   
RESAMPLE:
	#resample Experiment volume to look like SurfAnat
	set Skip = 0
	cd $CurDir
	set ExpAnat_ResampPrefix = $ExpAnatPrefix"_resamp_"$clpbelow
	set ExpAnat_Resamp = $ExpAnat_ResampPrefix$SurfAnatView
	echo ""
	echo "resampling $ExpAnat to match $SurfAnatPath/$SurfAnat"
	if (`@CheckForAfniDset  $ExpAnat_Resamp.BRIK` > 0) then
		echo ""
		echo "Warning: $ExpAnat_Resamp exists in $CurDir"
		echo "Enter O/S/Q to Overwrite/Skip/Quit:"
		set sel = $<
		if ("$sel" == 'O' || "$sel" == 'o') then
			rm -f $ExpAnat_Resamp.BRIK* $ExpAnat_Resamp.HEAD
		endif
		if ("$sel" == 'S' || "$sel" == 's') then
			echo "Skipping resampling, existing data set $ExpAnat_Resamp will be used"
			set Skip = 1
		endif
		if ("$sel" == 'Q' || "$sel" == 'q') then
			echo "Quitting ..."
			goto END
		endif
		echo ""
	endif
	if ($Skip == 0) then
      set tmpref = '___tmp__rs'"$ExpAnat_ResampPrefix"
		if ($clpbelow != '') then
         rm -rf ${tmpref}*.???? >& /dev/null
         @clip_volume -below $clpbelow -input $ExpAnat -prefix $tmpref
         set nxt = "$tmpref""$ExpAnatView"
         if (!(-f $nxt.BRIK || -f $nxt.BRIK.gz || -f $nxt.BRIK.Z || -f $nxt.BRIK.bz2)) then 
			   goto NO_RESAMP
		   endif
      else   
         set nxt = "$ExpAnat"
      endif
      echo "3dresample -master $SurfAnatPath/$SurfAnat -prefix $ExpAnat_ResampPrefix -rmode Cu -inset $nxt"
		echo ""
		3dresample -master $SurfAnatPath/$SurfAnat -prefix $ExpAnat_ResampPrefix -rmode Cu -inset $nxt
		if (!(-f $ExpAnat_Resamp.BRIK || -f $ExpAnat_Resamp.BRIK.gz || -f $ExpAnat_Resamp.BRIK.Z || -f $ExpAnat_Resamp.BRIK.bz2)) then 
			goto NO_RESAMP
		endif
      rm -rf ${tmpref}*.???? >& /dev/null
	endif
	set ExpAnatPrefix = $ExpAnat_ResampPrefix
	set ExpAnat = $ExpAnat_Resamp
	set Resampled = 1
	goto Ret_RESAMPLE
	
REGISTER:
	cd $CurDir
	if ($prefix == '') then
      set VolRegPrefix = $SurfAnatPrefix"_Alnd_Exp"
	else
      set VolRegPrefix = $prefix
   endif
   echo ""
	if (-f $VolRegPrefix$SurfAnatView.BRIK) then
		echo ""
		echo "Warning: $VolRegPrefix$SurfAnatView exists in $CurDir"
		echo "Enter O/Q to Overwrite/Quit:"
		set sel = $<
		if ("$sel" == 'O' || "$sel" == 'o') then
			rm -f $VolRegPrefix$SurfAnatView.BRIK $VolRegPrefix$SurfAnatView.HEAD
		endif
		if ("$sel" == 'Q' || "$sel" == 'q') then
			echo "Quitting ..."
			goto END
		endif
		echo ""
	endif
	
   echo "Registering $SurfAnatPath/$SurfAnat to $ExpAnat"
	if ($UseWarp == 0) then
	   echo "3dvolreg -wtrim -clipit -twopass -twodup -zpad 8 \"
      echo "         -rotcom -verbose -base $ExpAnat \"
      echo "         -prefix $VolRegPrefix $SurfAnatPath/$SurfAnat"
	   echo ""
	   if ( -f ${VolRegPrefix}.A2E.1D) rm -f ${VolRegPrefix}.A2E.1D 
      3dvolreg -wtrim -clipit -twopass \
               -twodup -zpad 8 -rotcom \
               -verbose -base $ExpAnat \
               -1Dmatrix_save  ${VolRegPrefix}.A2E.1D \
               -prefix $VolRegPrefix \
               -cubic   \
               $SurfAnatPath/$SurfAnat
	   if ( ! ( -f $SurfAnatPath/$VolRegPrefix$SurfAnatView.BRIK || \
               -f $SurfAnatPath/$VolRegPrefix$SurfAnatView.BRIK.gz || \
               -f $SurfAnatPath/$VolRegPrefix$SurfAnatView.BRIK.Z || \
               -f $SurfAnatPath/$VolRegPrefix$SurfAnatView.BRIK.bz2)) then
		   echo "Failed to find $SurfAnatPath/$VolRegPrefix$SurfAnatView"
         goto NO_VOLREG
	   endif
      #differing views?
	   mv $SurfAnatPath/$VolRegPrefix* ./
      if ("$SurfAnatView" != "$ExpAnatView") then
         echo "Changing view from $SurfAnatView to $ExpAnatView."
         if ($okchangeview == 0) then
            echo "Note that only rigid-body registration was used here."
            echo "So change of view may not be appropriate." 
         endif
         3drefit -view $ExpAnatView $VolRegPrefix$SurfAnatView
         set fview = $ExpAnatView
      else
         set fview = $SurfAnatView
      endif
   else if ($UseWarp == 1) then      
      set tmpref = '___tmp__zp'"$ExpAnatPrefix$SurfAnatPrefix"
      rm -rf ${tmpref}*.???? >& /dev/null
      set pd = 8
      
      echo "3dZeropad -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \"
      echo "          -mm -prefix ./${tmpref}_pad $SurfAnatPath/$SurfAnat"
      echo ""
      
      3dZeropad   -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \
                  -mm -prefix ./${tmpref}_pad $SurfAnatPath/$SurfAnat
      3dZeropad   -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \
                  -mm -prefix ./${tmpref}_refpad $ExpAnat
      if ( -f ${VolRegPrefix}.A2E.1D) rm -f ${VolRegPrefix}.A2E.1D 
      3dWarpDrive $cropt -twopass -verb -affine_general \
                  -cubic -final quintic \
                  -1Dmatrix_save ${VolRegPrefix}.A2E.1D \
                  -base ./${tmpref}_refpad$SurfAnatView \
                  -prefix ./${tmpref}_pad_wd ./${tmpref}_pad$SurfAnatView
	   if ($StripSkull >= 2) then
         #Have to apply same transform to original SurfAnat
         3dZeropad   -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \
                     -mm \
                     -prefix ./${tmpref}_padori $SurfAnatPath/$SurfAnatOri
         3dWarp   -matparent ./${tmpref}_pad_wd$SurfAnatView \
                  -quintic \
                  -prefix ./${tmpref}_pad_wdori ./${tmpref}_padori$SurfAnatView
         set wdnext = ${tmpref}_pad_wdori  
      else
         set wdnext = ${tmpref}_pad_wd   
      endif
      
      3dZeropad   -I -$pd -S -$pd -A -$pd -P -$pd -L -$pd -R -$pd \
                  -mm \
                  -prefix ./$VolRegPrefix ${wdnext}$SurfAnatView
	   #copy the WARPDRIVE_MATVEC_ fields to the zero unpadded dude
      3drefit  -atrcopy ${wdnext}$SurfAnatView \
               WARPDRIVE_INPUT_IDCODE $VolRegPrefix$SurfAnatView
      3drefit  -atrcopy ${wdnext}$SurfAnatView \
               WARPDRIVE_INPUT_NAME $VolRegPrefix$SurfAnatView
      3drefit  -atrcopy ${wdnext}$SurfAnatView \
               WARPDRIVE_BASE_IDCODE $VolRegPrefix$SurfAnatView
      3drefit  -atrcopy ${wdnext}$SurfAnatView \
               WARPDRIVE_MATVEC_FOR_000000 $VolRegPrefix$SurfAnatView
      3drefit  -atrcopy ${wdnext}$SurfAnatView \
               WARPDRIVE_MATVEC_INV_000000 $VolRegPrefix$SurfAnatView
      #differing views?
      if ("$SurfAnatView" != "$ExpAnatView") then
         echo "Changing view from $SurfAnatView to $ExpAnatView."
         3drefit -view $ExpAnatView $VolRegPrefix$SurfAnatView
         set fview = $ExpAnatView
      else
         set fview = $SurfAnatView
      endif
      if ( ! ( -f ./$VolRegPrefix$fview.BRIK || \
               -f ./$VolRegPrefix$fview.BRIK.gz || \
               -f ./$VolRegPrefix$fview.BRIK.Z || \
               -f ./$VolRegPrefix$fview.BRIK.bz2)) then
		   goto NO_WARPDRIVE
	   endif
      if ($cleanup == 1) then
         rm -rf ${tmpref}*.???? ${tmpref}*.????.* >& /dev/null
      endif
   else
      set tmpref = '___tmp__zp'"$ExpAnatPrefix$SurfAnatPrefix"
      rm -rf ${tmpref}*.???? >& /dev/null
      set pd = 8
      
      echo "3dZeropad -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \"
      echo "          -mm -prefix ./${tmpref}_pad $SurfAnatPath/$SurfAnat"
      echo ""
      
      3dZeropad   -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \
                  -mm -prefix ./${tmpref}_pad $SurfAnatPath/$SurfAnat
      3dZeropad   -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \
                  -mm -prefix ./${tmpref}_refpad $ExpAnat
      if ( -f ${VolRegPrefix}.A2E.1D) rm -f ${VolRegPrefix}.A2E.1D 
      3dAllineate -twopass -verb -warp affine_general \
                  -cubic -final quintic \
                  -1Dmatrix_save ${VolRegPrefix}.A2E.1D \
                  -base ./${tmpref}_refpad$SurfAnatView \
                  -cost lpa   \
                  -prefix ./${tmpref}_pad_al ./${tmpref}_pad$SurfAnatView  \
                  $alli_opt   
	   if ($StripSkull >= 2) then
         #Have to apply same transform to original SurfAnat
         3dZeropad   -I $pd -S $pd -A $pd -P $pd -L $pd -R $pd \
                     -mm \
                     -prefix ./${tmpref}_padori $SurfAnatPath/$SurfAnatOri
         3dAllineate -1Dmatrix_apply ${VolRegPrefix}.A2E.1D \
            -input ./${tmpref}_padori$SurfAnatView \
            -prefix ./${tmpref}_pad_alori  \
            -overwrite  \
            -final quintic
         set wdnext = ${tmpref}_pad_alori  
      else
         set wdnext = ${tmpref}_pad_al   
      endif
      
      3dZeropad   -I -$pd -S -$pd -A -$pd -P -$pd -L -$pd -R -$pd \
                  -mm \
                  -prefix ./$VolRegPrefix ${wdnext}$SurfAnatView
	   #copy the WARPDRIVE_MATVEC_ fields to the zero unpadded dude
      3drefit  -atrcopy ${wdnext}$SurfAnatView \
               ALLINEATE_MATVEC_B2S_000000 $VolRegPrefix$SurfAnatView
      3drefit  -atrcopy ${wdnext}$SurfAnatView \
               ALLINEATE_MATVEC_S2B_000000 $VolRegPrefix$SurfAnatView
      #differing views?
      if ("$SurfAnatView" != "$ExpAnatView") then
         echo "Changing view from $SurfAnatView to $ExpAnatView."
         3drefit -view $ExpAnatView $VolRegPrefix$SurfAnatView
         set fview = $ExpAnatView
      else
         set fview = $SurfAnatView
      endif
      if ( ! ( -f ./$VolRegPrefix$fview.BRIK || \
               -f ./$VolRegPrefix$fview.BRIK.gz || \
               -f ./$VolRegPrefix$fview.BRIK.Z || \
               -f ./$VolRegPrefix$fview.BRIK.bz2)) then
		   goto NO_WARPDRIVE
	   endif
      if ($cleanup == 1) then
         rm -rf ${tmpref}*.???? ${tmpref}*.????.* >& /dev/null
      endif   
   endif
	
	#If have center shift, combine and reapply
   if ($no_center == 0) then
      echo "Combining xform with shift..."
      mv ${VolRegPrefix}.A2E.1D ${VolRegPrefix}".A2E_shft".1D
      cat_matvec -ONELINE $center_mat -I ${VolRegPrefix}".A2E_shft".1D \
         > ${VolRegPrefix}.A2E.1D 
      #cat_matvec -ONELINE ${VolRegPrefix}".A2E_shft".1D $center_mat \
      #  > ${VolRegPrefix}.A2E.1D 
      #set echo
      3dAllineate -master $ExpAnatOrig \
            -1Dmatrix_apply ${VolRegPrefix}.A2E.1D \
            -input $SurfAnatPath/$SurfAnat \
            -prefix ./${VolRegPrefix}$fview  \
            -overwrite  \
            $OutResOpt  \
            -final quintic
   else  
      if ("$OutResOpt" != "") then
         #Reproduce output with 3dAllineate, when no shifting is needed.
         set echo
         3dAllineate -master $ExpAnatOrig \
               -1Dmatrix_apply ${VolRegPrefix}.A2E.1D \
               -input $SurfAnatPath/$SurfAnat \
               -prefix ./${VolRegPrefix}$fview  \
               -overwrite  \
               $OutResOpt  \
               -final quintic
      endif
   endif
      
FOLLOWERS:
   #If you have follower dsets, do them here
   if ($#followers) then
      foreach fol ($followers)
         set folPrefix = `@GetAfniPrefix $fol`
         echo "Applying same transform to $folPrefix..."
         #set echo
         3dAllineate -master $ExpAnatOrig \
               -1Dmatrix_apply ${VolRegPrefix}.A2E.1D \
               -input $fol \
               -prefix ./${folPrefix:r}"_Alnd_Exp"$fview  \
               -overwrite  \
               -final $folinterp
      end
   endif
   
	#remove _resamp_
	if ($Resampled == 1 && $cleanup == 1) then
		echo "removing temporary bricks ..."
		rm -f $ExpAnat_Resamp".HEAD"
		rm -f $ExpAnat_Resamp".BRIK"
      if ($no_center == 0) then
         rm -f $ExpAnatPrefixOrig"_shft"$ExpAnatView"."* >& /dev/null
         rm -f ${VolRegPrefix}".A2E_shft".1D >& /dev/null
      endif
	endif
   
   #add a history note
   3dNotes -h "`basename $0` $argv[*]" $VolRegPrefix$fview
   
	goto Ret_REGISTER

CHECK_EXISTENCE:
	if (`@CheckForAfniDset $ExpAnat` < 2) goto NO_EXPANAT
   
   #if (!(-f $ExpAnat.HEAD || -f $ExpAnat)) goto NO_EXPANAT
	#if (!(-f $ExpAnat.BRIK || -f $ExpAnat.BRIK.gz || -f $ExpAnat.BRIK.Z || -f $ExpAnat.BRIK.bz2)) then
	#	goto NO_EXPANAT
	#endif

	if (`@CheckForAfniDset $SurfAnatPath/$SurfAnat` < 2) goto NO_SURFANAT
	
   #test -f $SurfAnatPath/$SurfAnat.HEAD || goto NO_SURFANAT
	#if (!(-f $SurfAnatPath/$SurfAnat.BRIK || -f $SurfAnatPath/$SurfAnat.BRIK.gz || -f $SurfAnatPath/$SurfAnat.BRIK.Z || -f $SurfAnatPath/$SurfAnat.BRIK.bz2)) then
	#	goto NO_SURFANAT
	#endif
   
   if ($no_center) then
      #check for large center difference
      set dist_cent = `@Center_Distance -dset $ExpAnat.HEAD $SurfAnatPath/$SurfAnat.HEAD`
      set ishuge = `ccalc -form int -eval "step($dist_cent - 80)"`
      set isbig = `ccalc -form int -eval "step($dist_cent - 30)"`
      if ($isbig) then
         echo ""
         echo "*********** Warning *************"
         echo "Dataset centers are $dist_cent mm"
         echo "apart. If registration fails, try"
         echo "adding option -align_centers"
         #echo "recentering all the input data using" /**** The olde WAY ****/
         #echo "@Align_Centers -base $SurfAnatPath/$SurfAnat.HEAD -dset $ExpAnat.HEAD -child CHILDREN"
         #echo "and rerun `basename $0` using the shifted dset"
         #echo "See @Align_Centers for more help."
         #echo "*********************************"
         if ($ishuge) then
            echo ""
            echo "Hit Enter to proceed or ctrl+c to quit."
            echo ""
            set junk = $<
         endif
      else
         echo "Center distance of $dist_cent mm"   
      endif 
      set center_mat = ''
   else
      #Center shifting is best done after skull stripping, if any is needed  
   endif
     
	goto Ret_CHECK_EXISTENCE

CHECK_PROGRAMS:
	 set failed_pgms = 0
    foreach test_command ( 3dvolreg adwarp @GetAfniView @GetAfniPrefix )
		(which $test_command) >& /dev/null

		if ( $status ) then
	   	 echo "program not found in path: $test_command"
	   	 @ failed_pgms ++
		endif
    end

    if ( $failed_pgms ) then
		echo "$failed_pgms program(s) not found"
		goto END
    endif

	goto Ret_CHECK_PROGRAMS
	
NO_SURFANAT:
	echo ""
	echo "Error: No Surface Anatomy $SurfAnat (.HEAD or .BRIK) volume in $SurfAnatPath"
	echo ""
	goto END

NO_EXPANAT:
	echo ""
	echo "Error: No Experiment Anatomy $ExpAnat (.HEAD or .BRIK) in current directory"
	echo ""
	goto END

NO_DOWNGOOD_BADBAD:
	echo ""
	echo "Error: adwarp failed."
	echo ""
	goto END

NO_SS:
   echo ""
   echo "Error: SkullStripping failed."
   echo ""
   goto END
   
NO_VOLREG:
	echo ""
	echo "Error: 3dvolreg failed."
	echo ""
	goto END
NO_WARPDRIVE:
	echo ""
	echo "Error: 3dwarpdrive failed."
	echo ""
	goto END
NO_RESAMP:
	echo ""
	echo "Error: 3dresample failed."
	echo ""
	goto END
	
USAGE:
echo ""
echo "Usage: "
echo "`basename $0` <-exp_anat Experiment_Anatomy> <-surf_anat Surface_Anatomy> "
echo "              [dxyz] [-wd] [-prefix PREFIX] [-EA_clip_below CLP]"
echo "              [-align_centers] [-ok_change_view] [-strip_skull WHICH]"
echo ""
echo "Creates a version of Surface Anatomy that is registered to Experiment Anatomy."
echo ""
echo "Mandatory parameters:"
echo "<-exp_anat Experiment_Anatomy>: Name of high resolution anatomical data set in register "
echo "        with experimental data."
echo "<-surf_anat Surface_Anatomy> Path and Name of high resolution antomical data set used to "
echo "        create the surface."
echo ""
echo "  NOTE: In the old usage, there were no -exp_anat and -surf_anat flags and the two "
echo "  volumes had to appear first on the command line and in the proper order."
echo ""
echo "Optional parameters:"
echo "   [-dxyz DXYZ]: This optional parameter indicates that the anatomical "
echo "        volumes must be downsampled to dxyz mm voxel resolution before "
echo "        registration. That is only necessary if 3dvolreg runs out of memory."
echo "        You MUST have 3dvolreg that comes with afni distributions newer than "
echo "        version 2.45l. It contains an option for reducing memory usage and "
echo "        thus allow the registration of large data sets."
echo "   [-out_dxyz DXYZ]: Output the final aligned volume at a cubic voxelsize"
echo "                     of DXYZmm. The default is based on the grid of ExpVol."
echo "   [-wd]: Use 3dWarpDrive's general affine transform (12 param) instead of "
echo "        3dvolreg's 6 parameters."
echo "        If the anatomical coverage differs markedly between 'Experiment "
echo "        Anatomy' and 'Surface Anatomy', you might need to use -EA_clip_below "
echo "        option or you could end up with a very distorted brain."
#echo "        With more degrees of freedom, there is more room for the alignment not"
#echo "        to converge very well, especially when spatial coverage of the two dsets"
#echo "        is not the same. So use this option when you have to, not as the default."
echo "        The default now is to use -coarserot option with 3dWarpDrive, this"
echo "        should make the program more robust. If you want to try running without it"
echo "        the add -ncr with -wd"
echo "        I would be interested in examining cases where -wd option failed to "
echo "        produce a good alignment."
echo "   [-al]: Use 3dAllineate to do the 12 parameter alignment. Cost function"
echo "          is lpa"
echo "   [-al_opt 'Options for 3dAllineate']: Specify set of options between quotes"
echo "                                           to pass to 3dAllineate.   "
echo "   [-ok_change_view]: Be quiet when view of registered volume is changed"
echo "                      to match that of the Experiment_Anatomy, even when"
echo "                      rigid body registration is used."
echo "   [-strip_skull WHICH]: Use 3dSkullStrip to remove non-brain tissue and "
echo "                         potentially improve the alignment. WHICH can be"
echo "                         one of 'exp_anat', 'surf_anat', or 'both'. In the first case,"
echo "                         the skull is removed from Experiment_Anatomy dataset,"
echo "                         in the second it is removed from the surf_anat dataset."
echo "                          With 'both' the skull is removed from"
echo "                         Experiment_Anatomy and Surface_Anatomy."
echo "   [-skull_strip_opt 'Options For 3dSkullStrip']: Pass the options between"
echo "                         quotes to 3dSkullStrip."
echo "   [-align_centers]: Adds an additional transformation to align the volume"
echo "                     centers. This is a good option to use when volumes"
echo "                     are severely out of alignment."
echo "   [-EA_clip_below CLP]: Set slices below CLPmm in 'Experiment Anatomy' to zero."
echo "        Use this if the coverage of 'Experiment Anatomy' dataset"
echo "        extends far below the data in 'Surface Anatomy' dataset."
echo "        To get the value of CLP, use AFNI to locate the slice"
echo "        below which you want to clip and set CLP to the z coordinate"
echo "        from AFNI's top left corner. Coordinate must be in RAI, DICOM."   
echo "   [-prefix PREFIX]: Use PREFIX for the output volume. Default is the prefix "
echo "   [-surf_anat_followers Fdset1 Fdset2 ...]: Apply the same alignment"
echo "                transform to datasets Fdset1, Fdset2, etc."
echo "                This must be the last option on the command line."
echo "                All parameters following it are considered datasets."
echo "                You can transform other follower dsets manually by"
echo "                executing: "
echo "         3dAllineate -master Experiment_Anatomy \"
echo "                     -1Dmatrix_apply Surface_Anatomy_Alnd_Exp.A2E.1D \"
echo "                     -input Fdset   \"
echo "                     -prefix Fdset_Alnd_Exp+orig \"
echo "                     -final NN"
echo "   [-followers_interp KERNEL]: Set the interpolation mode for the "
echo "                               follower datasets. Default is NN, which "
echo "                               is appropriate for ROI datasets."
echo "                               Allowed KERNEL values are:"
echo "                               NN, linear, cubic, or quintic"
echo "        of the 'Surface Anatomy' suffixed by _Alnd_Exp."
echo "   [-keep_tmp]: Keep temporary files for debugging. Note that you should"
echo "                delete temporary files before rerunning the script."
echo ""         
echo ""
echo "NOTE: You must run the script from the directory where Experiment Anatomy resides."
echo ""
echo "Example 1: For datasets with no relative distortion and comparable coverage."
echo "           Using 6 param. rigid body transform."
echo "@SUMA_AlignToExperiment -exp_anat DemoSubj_spgrsa+orig. \"
echo "                        -surf_anat ../FreeSurfer/SUMA/DemoSubj_SurfVol+orig."
echo ""
echo "Example 2: For datasets with some distortion and different coverage."
echo "           Using 12 param. transform and clipping of areas below cerebellum:"
echo "@SUMA_AlignToExperiment -exp_anat ABanat+orig. -surf_anat DemoSubj_SurfVol+orig. \"
echo "                       -wd -prefix DemoSubj_SurfVol_WD_Alnd_Exp \"
echo "                       -EA_clip_below -30"
echo ""
echo "Example 3: For two monkey T1 volumes with very different resolutions and severe"
echo "           shading artifacts."
echo "@SUMA_AlignToExperiment    -surf_anat MOanat+orig. -al \"
echo "                           -exp_anat MoExpanat+orig. \"
echo "                           -strip_skull both -skull_strip_opt -monkey \"
echo "                           -align_centers \"
echo "                           -out_dxyz 0.3"
echo "More help may be found at http://afni.nimh.nih.gov/ssc/ziad/SUMA/SUMA_doc.htm"
echo ""
echo "Ziad Saad (saadz@mail.nih.gov)"
echo "SSCC/NIMH/ National Institutes of Health, Bethesda Maryland"
echo ""
	goto END

END:
	cd $CurDir
