#!/bin/tcsh -f
@global_parse `basename $0` "$*" ; if ($status) exit 0
set stat = 0
set stdir = $PWD

goto PARSE
RET_PARSE:

LOCALSTATS:      
   cd $stdir
   if ( ! -d $odir) mkdir -p $odir
    
   set sopt = ''
   if ($#statvector == 3 && \
         $statvector[1] == "median" && \
         $statvector[2] == "MAD" && \
         $statvector[3] == "P2skew" ) then
      set sopt = ('-stat mMP2s')
   else if ($#statvector == 4 && \
         $statvector[1] == "mean" && \
         $statvector[2] == "median" && \
         $statvector[2] == "MAD" && \
         $statvector[3] == "P2skew" ) then
      set sopt = ('-stat mMP2s')
   else
      foreach lstat ($statvector)
         set sopt = ($sopt '-stat' $lstat)
      end
   endif
      
   set mopt = ''
   if ($inmask != '') set mopt = "-mask $inmask"
   set inpref = `@GetAfniPrefix $involume | sed 's/.nii$//g'` 
   if ( ! -f $odir/${inpref}+orig.HEAD) then
      3dcalc -a "${involume}" -expr 'a' -datum short -prefix $odir/${inpref}+orig
   endif
   
   foreach neigh ($localvector)
      set oneigh = `printf '%02d' $neigh`
      set sublopt = ''
      set cnt = 1
      foreach lstat ($statvector)
         set ss = $statlabelvector[$cnt].${oneigh}_mm
         set sublopt = ($sublopt -sublabel `ccalc -i $cnt -1` $ss)
         @ cnt ++
      end
      if ( ! -f $odir/${inpref}.${olabel}.${oneigh}+orig.HEAD ) then
         echo "Running 3dLocalstat $neigh on $involume...`date`"
         3dLocalstat   $mopt \
                       -nbhd "RECT($neigh,$neigh,$neigh)" \
                       $sopt -label_ext ${oneigh}_mm \
                       -datum short -reduce_max_vox $max_vox \
                       -prefix $odir/${inpref}.${olabel}.${oneigh} \
                       "${involume}"
         #3drefit $sublopt $odir/${inpref}.${olabel}.${oneigh}+orig   
      else
         echo "$odir/${inpref}.${olabel}.${oneigh} exists already"
      endif
   end
   if ( $Scale == 9) then
      if ( ! -f $odir/${inpref}.sc${fatScale}.perc+orig.HEAD ) then
         echo "Running 3dLocalstat $fatScale on $involume for scaling...`date`"
         3dLocalstat  \
                 -nbhd "SPHERE($fatScale)" \
                 -stat  perc:65:95:5 \
                 -datum short -reduce_max_vox $max_vox \
                 -prefix $odir/${inpref}.sc${fatScale}.perc \
                 "${involume}"
      else
         echo "$odir/${inpref}.sc${fatScale}.perc exists already"
      endif
   endif
   if ( "$Mname" != "" ) then
      if ("$Mname" == "AUTO") then
               cd $odir
         if ( ! -f T1.uni+orig.HEAD) then
            if ( $Scale == 9) then
               cd $stdir
               @T1mask -T1 $involume -hullmask 1.0 -odir $odir
               cd $odir
               set sbscale = \
                  `3dinfo -label2index "perc:${fatPerc}.00"   \
                              ${inpref}.sc${fatScale}.perc+orig`
               if ("$sbscale" == '') then
                  echo "Could not find sub-brick 'perc:${fatPerc}.00'"
                  echo " in ${inpref}.sc${fatScale}.perc+orig"
                  goto BEND
               endif            
               3dcalc -a T1+orig \
                      -b ${inpref}.sc${fatScale}.perc+orig"[$sbscale]"   \
                      -c T1.hull.mask.m+orig \
                      -expr 'step(c-1)*step(b)*a/b'   \
                      -prefix T1.uni
            else
               cd $stdir
               @T1scale -T1 $involume -brainhull 1.0 -odir $odir
               cd $odir
            endif
         else
            echo "Reusing T1.uni+orig"
         endif
         if ( ! -f T1.uni.sn+tlrc.HEAD) then
            #Run 3dSpatNorm to get rid of basal voxels, and auto_tlrc
            3dSpatNorm  -overwrite -orig_space -prefix T1.uni.sn \
                        -bottom_cuts ALRP T1.uni+orig
            @auto_tlrc  -base MNI_sk_avg152T1+tlrc  -init_xform AUTO_CENTER \
                        -no_ss -input T1.uni.sn+orig 
            if ( ! -f MNI_sk152T1+tlrc.HEAD ) then
               @auto_tlrc  -base MNI_sk_avg152T1+tlrc -base_copy MNI_sk152T1
            endif
         else
            echo "Reusing T1.uni.sn+tlrc.HEAD"
         endif
         if ( ! -f T1.uni.sn.Xat.1D) then
            echo "Failed to run @auto_tlrc"
            goto BEND
         endif
         cp -p T1.uni.sn.Xat.1D ${inpref}.Xat.1D
            cd $stdir
      else
         cp -p $Mname $odir/${inpref}.Xat.1D
      endif
      set Mname = ${inpref}.Xat.1D
   endif

