#! /usr/bin/tclsh
#############################################################################
# tksurfer script: eccen-views  [disp phase-encoded data on 3D folded/unfolded]
##############################################################################
### recent changes in lib/tcl scripts (keep all here)
# 11/06/08 -- add polar readstat option to eccen, twocond
# 11/06/09 -- comment out all defaults here (else cmdline opts overwritten)
# 11/06/10 -- force correct complexvalflag
# 11/06/22 -- add setfile rawdata, regdat
# 11/09/25 -- rm setfile rawdata (except real list), done in new tksurfer
# 11/10/14 -- new 12-way modify complex amp mess
# 12/02/16 -- movie360/{phase,offset}movie/save{views,flat} respect tiffoutflag
# 12/02/18 -- {phase,offset}movie respect abspath rgbname
# 12/03/07 -- fix real-flat missing statname crash
# 12/04/20 -- catch errs, defaults/help for standalone use, cp'd to others
# 12/12/02 -- real-{views/flat}:read mask if statmaskampflag, maskfloatstem set
# 13/10/27 -- setdefpatchview: set patch matches ?h.{occip,full}*.patch.flat*
# 13/10/31 -- movie360.tcl: cleanup, add diagonal and zoom-unzoom
# 13/11/02 -- readenv *before* setdefpatchview in flat script so uses patchname
# 14/01/10 -- rm ### in message if -mean- to subst not found
# 14/01/10 -- remove defaulting non-existent cplxstatname?'s, add csurf comment
# 14/01/10 -- add log message when tcl script reads stats
# 14/04/29 -- pol/ecc/two: if $maskfloatstem passed to tcl via env, overrides
# 14/04/29 -- real: if $floatstem matches *.mgh, *don't* append -$hemi.w
# 14/05/01 -- fs-make.tcl: also write fs/fm as wfiles, uses setfile, needs $dir
# 14/05/04 -- {movie360,phasemovie,fs-make,borders}.tcl: $session->$isession
# 14/05/04 -- {eccen,polar,fs,real,2cond}-{flat,views}.tcl: $session->$isession
# 16/05/09 -- real-{view,flat}.tcl: multi: csurftclenv sets tclvars,not envvars
# 16/05/09 -- real-{view,flat}.tcl: multi: csurftclenv sets tclvars,not envvars
# 16/06/07 -- swapstat, setfile stat $val: so tksurfer.tcl knows name loaded
# 18/06/07 -- TODO: logcmd in all other scripts
# 25/05/16 -- $smoothoverlaymaskflag was not passed! (always smoothed stat)
# 25/05/16 -- pass/use $smoothstepsstat by env, to sep. from $smoothsteps (data)

#TODO: remove -mean- substitution logic from here to csurf:fixswfileprefs
#TODO: check floatstem passed w/infix (_f,_g,_d) before add _f,_r,_i (cf:csurf)
#TODO: change $dir to $scandir (old OK w/tksurfer.tcl trace)

### wrap entire script so script errors/crashes can go to log
catch {

### session dir autoset to $cwd/.. when cwd=scripts (standalone: set here)
#set isession /usr0/fspace/110329MS/image

### tcl-only defs (set for standalone tclscript, order: cmdline,here,readenv)
#set dir eccen1          ;# scandir, usu. subdir of "image/" (old: 004/image7)
#set rgbname eccen       ;# name of rgbfiles
#set floatstem sig       ;# wfile stem
#set realname _r         ;# real infix in wfile
#set complexname _i      ;# imaginary infix in wfile
#set cplxstatname none   ;# one of the following 3
### vars definitions from csurf, not used here
#set cplxstatname1 _f    ;# infix cross-subj F-ratio from complex raw amp
#set cplxstatname2 _g    ;# infix cross-subj F-ratio from complex sig
#set cplxstatname3 _a    ;# infix cross-subj t-test of complex sig vs. num
#set cplxstatname4 _e    ;# infix cross-subj Rayleigh test cpx sig vs. num
#set cplxstatname5 _b    ;# infix cross-subj t-test of complex pow vs. num
#set cplxstatname6 _h    ;# infix cross-subj cluster-filtered F-ratio

### C-parm defs (set for standalone tclscript, order: cmdline,here,readenv)
#set overlayflag 1       ;# overlay data on gray brain
#set surfcolor 1         ;# draw the curvature under data
#set avgflag 1           ;# make half convex/concave
#set complexvalflag 1    ;# two-component data
#set colscale 0          ;# 0=wheel,1=heat,2=BR,3=BGR,4=twocondGR,5=gray
#set angle_offset 0.75   ;# phase offset
#set angle_cycles 1.0    ;# adjust range
#set fthresh 0.3         ;# val/curv sigmoid zero (neg=>0)
#set fslope 1.5          ;# contast (was fsquash 2.5)
#set fmid   1.1          ;# set linear region
#set smoothsteps 20      ;# 10 steps = ~4 mm FWHM on surface
#set offset 0.30         ;# default lighting offset 
#set cvfact 1.30         ;# background light/dark curv gray contrast
#set light2 0.8          ;# bakcompat: more top light (old tksurfer def=0.6)

### read non-cap setenv vars (or ext w/correct rgbname) to override defaults
source $env(CSURF_DIR)/lib/tcl/readenv.tcl

### default missing tcl-only for standalone, except req'd scandir/floatstem
if ![info exists realname]      { set realname _r }
if ![info exists complexname]   { set complexname _i }
if ![info exists cplxstatname]  { set cplxstatname none }
foreach var "dir floatstem" {
  if ![info exists $var] {
    puts "\ntksurfer: [file tail $script]: ### variable \"$var\" undefined"
    puts \
    "tksurfer: [file tail $script]: ### set dir (scandir), floatstem (of wfile)"
    puts "\n  cd /usr0/sessions/120101MS/image/scripts"
    puts "  setenv dir 3-eccen                # scandir in \$isession=dir/image"
    puts "  setenv floatstem eccen-vreg+orig  # <floatstem>_r-rh.w"
    puts "  setenv noexit                     # don't exit after render"
    puts "  setenv nosave                     # don't immediately save bitmap"
    puts "  tksurfer marser rh inflated -tcl [file tail $script]\n"
    exit
  }
}
if ![info exists rgbname] { set rgbname $floatstem }
set complexvalflag 1   ;# force correct
set overlayflag 1      ;# force correct

### read curvature (or sulc)
puts "tksurfer: [file tail $script]: read curvature"
read_binary_curv

### setenv eccendir overrides setenv dir (old)
#if [info exists eccendir] { set dir $eccendir } ;# (breaks 2nd after fs sets)

### opt off/repl/mask/mult amp by none/cxFamp(_f)/cxFsig(_g)/tsig(_a)(12combos)
set readstat 0
if { [info exists statmultampflag] && $statmultampflag } { set readstat 1 }
if { [info exists statmaskampflag] && $statmaskampflag } { set readstat 2 }
if { [info exists statreplampflag] && $statreplampflag } { set readstat 3 }
if {$readstat} {
  puts "tksurfer: [file tail $script]: read and smooth stat mask"
  if {$readstat == 1} {puts "tksurfer: [file tail $script]: stat multiply amp"}
  if {$readstat == 2} {puts "tksurfer: [file tail $script]: stat masks amp"}
  if {$readstat == 3} {puts "tksurfer: [file tail $script]: stat replaces amp"}
  set i [string first -mean- $floatstem] ;# csurf xsubjavg: -mean- => -{t}stat-
  if {$i != -1} {
    set newinfix stat ;#N.B.: match csurf literal
    if {$cplxstatname == "_a"} {set newinfix tstat} ;#N.B.: match csurf literal
    if {$cplxstatname == "_b"} {set newinfix tstat} ;#N.B.: match csurf literal
    puts "tksurfer: [file tail $script]: $floatstem: -mean- infix => $newinfix"
    set statfloatstem [string range \
      $floatstem 0 $i]${newinfix}[string range $floatstem [expr $i + 5] end]
    setfile val */$dir/${statfloatstem}${cplxstatname}-$hemi.w
  } else {
    puts "tksurfer: [file tail $script]: no \"-mean-\" infix in $floatstem"
    setfile val */$dir/${floatstem}${cplxstatname}-$hemi.w
  }
  # if $maskfloatstem exists (passed to tcl via env) use it (overrides above!)
  if { [info exists maskfloatstem] &&
       $maskfloatstem != "" && $maskfloatstem != "-unset-"} {
    puts "tksurfer: [file tail $script]: \$maskfloatstem exists, override above"
    setfile val */$dir/${maskfloatstem}-$hemi.w  ;# stem includes cplxstatname
  }
  puts "tksurfer: [file tail $script]: read stats, swap_stat_val"
  read_binary_values
  smooth_val $smoothstepsstat
  swap_stat_val
  #TODO: eventually use: set stat blah, read_binary_stats
  setfile stat $val  ;# so tksurfer.tcl knows/saves name prev loaded stat file
}

### read and smooth real/imag component MRI Fourier transform of data
if { [info exists cpxangrealampflag] && $cpxangrealampflag} {
  ## read real/imag, avg cmplx ang, avg neigh amp ignoring phase dispersion
  puts "tksurfer: [file tail $script]: read imag Fourier comp, mv to val2"
  setfile val */$dir/${floatstem}${complexname}-$hemi.w     ;# eccentricity
  read_binary_values
  copy_val_val2
  puts "tksurfer: [file tail $script]: read real Fourier comp"
  setfile val */$dir/${floatstem}${realname}-$hemi.w     ;# eccentricity
  read_binary_values
  puts "tksurfer: [file tail $script]: smooth ignore dispers.: avg ang/realamp"
  smooth_complexang_realamp $smoothsteps
} else {  ;# standard complex vector avg
  ## read and smooth imag component MRI Fourier transform of data
  puts "tksurfer: [file tail $script]: read and smooth complex Fourier comp"
  setfile val */$dir/${floatstem}${complexname}-$hemi.w     ;# eccentricity
  read_binary_values
  smooth_val $smoothsteps
  copy_val_val2           ;# shift imag comp out of way
  ## read and smooth real component MRI Fourier transform of data
  puts "tksurfer: [file tail $script]: read and smooth real Fourier comp"
  setfile val */$dir/${floatstem}${realname}-$hemi.w     ;# eccentricity
  read_binary_values
  smooth_val $smoothsteps
}

### expand rawdata (csurf imagepatt, regdat) w/scandir (now in new tksurfer)
#if [info exists rawdata] {  ;# left here for HOWTO but rm'd from all others
#  setfile regdat */$dir/[file tail $regdat]
#  setfile rawdata */$dir/[file tail $rawdata]
#}

### scale and position brain
puts "tksurfer: [file tail $script]: scale, position brain"
open_window
make_lateral_view       ;# rotate either hemisphere
do_lighting_model

### save requested rgbs (transforms done here)
puts "tksurfer: [file tail $script]: save rgb's"
source $env(CSURF_DIR)/lib/tcl/saveviews.tcl

### save phasemovie
if [info exists phasemovie] {
  puts "tksurfer: [file tail $script]: save phasemovie"
  source $env(CSURF_DIR)/lib/tcl/phasemovie.tcl
}

### errors (if any) to log
} ret  ;# end catch
if {$ret != ""} { puts "tksurfer: [file tail $script]: ### $ret" }

if ![info exists noexit] { exit }
