#!/bin/tcsh -f

HELP:
if ("$1" == '' || "$1" == "-help" || "$1" == "-h") then
   echo "Usage 1: A script to clip regions of a volume"
   echo ""
   echo "   `basename $0` <-input VOL> <-below Zmm> [ [-and/-or] <-above Zmm> ]"
   echo ""
   echo "   Mandatory parameters:"
   echo "      -input VOL: Volume to clip"
   echo "    + At least one of the options below:"
   echo "      -below Zmm: Set to 0 slices below Zmm"
   echo "                  Zmm (and all other coordinates) are in RAI"
   echo "                  as displayed by AFNI on the top left corner"
   echo "                  of the AFNI controller" 
   echo "      -above Zmm: Set to 0 slices above Zmm"
   echo "      -left  Xmm: Set to 0 slices left of Xmm"
   echo "      -right  Xmm: Set to 0 slices right of Xmm"
   echo "      -anterior Ymm: Set to 0 slices anterior to Ymm"
   echo "      -posterior Ymm: Set to 0 slices posterior to Ymm"
   echo "    + Or the box option:"
   echo "      -box Cx Cy Cz Dx Dy Dz: Clip the volume to a box"
   echo "                              centered at Cx, Cy, Cz (RAI mm),"
   echo "                              and of dimensions Dx Dy Dz (RAI mm)"
   echo "      -mask_box Cx Cy Cz Dx Dy Dz: Same as -box, but set all values"
   echo "                              inside of box to 1."
   echo "      Example:"
   echo "         @clip_volume -mask_box 20.671 -10.016 23.362 10 10 10 \"
   echo "                      -input seg_no_spat.c+orig.BRIK \"
   echo "                      -prefix small_box_volume -crop_greedy"
   echo ""
   echo "      Note:"
   echo "         If you are not cropping the output, you might consider"
   echo "         using 3dUndump instead."
   echo ""
   echo "    Optional parameters:"
   echo "      -and (default): Combine with next clipping planes using 'and'"
   echo "      -or           : Combine with next clipping planes using 'or'"
   echo "         Note: These two parameters affect the clipping options that"
   echo "               come after after them. Unfortunately they are used"
   echo "               to build a mask of what is to be kept in the end, rather"
   echo "               than what is to be removed, so they can be confusing."
   echo "               A '-and' multiplies the mask by what is to be kept from"
   echo "               the next cut, and a '-or' adds to it."
   echo "      -verb         : Verbose, show command"
   echo "      -crop_allzero : Crop the output volume with 3dAutobox -noclust"
   echo "                      This would keep 3dAutobox from removing any"
   echo "                      slices unless they are all zeros"
   echo "      -crop_greedy  : Crop the output volume with 3dAutobox"
   echo "                      In addition to what you specified for cropping,"
   echo "                      slices with a few non zero voxels might also get"
   echo "                      chopped off by 3dAutobox"
   echo "      -crop : Same as -crop_greedy, kept for backward compatibility"
   echo "      -prefix PRFX  : Use PRFX for output prefix. Default is the "
   echo "                      input prefix with _clp suffixed to it."
   echo "      -followers DSET1 DSET2 ...: Apply the same treatment to the"
   echo "                      follower datasets. Note that cropped or clipped"
   echo "                      versions are all named automatically by affixing"
   echo "                      _clp to their prefix."
   echo ""    
   echo "Example:"
   echo "@clip_volume -below -30 -above 53 -left 20 -right -13 -anterior -15 \"
   echo "             -posterior 42 -input ABanat+orig. -verb -prefix sample"
   echo ""
   echo "Written by Ziad S. Saad (saadz@mail.nih.gov)"
   echo "                        SSCC/NIMH/NIH/DHHS"
   echo ""
   goto END
endif
  

