#! /bin/csh -f
###############################################################################
# hand register, surface-paint DTi data, conv to ASCII tables (10 min)
###############################################################################
# 20Jan2010 -- 0.1a: marty sereno
# 29Jan2010 -- 0.1b: check regdat name (paint) and $name (tkregister) match
# 07Feb2010 -- 0.1c: use new paint uniq paint vtx number
# 07Feb2010 -- 0.1d: big paste, cleanup
# 26May2010 -- 0.1e: accept variable length image prefixes
# 28May2010 -- 0.1f: volreg, avg, render, option-ify
# 29Apr2010 -- 0.1g: check input files
# 09Sep2010 -- 0.1h: change from -Fourier to -heptic
# 09Oct2010 -- 0.1i: bugs handling avgdir, propagate first register.dat
# 15Oct2010 -- 0.1j: -conv2 to for ima2brik'd FIL ima's, fix cp reg
# 11Mar2011 -- 0.1k: restart: TODO: re-reg to qT1, use sample between orig/pial
# 01Apr2011 -- 0.1m: new cmdline for MGH paint-between-orig-and-pial
# 25Oct2012 -- 0.1n: shiftreg.tcl after cpreg so not overwritten
# 02Nov2012 -- 0.1o: new FIL name format
set vers = 0.1o
# INPROG: spher harm rot invar, show diff normals have same spectrum
# INPROG: proj 5 closest to norm, plot on surf vs. 5 closest to perp plane
# INPROG:          vs. 5 closest to arbitrary direction (no norm project)
# INPROG: err: => outdirsuff: Undefined variable. (from dti2surf -doallreg)

### actions
set conv = 0
set conv2 = 0
set volreg = 0
set avgreps = 0
set manregB0 = 0
set manregT1 = 0
set cpreg = 0
set shiftreg = 0
set tobfloat = 0
set paint = 0
set zeropad = 0
set val2asc = 0
set pastedd = 0
set uniqvox = 0
set vtx2asc = 0
set bigpaste = 0
set render = 0
set parms = 0
set force = 0
set cleanup = 0
set realclean = 0

###############################################################################
# next section to be hand-edited in this script
###############################################################################
#set prefpref = f100924       # e.g., d100924-0002-00025
set prefpref = fd141069

### DTi scan parms -- hi-res
set rawscanpreflist = ( scan05+orig scan06+orig )  # just for -conv2
set scanpreflist = ( $prefpref-0005 $prefpref-0006 )  # -conv2 output 
set nslices = 62             # number of slices
set xysize = 128             # inplane x-y matrix
set inplane = 1.7188         # in plane x-y voxel size
set thick =  1.7             # slice thickness
set repdel = -3.6            # estimate during-scan B0-caused shift, in mm
### DTi scan parms -- lo-res
#set rawscanpreflist = ( scan03+orig scan04+orig )  # just for -conv2
#set scanpreflist = ( $prefpref-0003 $prefpref-0004 )  # -conv2 output
#set nslices = 52            # number of slices
#set xysize = 96             # inplane x-y matrix
#set inplane = 2.291670      # in plane x-y voxel size
#set thick = 2.3             # slice thickness
#set repdel = -1.6           # estimate during-scan B0-caused shift, in mm

### address indiv runs or avg
#set scanpref = $scanpreflist[1]   # first run
set scanpref = $scanpreflist[2]  # second run
#set scanpref = $prefpref-avg      # avg std-res runs (N.B.: can't do 2 avgs!)

### command line adjustable parm defaults
#set name = martys09         # SUBJECTS_DIR name (orig: martys)
#set name = marser-qT1       # SUBJECTS_DIR name (orig: martys)
set name = fredic-qT1        # SUBJECTS_DIR name (orig: martys)
#set newcurvflag = 0         # martys09 -> old curv
#set newcurvflag = 1         # marser-qT1 -> new curv
set newcurvflag = 0          # fredic-qT1 -> old!!
#set session = 100924MS      # FUNCTIONALS_DIR session (prev: 100413MS)
#set session = 100924MSb     # made copy to save old surface render
set session = 121031FD       # fred

###############################################################################
### register/paint parms
#set regtarg = orig          # SUBJECTS_DIR register target
set regtarg = orig.mgz       # SUBJECTS_DIR register target
#set usethickflag = 0        # abs mm (0) or fraction (1) of cortical thickness
set usethickflag = 1         # abs mm (0) or fraction (1) of cortical thickness
set smoothsteps = 4          # smooth steps along surface
#set paintsurf = orig1       # sample data using this surface
set paintsurf = white        # sample data using this surface
#set dmin = 0.75             # min along norm (if usethickflag, frac vs. mm)
#set dmax = 1.25             # max along norm (if usethickflag, frac vs. mm)
set dmin = 0.5               # min along norm (if usethickflag, frac vs. mm)
set dmax = 0.5               # max along norm (if usethickflag, frac vs. mm)

set dstep = 0.25             # step size along norm
set normop = avg             # operation on samples along normal
### render parms
set rendersurf = inflated    # render data on this surface
set outdirsuff = all         # infix to add to ASCII files output dir

### derived vars
set imagedir = $FUNCTIONALS_DIR/$session/image
set scriptsdir = $imagedir/scripts
set dmid = `echo "scale=2; ($dmax + $dmin)/2.0" | bc -l`  # for uniq paint vox

### help
if ($#argv < 1) then
  echo ""
  echo \
"usage: dti2surf [-action] ... [-force] [-cleanup] [-parm value] [...]"
  echo \
"usage: dti2surf ... |& tee dti2surf.log"
  echo ""
  echo "  raw scans (manually edit values in script)"
  echo "  -------------------------------------------------------------------"
  echo "  scanpreflist = $scanpreflist"
  echo "  curr scanpref = $scanpref"
  echo "  -------------------------------------------------------------------"
  echo ""
  echo "  files and binaries"
  echo "  -------------------------------------------------------------------"
  echo '  input files: 68 ANALYZE diffusion imgs in  $imagedir/raw'
  echo "  output files (for each hemi):"
  echo "    $scanpref-all-{lh,rh}-.txt/*.float (nohead surfpaint diff dirs)"
  echo "    {lh,rh}.$paintsurf.{vtx,norm,nei,uniq} (ASCII surf geometry)"
  echo \
    "    $scanpref-all-paste-{lh,rh}.txt: vtx#,xyz,normxyz,uniqID,68dirs (summ)"
  echo "  surfer binaries: calcvert, tkregister, paint, brik2bfloat, asc2float"
  echo "  AFNI binaries: to3d, 3dvolreg, 3dcalc"
  echo "  -------------------------------------------------------------------"
  echo ""
  echo "  -actions (multiple OK, fixed order)"
  echo "  -------------------------------------------------------------------"
  echo "  -parms     curr parm values (to change: dti2surf ... -parm <value>)"
  echo '     [next 3 affect all scans in $scanpreflist]'
  echo "  -conv      ANALYZE->BRIKs, create scandirs, mv conv'd BRIKs to them"
  echo "  -conv2     BRIKin1->BRIKs, create scandirs, mv conv'd BRIKs to them"
  echo "  -volreg    align scan2,3... to scan1 (if >1), -force to redo"
  echo "  -avgreps   avg repetitions (if >1), generates scandir w/avg infix"
  echo '  -doallavg  convert/volreg/average (all scans in $scanpreflist)'
  echo '     [next 11 apply only to current $scanpref]'
  echo "  -manregB0  reg 2nd B0 img->struct (if scanpref[2+], cp scanpref[1])"
  echo "  -cpreg     copy register.dat to other B0's, other dirs"
  echo "  -shiftreg  run shiftreg.tcl script to correct B0 drift"
  echo "  -tobfloat  convert DTi BRIK data to bfloat slices"
  echo "  -paint     paint DTi data onto $paintsurf between $dmin,$dmax above"
  echo "     [if -usethickflag: $dmin,$dmax are frac thickness instead of mm]"
  echo "  -zeropad   zeropad paint wfiles so every vtx incl (now paint does)"
  echo "  -val2asc   convert zero-padded vertex files to ASCII"
  echo "  -pastedd   paste diffs->file, 1 col/diffdir,->float fast MATLAB read"
  echo "  -uniqvox   make/pad/ascii uniq paintvox vtxlabels for search midpnt"
  echo "  -vtx2asc   ASCII dump vertex xyz,norms,neighbors,uniq to outdir"
  echo "  -bigpaste  vtx#,xyz,normxyz,uniqID,68dirs"
  echo "  -render    render all diff dirs onto rendersurf ($rendersurf)"
  echo '  -doallreg  manreg->end (just $scanpref), if outfiles exist, skip on)'
  echo "  -force     redo/overwrite anything as needed"
  echo "  -cleanup   rm bfloat/hdr, unpadded/txt wfiles, float, bigpaste"
  echo "  -realclean rm all but first register.dat (saved in scripts)"
  echo "  -------------------------------------------------------------------"
  echo "                                                         vers: $vers"
  exit
endif

### check infiles, binaries
foreach hemi (lh rh)
  set origcurv = $SUBJECTS_DIR/$name/surf/$hemi.curv
  if (! -e $origcurv) then
    echo "dti2surf: ### $origcurv (for 0-padding *.w files) not found"
    exit
  endif
  set fullpaintsurf = $SUBJECTS_DIR/$name/surf/$hemi.$paintsurf
  if (! -e $fullpaintsurf) then
    echo "dti2surf: ### $fullpaintsurf (for sampling data) not found"
    exit
  endif
end
# also need paste,cut,tail
set surferbins =  ( calcvert tkregister paint brik2bfloat asc2float )
set afnibins =  ( to3d 3dvolreg 3dcalc 3dbucket )
foreach bin ( $surferbins $afnibins )
  if ("`which $bin`" == "${bin}: Command not found.") then
    echo "dti2surf: ### required binary: $bin not on path (run newdefs)"
    exit
  endif
end

### getops, save non-option args (none currently)
set i = 1
set argv2 = ""  # non-option args
while ($i <= "$#argv")
  set arg = $argv[$i]
  # 0-arg
  if ("$arg" == "-conv") then
    set conv = 1
    @ i++; continue
  endif
  if ("$arg" == "-conv2") then
    set conv2 = 1
    @ i++; continue
  endif
  if ("$arg" == "-volreg") then
    set volreg = 1
    @ i++; continue
  endif
  if ("$arg" == "-avgreps") then
    set avgreps = 1
    @ i++; continue
  endif
  if ("$arg" == "-manregB0") then
    set manregB0 = 1
    @ i++; continue
  endif
  if ("$arg" == "-cpreg") then
    set cpreg = 1
    @ i++; continue
  endif
  if ("$arg" == "-shiftreg") then
    set shiftreg = 1
    @ i++; continue
  endif
  if ("$arg" == "-tobfloat") then
    set tobfloat = 1
    @ i++; continue
  endif
  if ("$arg" == "-paint") then
    set paint = 1
    @ i++; continue
  endif
  if ("$arg" == "-zeropad") then
    set zeropad = 1
    @ i++; continue
  endif
  if ("$arg" == "-val2asc") then
    set val2asc = 1
    @ i++; continue
  endif
  if ("$arg" == "-pastedd") then
    set pastedd = 1
    @ i++; continue
  endif
  if ("$arg" == "-uniqvox") then
    set uniqvox = 1
    @ i++; continue
  endif
  if ("$arg" == "-vtx2asc") then
    set vtx2asc = 1
    @ i++; continue
  endif
  if ("$arg" == "-bigpaste") then
    set bigpaste = 1
    @ i++; continue
  endif
  if ("$arg" == "-render") then
    set render = 1
    @ i++; continue
  endif
  if ("$arg" == "-parms") then
    set parms = 1
    @ i++; continue
  endif
  if ("$arg" == "-doallavg") then
    set conv2 = 1
    set volreg = 1
    set avgreps = 1
    @ i++; continue
  endif
  if ("$arg" == "-doallreg") then
    set manregB0 = 1
    set cpreg = 1
    set shiftreg = 1
    set tobfloat = 1
    set paint = 1
    set zeropad = 1
    set val2asc = 1
    set pastedd = 1
    set uniqvox = 1
    set vtx2asc = 1
    set bigpaste = 1
    set render = 1
    @ i++; continue
  endif
  if ("$arg" == "-force") then
    set force = 1
    @ i++; continue
  endif
  if ("$arg" == "-cleanup") then
    set cleanup = 1
    @ i++; continue
  endif
  if ("$arg" == "-realclean") then
    set realclean = 1
    @ i++; continue
  endif
  # 1-arg
  @ i2 = $i + 1
  if ($#argv >= $i2) then
    if ("$arg" == "-name") then
      set name = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-newcurvflag") then
      set newcurvflag = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-session") then
      set session = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-nslices") then
      set nslices = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-xysize") then
      set xysize = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-inplane") then
      set inplane = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-thick") then
      set thick = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-regtarg") then
      set regtarg = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-usethickflag") then
      set usethickflag = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-smoothsteps") then
      set smoothsteps = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-paintsurf") then
      set paintsurf = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-dmin") then
      set dmin = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-dmax") then
      set dmax = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-dstep") then
      set dstep = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-normop") then
      set normop = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-rendersurf") then
      set rendersurf = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-outdirsuff") then
      set outdirsuff = $argv[$i2]
      @ i+=2; continue
    endif
  endif
  # errs, non-options args
  if ("$arg" =~ "-*") then
    echo "option: $arg => bad option, or missing arg(s)"
    exit
  else
    set argv2 = "$argv2 $argv[$i]"  # argv2: saved non-option args (none)
  endif
  @ i++
end

if ($parms) then
  echo "==================================================================="
  echo "curr values of parms (to change: dti2surf ... -parm <value> ...)"
  echo "==================================================================="
  foreach parm ( scanpref imagedir \
                 name newcurvflag session \
                 nslices xysize inplane thick \
                 regtarg usethickflag smoothsteps paintsurf \
                 dmin dmax dstep normop \
                 rendersurf outdirsuff )
    set val = `eval echo '$'$parm`  # csh de-reference (get val given varname)
    echo "  $parm = $val"
  end
endif

if ($conv) then
  echo "==================================================================="
  echo "convert ANALYZE files, create scandirs, mv conv'd BRIKs into them"
  echo "==================================================================="
  cd $imagedir/raw
  foreach everyscanpref ( $scanpreflist )
    foreach hdr ($everyscanpref*.hdr)   # conv all reps (vs. mostly work on 1)
      set namelen = `echo $hdr | wc -c` # fMT0941-0003-00055-000055-01.hdr =>
      @ endpref = $namelen - 15         # fMT0941-0003-00055
      set imagepref = `echo $hdr | cut --characters=1-$endpref`
      if (! -e ../$imagepref/$imagepref+orig.BRIK || $force) then
        if ($force) rm -f ../$imagepref/$imagepref+orig.BRIK # no AFNIoverwrite
        #set halfx = `echo "scale=3; ($xysize * $inplane)/2.0" | bc -l`
        #set halfy = $halfx
        #set halfz = `echo "scale=3; ($nslices * $thick)/2.0" | bc -l`
        #set fovopts = "-xFOV ${halfx}R-L -yFOV ${halfy}A-P -zSLAB ${halfz}I-S"
        set fovopts = "-orient RPI"    # from to3d raw mosaics, no args
        set cmd = "to3d -prefix $imagepref $fovopts $hdr"
        echo $cmd
        $cmd
        if (! -e ../$imagepref) mkdir ../$imagepref
        mv $imagepref+orig.* ../$imagepref
        echo "dti2surf: moved $imagepref HEAD/BRIK into scandir: ../$imagepref"
      else
        echo "dti2surf: ../$imagepref/$imagepref+orig.BRIK already made"
      endif
    end
  end
endif

if ($conv2) then
  echo "==================================================================="
  echo "unpack BRIK-in-1 files, create scandirs, mv unpacked BRIKs into them"
  echo "==================================================================="
  cd $imagedir
  foreach scanpref ( $rawscanpreflist )   # scan02+orig
    set subbrik = 0
    set subbriks = 63
    set scannum = 00`echo $scanpref | cut -c 5-6`  # 02 -> 0002
    while ($subbrik < $subbriks)
      if ($subbrik < 10) then
        set diffdirnum = 0000${subbrik}
      else
        set diffdirnum = 000${subbrik}
      endif
      set outbrikpref = $prefpref-$scannum-$diffdirnum  # f100924-0002-00018
#xxxxx -- TODO: check out exists, skip to next if not force (curr is force)
      if (-e $outbrikpref+orig.BRIK) rm $outbrikpref+orig.BRIK
      if (-e $outbrikpref+orig.HEAD) rm $outbrikpref+orig.HEAD
### vars in "" get subst'd, even if in '' protecting brackets from shell
#set cmd =  \
#  "3dbucket -prefix $outbrikpref '$imagedir/raw/zzAFNI/$scanpref[$subbrik]'"
      set bindex = "[$subbrik]" # avoid interpretation in next as csh array ind
      set cmd =  \
        "3dbucket -prefix $outbrikpref '$imagedir/raw/zzAFNI/$scanpref$bindex'"
      echo "$cmd"
      echo "$cmd" > zz.csh
      csh zz.csh
      if (! -e $outbrikpref) then
        echo "mkdir $outbrikpref"
        mkdir $outbrikpref
      endif
      echo "mv $outbrikpref+orig.* $outbrikpref"
      mv $outbrikpref+orig.* $outbrikpref
      @ subbrik++
    end
  end
  rm -f zz.csh
endif

if ($volreg) then
  echo "==================================================================="
  echo "3dvolreg each diffdir BRIK to corresponding one from 1stscan (if >1)"
  echo "==================================================================="
  if ($#scanpreflist == 1) then
    echo "dti2surf: only one scan in scanpreflist, skipping 3dvolreg"
    goto skipvolreg
  endif
  set targscanpref = $scanpreflist[1]       # fMT0941-0002
  set movescanpreflist = ( $scanpreflist[2-] )   # fMT0941-000[346]
  # example to reg: fMT0941-0003-00057/fMT0941-0003-00057+orig.BRIK
  cd $imagedir
  foreach targscan ($targscanpref-00???)  # 68 (7+61) (??? in case more)
    set namelen = `echo $targscan | wc -c`
    @ begindiffnum = $namelen - 5              # fMT0941-0003-00055 => 00055
    set diffnum = `echo $targscan | cut --characters=$begindiffnum-`
    foreach movescanpref ($movescanpreflist)  # num avgs each direction
      set movescan = $movescanpref-$diffnum
      cd $imagedir/$movescan  # AFNI reads anywhere, but only writes local
      set fulltargbrik = $imagedir/$targscan/$targscan+orig.BRIK
      set fulltarghead = $imagedir/$targscan/$targscan+orig.HEAD
      set fullmovebrik = $imagedir/$movescan/$movescan+orig.BRIK
      set fullmovehead = $imagedir/$movescan/$movescan+orig.HEAD
      if (! -e $fulltargbrik && ! -e $fulltarghead) then
        echo "dti2surf: ### 3dvolreg input file not found: $fulltargbrik"
        exit
      endif
      if (! -e $fullmovebrik && ! -e $fullmovehead) then
        echo "dti2surf: ### 3dvolreg input file not found: $fullmovebrik"
        exit
      endif
      set regstem = $movescan-vreg
      set regbrik = $movescan-vreg+orig.BRIK
      set reghead = $movescan-vreg+orig.HEAD
      set noregbrik = $movescan-noreg+orig.BRIK
      set noreghead = $movescan-noreg+orig.HEAD
      if (! -e $noregbrik || $force) then
        echo "==== outstem: $regstem ========================================="
        if (-e $noregbrik && $force) then
          echo "dti2surf: re-doing 3dvolreg alignment (move back noreg BRIK)"
          mv -f $noregbrik $fullmovebrik
        endif
        # defaults: -twoblur=2.0 -rot_thresh=0.03 -x_thresh=0.02 -delta=0.7
        # -Fourier left a big rot, not changed by any of above
        #set opts = "-twodup -twopass -heptic -verbose"
        set opts = "-twodup -twopass -heptic -verbose -1Dfile motion.1D"
        set cmd = \
          "3dvolreg $opts -prefix $regstem -base $fulltargbrik $fullmovebrik"
        echo "dti2surf: $cmd"
        $cmd
        mv $fullmovebrik $noregbrik
        mv $fullmovehead $noreghead
        mv $regbrik $fullmovebrik
        mv $reghead $fullmovehead
        echo "dti2surf: mv orig->noreg, vreg->orig"
      else
        echo "dti2surf: $fullmovebrik already 3dvolreg'd (use -force to redo)"
      endif
    end
  end
endif
skipvolreg:

if ($avgreps) then
  echo "==================================================================="
  echo "average scan repetitions"
  echo "==================================================================="
  if ($#scanpreflist == 1) then
    echo "dti2surf: only one scan in scanpreflist, skipping average reps"
    goto skipavgreps
  endif
  cd $imagedir
  # fMT0941-0002-00041 => $scanname-$scannum-$diffnum
  foreach scan1 ( $scanpreflist[1]-00??? )
    set namelen = `echo $scan1 | wc -c`
    @ endscanname = $namelen - 12
    set scanname = `echo $scan1 | cut --characters=1-$endscanname`
    @ beginscannum = $namelen - 10
    @ endscannum = $namelen - 7
    set scannum = `echo $scan1 | cut --characters=$beginscannum-$endscannum`
    @ begindiffnum = $namelen - 5
    set diffnum = `echo $scan1 | cut --characters=$begindiffnum-`
    echo "dti2surf: working on diff-dir num: $diffnum ($scanname-$scannum)"
    # get briklist
    set avgbriklist = ( )
    foreach scanpreftoavg ($scanpreflist)
      set brik = \
        $imagedir/$scanpreftoavg-$diffnum/$scanpreftoavg-$diffnum+orig.BRIK
      if (! -e $brik) then
        echo "dti2surf: ### 3dcalc input file not found: $brik"
        exit
      endif
      set avgbriklist = ( $avgbriklist $brik )
    end
    # do avg
    set avgscannum = avg
    set avgdir = $imagedir/$scanname-$avgscannum-$diffnum
    if (! -e $avgdir) mkdir $avgdir
    cd $avgdir  # AFNI reads anywhere, but only writes locally
    set avgbrikstem = $scanname-$avgscannum-$diffnum
    if (! -e $avgbrikstem+orig.BRIK || $force) then
      if ($force) rm -f $avgbrikstem+orig.BRIK  # no AFNI overwrite
      set taglist = (a b c d e f g h i j k l m n o p q r s t u v w x y z)
      set cmd = "3dcalc -verbose"
      set afniexpr = ""
      set i = 1
      foreach brik ($avgbriklist)
        if ($i == 1) then
          set afniexpr = $taglist[$i]
        else
          set afniexpr = "$afniexpr+$taglist[$i]"
        endif
        set cmd = "$cmd -$taglist[$i] $brik"
        @ i++
      end
      @ i--
      set cmd = ($cmd -expr "($afniexpr)/$i.0" -prefix $avgbrikstem)
      echo ""
      echo $cmd
      $cmd
    else
      echo "dti2surf: $avgbrikstem+orig.BRIK already made"
    endif
  end
endif
skipavgreps:

######################################################################
# all following operate only on current $scanpref (maybe avgdir)
######################################################################

if ($manregT1) then
  ### TODO
  echo "first register T1 align scan, cp reg to next for verify/touchup"
endif

if ($manregB0) then
  echo "==================================================================="
  echo "manually register $scanpref image (2nd B0) to structurals"
  echo "==================================================================="
  cd $imagedir/$scanpref-00001   # first B0 not yet saturated so use second
  forceMSB $scanpref-00001+orig.BRIK
  if (! -e register.dat) then    # make blank only for scanpreflist[1]
    if ("$scanpref" == "$scanpreflist[1]") then
      echo "dti2surf: making identity register.dat"
      echo $name              > register.dat
      echo $inplane          >> register.dat
      echo $thick            >> register.dat
      echo 0.20              >> register.dat
      echo "1.0 0.0 0.0 0.0" >> register.dat
      echo "0.0 1.0 0.0 0.0" >> register.dat
      echo "0.0 0.0 1.0 0.0" >> register.dat
      echo "0.0 0.0 0.0 1.0" >> register.dat
    else
      if (-e $imagedir/$scanpreflist[1]-00001/register.dat) then
        cp $imagedir/$scanpreflist[1]-00001/register.dat .
      else
        echo "manregB0: ### no register.dat in $scanpreflist[1] to cp to curr"
        exit
      endif
    endif
  else
    echo "dti2surf: using existing register.dat"
  endif
  cd $imagedir/scripts
  set echo
  # next fails if instead: set cmd =, echo cmd, cmd
  echo "pwd = `pwd`"
  tkregister \
    $imagedir/$scanpref-00001 \
    $SUBJECTS_DIR/$name/mri/$regtarg \
    -movformat $scanpref-00001+orig.BRIK \
    -nslices $nslices \
    -reps 1 \
    -imres $xysize $xysize \
    -regdat $imagedir/$scanpref-00001/register.dat
  unset echo
  cp $imagedir/$scanpref-00001/register.dat $imagedir/scripts  # backup
endif

if ($cpreg) then
  echo "==================================================================="
  echo "copy manually-obtained register.dat into all $scanpref dirs"
  echo "==================================================================="
  cd $imagedir
  if (-e $scanpref-00001/register.dat) then
    set regname = `awk 'FNR==1 {print $1}' $scanpref-00001/register.dat`
    if ($regname != $name) then
      echo "dti2surf: ### name mismatch: register.dat=$regname vs script=$name)"
      echo "dti2surf: ### fix: paint (but not tkregister!) uses regdat name"
      exit
    endif
  endif
  foreach dir ($scanpref*)
    if ($dir == $scanpref-00001) continue
    if (-e $dir/register.datORIG && $force) then
      rm -f $dir/register.datORIG
    endif
    if (! -e $dir/register.dat || $force) then
      if (! -e $scanpref-00001/register.dat) then
        echo "dti2surf: ### register file to copy not found:"
        echo "   $scanpref-00001/register.dat"
        exit
      endif
      set cmd = "cp $scanpref-00001/register.dat $dir"
      echo $cmd
      $cmd
    else
     echo "dti2surf: $dir/register.dat already exists"
    endif
  end
endif

if ($shiftreg) then
  echo "==================================================================="
  echo "correct B0-induced drift for $scanpref"
  echo "==================================================================="
  cd $scriptsdir
  echo "./shiftreg.tcl $imagedir $scanpref $repdel"
  ./shiftreg.tcl $imagedir $scanpref $repdel
endif

if ($tobfloat) then
  echo "==================================================================="
  echo "convert DTi data to bfloat slices (TODO: make paint read BRIK)"
  echo "==================================================================="
  cd $imagedir
  foreach dir ($scanpref-00???)  # skip $scanpref-all, -avg- scanpref infix OK
    cd $imagedir/$dir
    set stem = ${dir}+orig    # orig embedded in stem from now on
    if (! -e ${stem}_000.bfloat || $force) then
      if (! -e $stem.BRIK) then
        echo "dti2surf: ### brik2bfloat input file: $stem.BRIK not found"
        exit
      endif
      brik2bfloat $stem $stem 0
    else
      echo "dti2surf: ${stem}_000.bfloat already exists"
    endif
  end
endif

if ($paint) then
  echo "==================================================================="
  echo "paint onto $paintsurf"
  echo "==================================================================="
  cd $imagedir
  foreach dir ($scanpref-00???)  # skip $scanpref-all, -avg- scanpref infix OK
    echo "cd $imagedir/$dir"
    cd $imagedir/$dir
    set stem = ${dir}+orig
    foreach hemi (lh rh)
      if (! -e ./$stem-$hemi.w || $force) then
        if (! -e ${stem}_000.bfloat) then
          echo "dti2surf: ### paint input file: ${stem}_000.bfloat not found"
          exit
        endif
        set echo
        if ($usethickflag) then
          ### use latest mri_vol2surf
          #setenv FREESURFER_HOME /usr/local/freesurfer-5.0.0-cent4-64
          #source $FREESURFER_HOME/FreeSurferEnv.csh 
          ### what formats does --mov take?
          ### old multifile bfloat format not recognized?
          ### could just make my paint read thickness
          #set stem = f100924-0004-00000+orig
          #set surffwhm = 4.0
          #set hemi = rh
          #set dfrac = 0.5
          #mri_vol2surf \
          #  --mov ${stem}_%03d.bfloat \
          #  --reg register.dat \
          #  --surf-fwhm $surffwhm \
          #  --hemi $hemi \
          #  --projfrac $dfrac \
          #  --interp trilinear \
          #--o ./$stem-$hemi.w-zzzz
          ### back to FreeSurfer0.8
          #pushd /buc03/usr1/local/FreeSurfer0.8
          #source FreeSurferEnv.csh8.5
          #popd
          ### [paint now does thickness-file-based frac, surface-smooth]
          # fraction of cortical thickness from surf
          paint \
            ${stem}_%03d.bfloat $hemi $paintsurf ./$stem-$hemi.w \
            -imageoffset 0 -nslices $nslices \
            -smooth $smoothsteps \
            -dfracmin $dmin -dfracmax $dmax -dstep $dstep -normop $normop \
            -regdat register.dat
        else
          # abs mm from surf
          paint \
            ${stem}_%03d.bfloat $hemi $paintsurf ./$stem-$hemi.w \
            -imageoffset 0 -nslices $nslices \
            -smooth $smoothsteps \
            -dmin $dmin -dmax $dmax -dstep $dstep -normop $normop \
            -regdat register.dat
        endif
        unset echo
      else
        echo "dti2surf: ./$stem-$hemi.w already exists"
      endif
    end
  end
endif


if ($zeropad) then
  echo "==================================================================="
  echo "pad *.w files to contain all vertices (no-data vertices -> 0.0)"
  echo "==================================================================="
  cd $imagedir
  foreach dir ($scanpref-00???)   # skip $scanpref-all, -avg- scanpref infix OK
    cd $imagedir/$dir
    set stem = ${dir}+orig
    foreach hemi (lh rh)
      if (! -e $stem-$hemi.nopad.w || $force) then
        if (! -e $stem-$hemi.w) then
          echo "dti2surf: ### zeropad infile: $stem-$hemi.w not found"
          exit
        endif
        if (! -e $SUBJECTS_DIR/$name/surf/$hemi.curv) then
          echo "dti2surf: ### zeropad input file:"
          echo "   $SUBJECTS_DIR/$name/surf/$hemi.curv not found"
          exit
        endif
        set echo
        mv $stem-$hemi.w $stem-$hemi.nopad.w
        set padarg = -padvalfile
        if ($newcurvflag) set padarg = -padvalfilenc
#xxxxxxxx -- calcvert mis-read vertex count of oldcurv treated as newcurv
#calcvert -padvalfilenc 
#    fd141069-0003-00000+orig-lh.nopad.w
#    /buc05/usr0/subjects/fredic-qT1/surf/lh.curv
#    fd141069-0003-00000+orig-lh.w
# calcvert: infile: /buc05/usr0/subjects/fredic-qT1/surf/lh.curv
# (68675327 vertices, -234884865 faces)
        calcvert $padarg \
          $stem-$hemi.nopad.w \
          $SUBJECTS_DIR/$name/surf/$hemi.curv \
          $stem-$hemi.w
        unset echo
      else
        echo "dti2surf: $stem-$hemi.nopad.w already exists"
      endif
    end
  end
endif

if ($val2asc) then
  echo "==================================================================="
  echo "convert vertex value files (*.uniq.w, *.w) to ASCII"
  echo "==================================================================="
  cd $imagedir
  foreach dir ($scanpref-00???)  # skip $scanpref-all, -avg- scanpref infix OK
    cd $imagedir/$dir
    set stem = ${dir}+orig
    foreach hemi (lh rh)
      if (! -e $stem-$hemi.w.txt || $force) then
        if (! -e $stem-$hemi.w) then
          echo "dti2surf: ### wfile->ASCII inp: $stem-$hemi.w not found"
          exit
        endif
        set echo
        calcvert -convert -valfilein -asciiout \
          $stem-$hemi.w \
          $stem-$hemi.w.txt
        unset echo
      else
        echo "dti2surf: $stem-$hemi.w.txt already exists"
      endif
    end
  end
endif

if ($pastedd) then
  echo "==================================================================="
  echo "strip header,vtxnums, paste->1file in outdir, each diff direct 1col"
  echo "==================================================================="
  cd $imagedir
  if (! -e $scanpref-$outdirsuff) mkdir $scanpref-$outdirsuff
  cd $scanpref-$outdirsuff
  foreach hemi (lh rh)
    if (! -e $scanpref-$outdirsuff-$hemi.txt || $force) then
      echo "=== working on: $hemi ==="
      set filelist = ""
      set i = 0
      # foreach diffusion direction directory (ddd)
      foreach dddir (../$scanpref-00???) # skip $scanpref-all, -avg- infix OK
        set wfile = $dddir/$scanpref-00???+orig-$hemi.w.txt
        echo "infile: $wfile"
        set tmpfile = Tmp$i-$hemi.txt
        tail --lines=+3 $wfile | awk '{print $2}' > $tmpfile
        set filelist = "$filelist $tmpfile"
        @ i++
      end
      if ("$filelist" == "") then
        echo "dti2surf: ### empty list of ASCII diff dir files to paste"
        exit
      endif
      paste $filelist > $scanpref-$outdirsuff-$hemi.txt
      echo "dti2surf: outfile: $scanpref-$outdirsuff-$hemi.txt ($i columns)"
      echo "dti2surf: removing tmpfiles..."
      rm Tmp*-$hemi.txt
      # for MATLAB import (ASCII import unusably slow)
      echo "dti2surf: converting ASCII table to float stream for MATLAB"
      asc2float $scanpref-$outdirsuff-$hemi.txt
    else
      echo "dti2surf: $scanpref-$outdirsuff-$hemi.txt already exists"
    endif
  end
endif

if ($uniqvox) then
  echo "==================================================================="
  echo "generate/pad/ascii uniq paintvox vtxlabels for search midpoint"
  echo "==================================================================="
  echo "dti2surf: calc uniq voxel id's at $dmid mm along vtx norm"
  set dir = $scanpref-00001
  # only once for register.dat in first diffusion direction directory
  cd $imagedir/$dir
  set stem = ${dir}+orig   # was: set stem = `basename *.BRIK .BRIK`
  foreach hemi (lh rh)
    # generate
    if (! -e ./$stem-$hemi.uniq.w || $force) then
      if (! -e ${stem}_000.bfloat) then
        echo "dti2surf: ### uniqvox input file ${stem}_000.bfloat not found"
        exit
      endif
      set echo
      paint \
        -uniqvox \
        ${stem}_%03d.bfloat $hemi $paintsurf ./$stem-$hemi.uniq.w \
        -imageoffset 0 -nslices $nslices \
        -dmin $dmid -dmax $dmid -dstep $dstep -normop $normop \
        -regdat register.dat
      unset echo
    else
      echo "dti2surf: ./$stem-$hemi.uniq.w already exists"
    endif
    # pad (add no-data vertices, set to zero)
    if (! -e ${dir}+orig-$hemi.uniq.nopad.w || $force) then
      if (! -e ${dir}+orig-$hemi.uniq.w) then
        echo "dti2surf: ### wfile to pad ${dir}+orig-$hemi.uniq.w not found"
        exit
      endif
      set echo
      mv ${dir}+orig-$hemi.uniq.w ${dir}+orig-$hemi.uniq.nopad.w
      set padarg = -padvalfile
      if ($newcurvflag) set padarg = -padvalfilenc
      calcvert $padarg \
        ${dir}+orig-$hemi.uniq.nopad.w \
        $SUBJECTS_DIR/$name/surf/$hemi.curv \
        ${dir}+orig-$hemi.uniq.w
      unset echo
    else
      echo "dti2surf: ${dir}+orig-$hemi.uniq.nopad.w already exists"
    endif
    # convert to ASCII
    if (! -e ${dir}+orig-$hemi.uniq.w.txt || $force) then
      if (! -e ${dir}+orig-$hemi.uniq.w) then
        echo "dti2surf: ### ->ASCII infile ${dir}+orig-$hemi.uniq.w not found"
        exit
      endif
      set echo
      calcvert -convert -valfilein -asciiout \
        ${dir}+orig-$hemi.uniq.w \
        ${dir}+orig-$hemi.uniq.w.txt
      unset echo
    else
      echo "dti2surf: ${dir}+orig-$hemi.uniq.w.txt already exists"
    endif
  end
endif

if ($vtx2asc) then
  echo "==================================================================="
  echo "dump ASCII vertex-xyz/norms/neigh, move all to outdir, save reg"
  echo "==================================================================="
  cd $imagedir/$scanpref-$outdirsuff
  # vtx, norm, neigh
  foreach dtype (vtx norm neigh)
    foreach hemi (lh rh)
      if (! -e $hemi.$paintsurf.$dtype || $force) then
        set fullpaintsurf = $SUBJECTS_DIR/$name/surf/$hemi.$paintsurf
        if (! -e $fullpaintsurf) then
          echo "dti2surf: ### surface for vtx dump $fullpaintsurf not found"
          exit
        endif
        set echo
        paint -dump $dtype $name $hemi $paintsurf
        mv $SUBJECTS_DIR/$name/surf/$hemi.$paintsurf.$dtype .
        unset echo
      else
        echo "dti2surf: `pwd`/$hemi.$paintsurf.$dtype already made"
      endif
    end
  end
  # reformat ascii uniqvox (N.B.: register.dat-specific, unlike vtx,norm,neigh)
  set dir = $scanpref-00001
  set dtype = uniq
  foreach hemi (lh rh)
    if (! -e $hemi.$paintsurf.$dtype || $force) then
      set echo
      #mv $imagedir/$dir/${dir}+orig-$hemi.uniq.w.txt $hemi.$paintsurf.$dtype
      set wfiletxt = $imagedir/$dir/${dir}+orig-$hemi.uniq.w.txt
      if (! -e $wfiletxt) then
        echo "dti2surf: ### uniq vtx dump to reformat $wfiletxt not found"
        exit
      endif
      /bin/echo -e "#vtx\tuniqID" > $hemi.$paintsurf.$dtype
      tail --lines=+3 $wfiletxt | awk '{printf "%d\t%d\n",$1,$2}' \
        >> $hemi.$paintsurf.$dtype
      unset echo
    else
      echo "dti2surf: `pwd`/$hemi.$paintsurf.$dtype already made"
    endif
  end
  # save register.dat to outdir
  cp $imagedir/$scanpref-00001/register.dat .
endif

if ($bigpaste) then
  echo "==================================================================="
  echo "big paste: vtx#,xyz,normxyz,uniqID,68dti"
  echo "==================================================================="
  cd $imagedir/$scanpref-$outdirsuff
  foreach hemi (rh lh)
    set outfile = $scanpref-all-paste-$hemi.txt
    if (! -e $outfile || $force) then
      # ASCII: vtx,norm,uniq => 1 comment line; 68dti => bare for asc2float
      if (! -e $hemi.$paintsurf.vtx) then
        echo "dti2surf: ### vtx dump to paste $hemi.$paintsurf.vtx not found"
        exit
      endif
      if (! -e $hemi.$paintsurf.norm) then
        echo "dti2surf: ### vtx dump to paste $hemi.$paintsurf.norm not found"
        exit
      endif
      if (! -e $hemi.$paintsurf.uniq) then
        echo "dti2surf: ### vtx dump to paste $hemi.$paintsurf.uniq not found"
        exit
      endif
      /bin/echo -e "#vtx\tx\ty\tz\tnx\tny\tnz\tvoxID\t68dti.." > $outfile
      tail --lines=+2 $hemi.$paintsurf.vtx > Tmp01
      tail --lines=+2 $hemi.$paintsurf.norm \
        | awk '{printf "%f\t%f\t%f\n",$2,$3,$4}' > Tmp02
      tail --lines=+2 $hemi.$paintsurf.uniq | awk '{print $2}' > Tmp03
      paste Tmp01 Tmp02 Tmp03 $scanpref-$outdirsuff-$hemi.txt >> $outfile
      rm Tmp01 Tmp02 Tmp03
      echo "dti2surf: big outfile: $outfile"
    else
      echo "dti2surf: $outfile already made"
    endif
  end
endif

if ($render) then
  echo "==================================================================="
  echo "render each diffusion dir onto surface, both hemis (render.tcl)"
  echo "==================================================================="
  cd $imagedir
  foreach scandir ($scanpref-00???)
    foreach hemi (lh rh)
      set outfile = $imagedir/rgb/$scandir-$hemi-$rendersurf-lat.rgb
      if (! -e $outfile || $force) then
        set wfile = \
          $FUNCTIONALS_DIR/$session/image/$scandir/$scandir+orig-$hemi.w
        if (! -e $wfile) then
          echo "dti2surf: ### wfile to render $wfile not found"
          exit
        endif
        cd $scriptsdir
        set tclenv = "dir=$scandir floatstem=$scandir+orig rgbname=$scandir"
        # render.tcl: assembles $session/image/$dir/$floatstem-$hemi.w
        echo "env $tclenv tksurfer -$name $hemi $rendersurf -tcl render.tcl"
        env $tclenv tksurfer -$name $hemi $rendersurf -tcl render.tcl
      else
        echo "dti2surf: $outfile already made"
      endif
    end
  end
endif

if ($cleanup) then
  echo "==================================================================="
  echo "cleanup: rm bfloat/hdr, unpadded/txt wfiles, float, bigpaste"
  echo "==================================================================="
  cd $imagedir
  foreach dir ($prefpref-*)
    if ($dir =~ *$outdirsuff) continue
    cd $imagedir/$dir
    rm $scanpref-*+orig_???.hdr
    rm $scanpref-*+orig_???.bfloat
    rm $scanpref-*+orig-?h.nopad.w
    rm $scanpref-*+orig-?h.w.txt
  end
  cd $imagedir/$scanpref-$outdirsuff
  rm $scanpref-all-?h.txt.float
  rm $scanpref-all-paste-?h.txt
endif

if ($realclean) then
  echo "==================================================================="
  echo "realclean: rm EVERYTHING but first register.dat and orig tarfiles?"
  echo "==================================================================="
  echo "(y|N <ret>)"
  set resp = $<
  if ($resp != "y" && $resp != "Y" && $resp != "yes") then
    echo "  ...quitting"
    exit
  endif
  cd $imagedir
  cp $scanpreflist[1]-00001/register.dat scripts/register.dat
  rm rgb/*
  rm $prefpref-*/*
  rm raw/*.ima
  rm -rf raw/zz*
endif

if ($pastedd || $uniqvox || $vtx2asc || $bigpaste) then
  echo ""
  echo "==================================================================="
  echo "done -- final output in: $imagedir/$scanpref-$outdirsuff"
  echo "==================================================================="
endif