REGROUP:
   cd $stdir
   
   cd $odir
   set cnt = 1
   set AddedAnat = 0
   foreach lstat ($statvector)
      if ( ! -f ${inpref}.us.${lstat}+orig.HEAD) then
         echo "Creating ${inpref}.us.${lstat} ..."
         
         set sbl = ()
         foreach neigh ($localvector)
            set oneigh = `printf '%02d' $neigh`
            set statlabel = $statlabelvector[$cnt].${oneigh}_mm
            set sbl = ("$sbl" ${inpref}.${olabel}.${oneigh}+orig"[$statlabel]")
         end
         if ($prepend_anat && $AddedAnat == 0 && \
             ($lstat =~ med* || $lstat =~ mean*)) then
            set AddAnatOpt = "${inpref}+orig"
         else
            set AddAnatOpt = ''
         endif
         set noglob
         3dTcat -prefix ${inpref}.us.${lstat} $AddAnatOpt $sbl
         if ( "$AddAnatOpt" != '') then
            if ($lstat =~ med*) then
               3drefit -sublabel 0 MEDIAN.00_mm ${inpref}.us.${lstat}+orig
            else 
               3drefit -sublabel 0 MEAN.00_mm ${inpref}.us.${lstat}+orig
            endif
            set AddedAnat = 1
         endif
         unset noglob
      else
         echo "Reusing ${inpref}.us.${lstat} ..."
      endif
      @ cnt ++
   end
   cd $stdir

SCALE:
   cd $stdir
   
   cd $odir
   set cnt = 1
   foreach lstat ($statvector)
      set sss = "${inpref}.us.${lstat}"
      set ttt = "${inpref}.sc${Scale}.${lstat}"
      if ( -f ${inpref}.${lstat}+orig.HEAD) then
         rm -f ${inpref}.${lstat}+orig.*
      endif
      if ($Scale == 1) then
         echo "Scaling by each sb median (overwriting) ${sss} to ${ttt} ..."
         @ScaleVolume -scale_by_median -input ${sss}+orig -prefix ${ttt}
      else if ($Scale == 2) then
         echo "Scaling by $ScaleVal (overwriting) ${sss} to ${ttt} ..."
         3dcalc -a ${sss}+orig -prefix ${ttt} -expr "a/$ScaleVal"
      else if ($Scale == 3) then
         echo "normalizing (overwriting) ${sss} to ${ttt} ..."
         @ScaleVolume -norm -input ${sss}+orig -prefix ${ttt} 
      else if ($Scale == 4) then
         #do nothing, deal with speciality below
      else if ($Scale == 5) then
         #do nothing, deal with speciality below
      else if ($Scale == 6) then
         #do nothing, deal with speciality below
      else if ($Scale == 7) then
         #do nothing, deal with speciality below
      else if ($Scale == 8) then
         #do nothing, deal with speciality below
      else if ($Scale == 9) then
         #do nothing, deal with speciality below
      else if ($Scale == 0) then
         echo "Copying unscaled signatures"
         3dcopy $sss+orig $ttt
      else 
         echo "Bad scale value of $Scale"
         goto END
      endif
      @ cnt ++
   end
   if ($Scale == 4) then
      #Only scale median signature per the equations derived 
      foreach lstat ($statvector)
         set sss = "${inpref}.us.${lstat}"
         set ttt = "${inpref}.sc${Scale}.${lstat}" 
         if ($lstat =~ med*) then
            3dDetrend -overwrite -prefix ___dt -polort 0 ${sss}+orig
            3dcalc -overwrite -a ___dt+orig -b ${inpref}.us.MAD+orig \
                     -expr '(step(b)*a/b)' -prefix $ttt
            rm -f ___dt+orig* 
         else
            #Just copy for ease on other scripts, nothing to do
            3dcopy $sss+orig $ttt
         endif
      end
   else if ($Scale == 5 || $Scale == 6) then
      #Only scale median signature per the equations derived
      #But only use last MAD sub-brick.
      #Also, scale MAD by last sub-brick 
      set ttal = ()
      foreach lstat ($statvector)
         set sss = "${inpref}.us.${lstat}"
         set ttt = "${inpref}.sc${Scale}.${lstat}" 
         if ( ! -f ${inpref}.sc${Scale}.${lstat}+orig.HEAD) then
            echo "Creating $ttt"
            if ($lstat =~ med*) then
               if ($Scale == 5) then
                  3dDetrend -overwrite -prefix ___dt -polort 0 ${sss}+orig
               else if ($Scale == 6) then
                  #prepend anatomy
                  3dbucket -prefix ___adt+orig "$stdir/${involume}" ${sss}+orig 
                  3drefit -sublabel 0 MEDIAN.00_mm ___adt+orig
                  3dDetrend -overwrite -prefix ___dt -polort 0 ___adt+orig
               endif
               3dcalc -overwrite -a ___dt+orig -b ${inpref}.us.MAD+orig'[$]' \
                        -expr '(step(b)*a/b)' -prefix $ttt
               rm -f ___dt+orig* ___adt+orig*
            else if ($lstat =~ MAD*) then
               set mm = `3dnvals ${inpref}.us.MAD+orig`
               @ mm --
               @ mm --
               3dcalc -overwrite -a ${inpref}.us.MAD+orig"[0..$mm]" \
                                 -b ${inpref}.us.MAD+orig'[$]' \
                        -expr '(step(b)*a/b)' -prefix $ttt
            else
               #Just copy for ease on other scripts, nothing to do
               3dcopy $sss+orig $ttt
            endif
         else 
            echo "Reusing $ttt"
         endif
         set ttal = ($ttal $ttt+orig)
      end
      if ( ! -f ${inpref}.sc${Scale}.${sigset}+orig.HEAD) then
         3dTcat -prefix ${inpref}.sc${Scale}.${sigset} $ttal
      else
         echo "Reusing ${inpref}.sc${Scale}.${sigset}"
      endif
   else if ($Scale == 7) then
      set ttal = ()
      foreach lstat ($statvector)
         set sss = "${inpref}.us.${lstat}"
         set ttt = "${inpref}.sc${Scale}.${lstat}" 
         if ( ! -f ${inpref}.sc${Scale}.${lstat}+orig.HEAD) then
            echo "Creating $ttt"
            if ($lstat =~ med*) then
               set mm = `3dinfo -nvi ${sss}+orig`
               @ mm --
               3dcalc -overwrite -a ${sss}+orig"[0-$mm]" \
                        -b ${inpref}.us.mean+orig'[$]' \
                        -expr '(step(b)*a/b)' -prefix $ttt
            else if ($lstat =~ MAD*) then
               3dcalc -overwrite -a ${inpref}.us.MAD+orig \
                                 -b ${inpref}.us.mean+orig'[$]' \
                        -expr '(step(b)*a/b)' -prefix $ttt
            else if ($lstat =~ mea*) then
               set mm = `3dinfo -nvi ${sss}+orig`
               @ mm --
               3dcalc -overwrite -a ${sss}+orig"[0-$mm]" \
                        -b ${inpref}.us.mean+orig'[$]' \
                        -expr '(step(b)*a/b)' -prefix $ttt
            else
               #Just copy for ease on other scripts, nothing to do
               3dcopy $sss+orig $ttt
            endif
         else 
            echo "Reusing $ttt"
         endif
         set ttal = ($ttal $ttt+orig)
      end
      if ( ! -f ${inpref}.sc${Scale}.${sigset}+orig.HEAD) then
         3dTcat -prefix ${inpref}.sc${Scale}.${sigset} $ttal
      else
         echo "Reusing ${inpref}.sc${Scale}.${sigset}"
      endif
   else if ($Scale == 8) then
      set ttal = ()
      foreach lstat ($statvector)
         set sss = "${inpref}.us.${lstat}"
         set ttt = "${inpref}.sc${Scale}.${lstat}" 
         if ( ! -f ${inpref}.sc${Scale}.${lstat}+orig.HEAD) then
            echo "Creating $ttt"
            if ($lstat =~ med* || $lstat =~ mean*) then
               3dcalc -overwrite -a ${sss}+orig -b ${inpref}.us.MAD+orig'[$]' \
                        -expr '(step(b)*a/b)' -prefix $ttt
            else if ($lstat =~ MAD*) then
               set mm = `3dnvals ${inpref}.us.MAD+orig`
               @ mm --
               @ mm --
               3dcalc -overwrite -a ${inpref}.us.MAD+orig"[0..$mm]" \
                                 -b ${inpref}.us.MAD+orig'[$]' \
                        -expr '(step(b)*a/b)' -prefix $ttt
            else
               #Just copy for ease on other scripts, nothing to do
               3dcopy $sss+orig $ttt
            endif
            3dNotes -h "`basename $0` $*" $ttt+orig
         else 
            echo "Reusing $ttt"
         endif
         set ttal = ($ttal $ttt+orig)
      end
      if ( ! -f ${inpref}.sc${Scale}.${sigset}+orig.HEAD) then
         3dTcat -prefix ${inpref}.sc${Scale}.${sigset} $ttal
      else
         echo "Reusing ${inpref}.sc${Scale}.${sigset}"
      endif
   else if ($Scale == 9) then
      if ( ! -f ${inpref}.sc${fatScale}.perc+orig.HEAD) then
         echo "Error: Missing scaling volume ${inpref}.sc${fatScale}.perc"
         goto BEND
      else
         set sbscale = \
            `3dinfo -label2index "perc:${fatPerc}.00"   \
                           ${inpref}.sc${fatScale}.perc+orig`
         if ("$sbscale" == '') then
            echo "Could not find sub-brick 'perc:${fatPerc}.00'"
            echo " in ${inpref}.sc${fatScale}.perc+orig"
            goto BEND
         endif
      endif
      
      set ttal = ()
      foreach lstat ($statvector)
         set sss = "${inpref}.us.${lstat}"
         set ttt = "${inpref}.sc${Scale}.${lstat}" 
         if ( ! -f ${inpref}.sc${Scale}.${lstat}+orig.HEAD) then
            echo "Creating $ttt"
            if ($lstat =~ med* || $lstat =~ mean* || $lstat =~ MAD*) then
               3dcalc -overwrite -a ${sss}+orig \
                      -b ${inpref}.sc${fatScale}.perc+orig"[$sbscale]" \
                      -expr '(step(b)*a/b)' -prefix $ttt
            else
               #Just copy for ease on other scripts, nothing to do
               3dcopy $sss+orig $ttt
            endif
            3dNotes -h "`basename $0` $*" $ttt+orig
         else 
            echo "Reusing $ttt"
         endif
         set ttal = ($ttal $ttt+orig)
      end
      if ( ! -f ${inpref}.sc${Scale}.${sigset}+orig.HEAD) then
         3dTcat -prefix ${inpref}.sc${Scale}.${sigset} $ttal
         3drefit -sublabel_suffix .sc${Scale} ${inpref}.sc${Scale}.${sigset}+orig
      else
         echo "Reusing ${inpref}.sc${Scale}.${sigset}"
      endif
   endif
   
   
   if ("$extrascl" == '-feat_znorm') then
      if ( $featmask == '' ) then
         if ( ! -f ${inpref}.am+orig.HEAD) then
            3dAutomask -prefix ${inpref}.am ${inpref}+orig
         else
            echo "Reusing ${inpref}.am+orig.HEAD"
         endif
         set featmask = ${inpref}.am+orig
      endif
      if ( ! -f ${inpref}.sc${Scale}z.${sigset}+orig.HEAD) then
         @ScaleVolume   -feat_znorm  -mask $featmask \
                        -prefix  ${inpref}.sc${Scale}z.${sigset} \
                        -input ${inpref}.sc${Scale}.${sigset}+orig
      else
         echo "Reusing ${inpref}.sc${Scale}z.${sigset}+orig.HEAD"
      endif
   endif
   
   #Add XYZ features
   if ( "$Mname" != "") then
      #The matrix coming from @auto_tlrc is such that M Xt = Xo
      #I want Xt = Mt Xo, so Mt = inv(M)
      #So, Xt = Mt Xo and Xz = Mz Mt Xo
      #Mz is obtained from @CreateMz, which creates Mnorm.1D
      #
      #Mall = Mz Mt, which is computed next
      # Mz is manually inserted here from the output of @CreateMz
      # with something like: set ll = ( `cat_matvec Mnorm.1D`)
      #                      set ll = ( `echo $ll | sed 's/ /,/g'` )
      # and put the content of $ll in MATRIX() below
      set Mall = (`cat_matvec $Mname -I   'MATRIX(0.024764,0,0,0.012501,0,0.020628,0,-0.379561,0,0,0.0231,-0.006564)'`)
      
      #Now I will use 3dcalc to compute Xz = Mall Xo, one coord at a time 
      #
      set M = ($Mall) #notation convenience
      if (! -f ${inpref}.Xz+orig.HEAD) then
         3dcalc -RAI -overwrite -a ${inpref}+orig \
                -expr "step(a)*(x*$M[1] + y*$M[2] + z*$M[3] + $M[4])"   \
                -prefix ${inpref}.Xz
         3drefit -sublabel 0 Xz ${inpref}.Xz+orig
      else 
         echo "Reusing ${inpref}.Xz+orig.HEAD"
      endif       
      
      if (! -f ${inpref}.Yz+orig.HEAD) then
         3dcalc -RAI -overwrite -a ${inpref}+orig \
                -expr "step(a)*(x*$M[5] + y*$M[6] + z*$M[7] + $M[8])"   \
                -prefix ${inpref}.Yz
         3drefit -sublabel 0 Yz ${inpref}.Yz+orig
      else 
         echo "Reusing ${inpref}.Yz+orig.HEAD"
      endif       
      
     
      if (! -f ${inpref}.Zz+orig.HEAD) then
         3dcalc -RAI -overwrite -a ${inpref}+orig \
                -expr "step(a)*(x*$M[9] + y*$M[10] + z*$M[11] + $M[12])"   \
                -prefix ${inpref}.Zz
         3drefit -sublabel 0 Zz ${inpref}.Zz+orig
      else 
         echo "Reusing ${inpref}.Zz+orig.HEAD"
      endif 
      
      foreach gg (${inpref}.sc${Scale}.${sigset}+orig.HEAD  \
                  ${inpref}.sc${Scale}z.${sigset}+orig.HEAD )
         if ( -f $gg ) then
            set ok = (`3dinfo -label $gg | grep -w Xz | grep -w Yz | grep -w Zz`)
            if ($status == 0) then
             echo "It looks like $gg has Xz Yz and Zz in it, not adding anything"
            else
               3dTcat -glueto  $gg \
                         ${inpref}.Xz+orig   \
                         ${inpref}.Yz+orig   \
                         ${inpref}.Zz+orig   
            endif
         endif
      end
   endif
   
   #make sure we have the history note
   foreach gg (${inpref}.sc${Scale}.${sigset}+orig.HEAD  \
                  ${inpref}.sc${Scale}z.${sigset}+orig.HEAD )
      if ( -f $gg ) then
         3dNotes -h "`basename $0` $*" $gg
      endif
   end
   
   cd $stdir      
goto END


PARSE:
set Narg = $#
set cnt = 1
set starttime=`date`
set resample = 1
set statvector = ""
set localvector = ""
set cleanafter = 1
set inmask = ""
set odir = './'
set olabel = 'loc_st'
set sigset = 'sigset'
set statopen = 0
set localopen = 0
set Scale = 0
set ScaleVal = 0
set max_vox = 0
set prepend_anat = 0
set extrascl = ''
set Mname = ''
set featmask = ''
if ("$1" == '') goto HELP
while ($cnt <= $Narg)
   set donext = 1

   if ($donext && "$argv[$cnt]" == "-help" || "$argv[$cnt]" == "-h") then
      goto HELP
   endif
   
   if ($donext && ("$argv[$cnt]" == "-d" || "$argv[$cnt]" == "-echo")) then
      set echo
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-feat_znorm") then
      set extrascl = -feat_znorm
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-prepend_anat") then
      set prepend_anat = 1
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-no_scale") then
      set Scale = 0
      set donext = 0   
   endif
   
   if ($donext && "$argv[$cnt]" == "-median_scale") then
      set Scale = 1
      set donext = 0   
   endif
   
   if ($donext && "$argv[$cnt]" == "-norm") then
      set Scale = 3
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-spnorm") then
      set Scale = 4
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-spnorm2") then
      set Scale = 5
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-aspnorm2") then
      set Scale = 6
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-mscl") then
      set Scale = 7
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-Mscl") then
      set Scale = 8
      set donext = 0   
   endif

   if ($donext && "$argv[$cnt]" == "-FATscl") then
      if ($cnt == `ccalc -i $Narg - 1`) then
         echo "Need two parameters after -FATscl such as -FATscl 25 75"
         goto END
      endif
      set Scale = 9
      @ cnt ++
      set fatScale = $argv[$cnt]
         #Sanity check, scale limits can be increased if needed
      if ($fatScale > 110 || $fatScale < 5) then
         echo "Looks like you -FATscl paramater 1 is bad."
         echo "Acceptable values should be <110 or >5, have $fatScale"
         goto END
      endif
      @ cnt ++
      set fatPerc = $argv[$cnt]
         #Sanity check, scale limits can be increased if needed
      if ($fatPerc > 100 || $fatPerc < 5) then
         echo "Looks like you -FATscl paramater 2 is bad."
         echo "Acceptable values should be <110 or >5, have $fatPerc "
         goto END
      endif
      set donext = 0   
   endif




   if ($donext && "$argv[$cnt]" == "-TT_Xform") then
      if ($cnt == $Narg) then
         echo "Need Affine xform in 1D file after -TT_Xform"
         goto END
      else 
         @ cnt ++
         set Mname = $argv[$cnt]
         if ("$Mname" != 'AUTO') then
            echo "Option -TT_Xform not ready for AUTO"
            goto BEND
         endif
         if ( ! -f $Mname && "$Mname" != 'AUTO') then
            echo "File $Mname not found"
            goto END
         endif
         set donext = 0   
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-scale_by_dset_median") then
      if ($cnt == $Narg) then
         echo "Need label after -scale_by_dset_median"
         goto END
      else 
         @ cnt ++
         set Scale = 2
         set ScaleVal = `3dBrickStat -median $argv[$cnt]`
         echo $ScaleVal
         set ScaleVal = $ScaleVal[2]
         set donext = 0   
      endif
      
   endif

   if ($donext && "$argv[$cnt]" == "-statlabel") then
      if ($cnt == $Narg) then
         echo "Need label after -statlabel"
         goto END
      else 
         @ cnt ++
         set olabel = $argv[$cnt]
         set donext = 0   
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-siglabel") then
      if ($cnt == $Narg) then
         echo "Need label after -siglabel"
         goto END
      else 
         @ cnt ++
         set sigset = $argv[$cnt]
         set donext = 0   
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-max_vox") then
      if ($cnt == $Narg) then
         echo "Need label after -max_vox"
         goto END
      else 
         @ cnt ++
         set max_vox = $argv[$cnt]
         set donext = 0   
      endif
   endif
   
   if ($donext && "$argv[$cnt]" == "-mask") then
      if ($cnt == $Narg) then
         echo "Need mask volume after -mask"
         goto END
      else
         @ cnt ++
         set localopen = 0
         set statopen = 0
         set inmask = $argv[$cnt]
         set donext = 0   
         #@ cnt ++
         #echo "MASK SET" $cnt $argv[$cnt]
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-feat_znorm_mask") then
      if ($cnt == $Narg) then
         echo "Need mask volume after -feat_znorm_mask"
         goto END
      else
         @ cnt ++
         set localopen = 0
         set statopen = 0
         set featmask = $argv[$cnt]
         set donext = 0   
         #@ cnt ++
         #echo "FEAT MASK SET" $cnt $argv[$cnt]
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-input") then
      if ($cnt == $Narg) then
         echo "Need volume for segmentation after -input"
         goto END
      else
         @ cnt ++
         set localopen = 0
         set statopen = 0
         set involume = "$argv[$cnt]"
         set donext = 0   
         #echo "INVOLUME SET" $cnt $argv[$cnt]
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-odir") then
      if ($cnt == $Narg) then
         echo "Need directory after -odir"
         goto END
      else
         @ cnt ++
         set odir = "$argv[$cnt]"
         if (! -d $odir) mkdir -p $odir
         if (! -d $odir) then
            echo "Failed to create $odir"
            goto END
         endif
         set donext = 0   
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-stat") then
      if ($cnt == $Narg) then
         echo "Need local stat names after -stat"
         goto END
      else
         @ cnt ++
         set localopen = 0
         set statvector = ($statvector $argv[$cnt])
         set donext = 0   
         set statopen = 1
      endif
   endif

   if ($donext && "$argv[$cnt]" == "-local") then
      if ($cnt == $Narg) then
         echo "Need neighborhood sizes after -local"
         goto END
      else
         @ cnt ++
         set statopen = 0
         set localvector = ($localvector $argv[$cnt])
         set donext = 0   
         set localopen = 1
      endif
   endif

  if ($donext) then
      if ($statopen == 1) then
         set statvector = ($statvector $argv[$cnt])
         @ cnt ++
      endif
      if ($localopen == 1) then
         set localvector = ($localvector $argv[$cnt])
         @ cnt ++
      endif
      if ($statopen == 0 && $localopen == 0) then
         echo "Parameter $argv[$cnt] not understood"
         apsearch -popt `basename $0` -word $argv[$cnt]
         goto END
      endif
   else 
      @ cnt ++
   endif 