PARSE:
	echo "Parsing ..."
	set Narg = $#
	set foll = ()
	set cnt = 1
   set crop = 0
   set cropopt = ""
   set anat_in = ''
   set prefix = ''
   set sgn = '*'
   set verb = 0
   set neq = 0
   set binarize = 0
   while ($cnt <= $Narg)
		set donext = 1;
      
      if ($donext && ("$argv[$cnt]" == "-box" || \
                      "$argv[$cnt]" == "-mask_box") ) then
         if ("$argv[$cnt]" == "-mask_box") set binarize = 1
         set aneeded = `ccalc -i $cnt + 6`
         set pLoc = $cnt		
		   if ($aneeded > $Narg) then
				echo "Need 6 params after -box"
            goto END
         endif
         @ cnt ++
         #get XYZ of center
         set C = ($argv[$cnt])
         @ cnt ++
         set C = ($C $argv[$cnt])
         @ cnt ++
         set C = ($C $argv[$cnt])
         @ cnt ++
         #Get mm box dims
         set D = ($argv[$cnt])
         @ cnt ++
         set D = ($D $argv[$cnt])
         set pLoc = $cnt
         @ cnt ++
         set D = ($D $argv[$cnt])
         
         echo "Box centered at $C, dimensions $D"
         #Keep Below
         set eq = "      (1-step(z - $C[3]-$D[3]/2))"
         #Keep Above
         set eq = "$eq * (step(z - $C[3]+$D[3]/2))"
         #Keep Anterior
         set eq = "$eq * (1-step(y - $C[2]-$D[2]/2))"
         #Keep Posterior
         set eq = "$eq * (step(y - $C[2]+$D[2]/2))"
         #Keep Right
         set eq = "$eq * (1-step(x - $C[1]-$D[1]/2))"
         #Keep Left
         set eq = "$eq * (step(x - $C[1]+$D[1]/2))"
         set donext = 0
      endif
      
      if ($donext && ("$argv[$cnt]" == "-below" || "$argv[$cnt]" == "-inferior") ) then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need Zmm after -below"
            goto END
			else
            @ cnt ++
            if ($neq == 0) then 
               set eq = "step(z - ($argv[$cnt]))"
               @ neq ++
            else 
               set eq = "$eq $sgn step(z - ($argv[$cnt]))"
               @ neq ++
            endif
            set donext = 0	
         endif	
      endif
      if ($donext && ("$argv[$cnt]" == "-above" || "$argv[$cnt]" == "-superior") ) then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need Zmm after -above"
            goto END
			else
            @ cnt ++
            if ($neq == 0) then 
               set eq = "step(($argv[$cnt]) - z)"
               @ neq ++
            else 
               set eq = "$eq $sgn step(($argv[$cnt]) - z)"
               @ neq ++
            endif
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-right") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need Xmm after -right"
            goto END
			else
            @ cnt ++
            if ($neq == 0) then 
               set eq = "step(x - ($argv[$cnt]))"
               @ neq ++
            else 
               set eq = "$eq $sgn step(x - ($argv[$cnt]))"
               @ neq ++
            endif
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-left") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need Xmm after -left"
            goto END
			else
            @ cnt ++
            if ($neq == 0) then 
               set eq = "step(($argv[$cnt]) - x)"
               @ neq ++
            else 
               set eq = "$eq $sgn step(($argv[$cnt]) - x)"
               @ neq ++
            endif
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-anterior") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need Ymm after -anterior"
            goto END
			else
            @ cnt ++
            if ($neq == 0) then 
               set eq = "step(y - ($argv[$cnt]))"
               @ neq ++
            else 
               set eq = "$eq $sgn step(y - ($argv[$cnt]))"
               @ neq ++
            endif
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-posterior") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need Ymm after -posterior"
            goto END
			else
            @ cnt ++
            if ($neq == 0) then 
               set eq = "step(($argv[$cnt]) - y)"
               @ neq ++
            else 
               set eq = "$eq $sgn step(($argv[$cnt]) - y)"
               @ neq ++
            endif
            set donext = 0	
         endif	
      endif
      
      if ($donext && "$argv[$cnt]" == "-crop_allzero") then
         set crop = 1;    set cropopt = "-noclust"		
         set donext = 0		
      endif

      if ($donext && ( "$argv[$cnt]" == "-crop_greedy"  || \
                       "$argv[$cnt]" == "-crop" ) ) then
         set crop = 1;    set cropopt = ""		
         set donext = 0		
      endif
      
      if ($donext && "$argv[$cnt]" == "-and") then
         set sgn = '*';		
         set donext = 0		
      endif
      if ($donext && "$argv[$cnt]" == "-or") then
         set sgn = '+';		
         set donext = 0		
      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]" == "-input") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need  volume after -input"
            goto END
			else
            @ cnt ++
            set anat_in = "$argv[$cnt]"
            set in_name = `@parse_afni_name $anat_in`
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-followers") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need  volume(s) after -followers"
            goto END
			else
            @ cnt ++
            while ( $cnt <= $Narg && "$argv[$cnt]" !~ "-*" ) 
               set foll = ($foll "$argv[$cnt]")
               @ cnt ++
               if ($cnt > $Narg) goto OUT
            end
            OUT:
            if ($cnt > $Narg) then
               @ cnt --
            else if ($cnt <= $Narg && "$argv[$cnt]" =~ "-*" ) then
               @ cnt --
            endif
            set donext = 0	
         endif	
      endif
      if ($donext && "$argv[$cnt]" == "-verb") then
         set verb = 1;		
         set donext = 0		
      endif
      if ($donext && "$argv[$cnt]" == "-echo") then
         set echo;		
         set donext = 0		
      endif
      if ($donext == 1) then
         echo "Error: Option or parameter '$argv[$cnt]' not understood"
         goto END
      endif
		@ cnt ++
	end
   
   if ($prefix == '') then
      set prefix = $in_name[2]"_clp"
   endif

DOIT:
   echo "Clipping"
   set val = "a"
   if ($binarize == 1) set val = "1"
   if ($crop == 1) then
      if ($verb) then
         set noglob
   echo "3dcalc -a "$anat_in" -expr "$val * step($eq)" -rai -prefix ___tmp_clp"
         unset noglob
      endif
      3dcalc -a "$anat_in" -expr "$val * step($eq)" -rai -prefix ___tmp_clp
      if ($verb) then
         set noglob
   echo "3dAutobox $cropopt -prefix $prefix -input ___tmp_clp$in_name[3]"
         unset noglob
      endif
      3dAutobox $cropopt -prefix $prefix -input ___tmp_clp$in_name[3]
      rm -f ___tmp_clp$in_name[3].???? >& /dev/null
      if ($#foll > 0) then
         set master = $prefix$in_name[3]
         foreach dd ($foll)
            set pin = `@parse_afni_name $dd`
            set pout = $pin[2]"_clp"
            3dresample -master $master -prefix $pout -input $dd
         end
      endif
   else
      set noglob
      if ($verb) echo "3dcalc -a "$anat_in" -expr "a * step($eq)" -rai -prefix $prefix"
      unset noglob
      3dcalc -a "$anat_in" -expr "a * step($eq)" -rai -prefix $prefix
      if ($#foll > 0) then
         foreach dd ($foll)
            set pin = `@parse_afni_name $dd`
            set pout = $pin[2]"_clp"
            3dcalc -a $dd  -expr "a * step($eq)" -rai -prefix $pout
         end
      endif
   endif
   
   
END:
