#!/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 RESAMPLE
Ret_RESAMPLE:

goto REGISTER
Ret_REGISTER:

echo "Done."
goto END


PARSE_COMMAND:
	
   #continue parsing for new options
   set Narg = $#
   set cnt = 1
   set cropt = '-coarserot'
   set prefix = ''
   set UseWarp = 0
   set clpbelow = ''
   set SA_in = ''
   set EA_in = ''
   set DownSample = 0
   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 ($DownSample < 0.3 || $DownSample > 4) then
               echo "Error: Bad value for dxyz ($argv[$cnt])"
               echo ""
               goto END
            endif
            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 = "$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]" == "-ncr") then
         set cropt = '';		
         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.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
	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)) then
				goto NO_DOWNGOOD_BADBAD
			endif
			
		endif
		set SurfAnatPrefix = $tmpPrefix
		set SurfAnat = $SurfAnatPrefix$SurfAnatView
		cd $CurDir
	endif
	goto Ret_DOWNSAMPLE

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 (-f $ExpAnat_Resamp.BRIK) 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)) 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)) 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 -rotcom -verbose -base $ExpAnat -prefix $VolRegPrefix $SurfAnatPath/$SurfAnat"
	   echo ""
	   3dvolreg -wtrim -clipit -twopass -twodup -zpad 8 -rotcom -verbose -base $ExpAnat -prefix $VolRegPrefix $SurfAnatPath/$SurfAnat
	   if (!(-f $SurfAnatPath/$VolRegPrefix$SurfAnatView.BRIK || -f $SurfAnatPath/$VolRegPrefix$SurfAnatView.BRIK.gz || -f $SurfAnatPath/$VolRegPrefix$SurfAnatView.BRIK.Z)) then
		   goto NO_VOLREG
	   endif
      set fview = $SurfAnatView
	   mv $SurfAnatPath/$VolRegPrefix* ./
   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 -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

      3dWarpDrive $cropt -twopass -verb -affine_general -cubic -final quintic -base ./${tmpref}_refpad$SurfAnatView -prefix ./${tmpref}_pad_wd ./${tmpref}_pad$SurfAnatView
	   
      3dZeropad -I -$pd -S -$pd -A -$pd -P -$pd -L -$pd -R -$pd -mm -prefix ./$VolRegPrefix ${tmpref}_pad_wd$SurfAnatView
	   #copy the WARPDRIVE_MATVEC_ fields to the zero unpadded dude
      3drefit -atrcopy ${tmpref}_pad_wd$SurfAnatView WARPDRIVE_INPUT_IDCODE $VolRegPrefix$SurfAnatView
      3drefit -atrcopy ${tmpref}_pad_wd$SurfAnatView WARPDRIVE_INPUT_NAME $VolRegPrefix$SurfAnatView
      3drefit -atrcopy ${tmpref}_pad_wd$SurfAnatView WARPDRIVE_BASE_IDCODE $VolRegPrefix$SurfAnatView
      3drefit -atrcopy ${tmpref}_pad_wd$SurfAnatView WARPDRIVE_MATVEC_FOR_000000 $VolRegPrefix$SurfAnatView
      3drefit -atrcopy ${tmpref}_pad_wd$SurfAnatView WARPDRIVE_MATVEC_INV_000000 $VolRegPrefix$SurfAnatView
      #differing views?
      if ("$SurfAnatView" != "$ExpAnatView") then
         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)) then
		   goto NO_WARPDRIVE
	   endif
      rm -rf ${tmpref}*.???? >& /dev/null
   endif
	
	
	#remove _resamp_
	if ($Resampled == 1) then
		echo "removing temporary bricks ..."
		rm -f $ExpAnat_Resamp".HEAD"
		rm -f $ExpAnat_Resamp".BRIK"
	endif
   
   #add a history note
   3dNotes -h "`basename $0` $argv[*]" $VolRegPrefix$fview
   
	goto Ret_REGISTER

CHECK_EXISTENCE:
	test -f $ExpAnat.HEAD || goto NO_EXPANAT
	if (!(-f $ExpAnat.BRIK || -f $ExpAnat.BRIK.gz || -f $ExpAnat.BRIK.Z)) then
		goto NO_EXPANAT
	endif

	test -f $SurfAnatPath/$SurfAnat.HEAD || goto NO_SURFANAT
	if (!(-f $SurfAnatPath/$SurfAnat.BRIK || -f $SurfAnatPath/$SurfAnat.BRIK.gz || -f $SurfAnatPath/$SurfAnat.BRIK.Z)) then
		goto NO_SURFANAT
	endif
   
   #check for large center difference
   set dist_cent = `@Center_Distance -dset $ExpAnat.HEAD $SurfAnatPath/$SurfAnat.HEAD`
   if (`ccalc -form int -eval "step($dist_cent - 80)"`) then
      echo ""
      echo "*********** Warning *************"
      echo "Dataset centers are $dist_cent mm"
      echo "apart. If registration fails, try"
      echo "recentering all the input data using"
      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 "*********************************"
      echo ""
      echo "Hit Enter to proceed or ctrl+c to quit."
      echo ""
      set junk = $<
   else
      echo "Center distance of $dist_cent mm"   
   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_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: `basename $0` <-exp_anat Experiment_Anatomy> <-surf_anat Surface_Anatomy> "
   echo "                     [dxyz] [-wd] [-prefix PREFIX] [-EA_clip_below CLP]"
	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 "   [-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 "   [-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 "        of the 'Surface Anatomy' suffixed by _AlndExp."
   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_AlndExp \"
   echo "                       -EA_clip_below -30"
   echo ""
   echo "More help may be found at http://afni.nimh.nih.gov/ssc/ziad/SUMA/SUMA_doc.htm"
	echo ""
	echo "Ziad Saad (ziad@nih.gov)"
	echo "SSCC/NIMH/ National Institutes of Health, Bethesda Maryland"
	echo ""
	goto END

END:
	cd $CurDir