end

if ($Scale == 6 && $prepend_anat == 1) then
   echo "Cannot use -aspnorm2 with -prepend_anat"
   goto BEND
endif

set statlabelvector = ()
foreach lstat ($statvector)
   if ($lstat =~ med*) then
      set statlabelvector = ($statlabelvector MEDIAN)
   else if ($lstat =~ mea*)  then
      set statlabelvector = ($statlabelvector mean)
   else if ($lstat =~ MAD)  then
      set statlabelvector = ($statlabelvector MAD)
   else if ($lstat =~ *skew*) then
      set statlabelvector = ($statlabelvector P2skew)
   else if ($lstat =~ *kurt*) then
      set statlabelvector = ($statlabelvector KURT)
   else if ($lstat =~ *FWHM*) then
      set statlabelvector = ($statlabelvector FWHMx FWHMy FWHMz)
   else if ($lstat =~ *diffs*) then
      set statlabelvector = ($statlabelvector AvgDif MinDif MaxDif)
   else if ($lstat =~ *perc*) then
      set i0 = `echo $lstat | cut -d ':' -f 2`
      set i1 = `echo $lstat | cut -d ':' -f 3`
      set ip = `echo $lstat | cut -d ':' -f 4`
      while ($i0 <= $i1) 
         set statlabelvector = ($statlabelvector perc:$i0)
         @ i0 += $ip
      end
   else
      echo "Don't have label for stat $lstat"
      set stat = 1
      goto END
   endif
end

goto RET_PARSE

HELP:
   echo ""
   echo "Usage: `basename $0` <-input DSET> <-stat STAT1 [STAT2...]> "
   echo "                     <-local R1 [R2 ...]> "
   echo "Calculate a set of local statisctics to form a signature (feature) set."
   echo "-input DSET: input dset"
   echo "-stat STAT: Type of localstat to compute. See 3dLocalstat -help"
   echo "            e.g. -stat mean median MAD P2skew kurt"
   echo "-local R: Radius of sphere which envelopes voxels for which STAT "
   echo "          STAT is derived."
   echo "            e.g. -local 1 2 3 4 6 8 10 13 16 19 "
   echo "-mask MASK: Mask volume restricting computation region"
   echo "-odir DIR: Output directory"
   echo "-prepend_anat: Add copy of DSET in feature vector. DSET is considered"
   echo "               to be a MEDIAN stat over a radius of 0. This option"
   echo "               will only work if you use at least one of 'mean' or "
   echo "               'median' as STAT."
   echo "               This option is useless with -aspnorm2 (see below)"
   echo ""
   echo "Scaling options:"
   echo "   -no_scale: Do not scale features. (scale 0)"
   echo "   -median_scale: Divide each sub-brick with its median which is"
   echo "               computed with @ScaleVolume -scale_by_median. "
   echo "               (scale 1)"
   echo "   -scale_by_dset_median: Divide by median over whole dset. (scale 2)"
   echo "   -norm: Scale dset with @ScaleVolume -norm.    (scale 3)"
   echo "   -spnorm: Scale median stats only."
   echo "         The set of median stats is demeaned, then divided by"
   echo "         the set of MAD values. (scale 4)" 
   echo "   -spnorm2: Scale median and MAD stats"
   echo "         For the set of median stats, demean then divide by"
   echo "         the last MAD feature."
   echo "         For the MAD stats, divide by the last MAD feature. (scale 5)"
   echo "   -aspnorm2: Lile -spnorm2, but add anatomical image to the "
   echo "           median feature set before scaling. (scale 6)" 
   echo "   -mscl: Scale the median stats by the last mean feature"
   echo "       Scale the MAD stats by the last mean feature. (scale 7)"
   echo "   -Mscl: Like spnorm2, BUT the mean is not removed from median stats"
   echo "       before scaling, AND mean stats are also subject to MAD scaling."
   echo "   -FATscl S P: Scale by P percentil value in sphere of radius S"
   echo "                Crude recommendation is 25 75"
   echo "                For now, P must be one of: 70, 75, 80, 85, 90, or 95"  
   echo "   -TT_Xform XMAT.1D: You can also create X Y Z coordinate features"
   echo "                      that are Z normalized. To do so you need to "
   echo "                      provide an affine transform that can be used"
   echo "                      to go between original and standard space."
   echo "                      The XMAT.1D expected here is the one generated"
   echo "                      by @auto_tlrc, but it can come from other sources"
   echo "                      as long as the following relationship holds:"
   echo "                          Xo = Mt Xt, where Xo and Xt are 4x1 "
   echo "                      coordinate vectors in original, and standard"
   echo "                      space, respectively."
   echo "               Note:  The transform need not be exact for these "
   echo "                      features to be of use." 
   echo ""
   echo "Extra Scaling:"
   echo "   -feat_znorm: After you're done applying the scaling options, "
   echo "            normalize the entire feature vector using "
   echo "            @ScaleVolume -feat_znorm"
   echo "   -feat_znorm_mask FSCMASK: Mask volume used for -feat_znorm"
   echo "                        If nothing is specified, 3dAutomask is used"
   echo ""
   echo "Example:"
   set ss = 12
   echo "   @CalculateSignatures -input AfniDataCropped/IBSR_${ss}_ana+orig. \\"
   echo "                     -stat median MAD P2skew kurt \\"
   echo "                     -statlabel medMADskewkurt   \\"
   echo "                     -local 1 2 3 4 6 8 10 13 16 19 \\"
   echo "                     -mask AfniDataCropped/IBSR_${ss}_ana+orig. \\"
   echo "                     -aspnorm2   \\"
   echo "                     -odir SegResults/s${ss}" 
   echo ""
   @global_parse -gopts_help

goto END

BEND:
set stat = 1
goto END

END:
exit $stat




