#! /usr/bin/tclsh
##############################################################################
# tksurfer script: borders.tcl  [calc,write borders using sphere]
##############################################################################
# used by csurf "Setup Calculate Fieldsign, Borders" panel, or standalone
# TODO: add controls popup to also make runnable from tksurfer tcl entry

### HOWTO run from cmdline:
#  cd $FUNCTIONALS_DIR/140430MSa/image/rawavg-all/scripts
#  [uncomment, adjust parameters below]
#  tksurfer marser-qT1 rh sphere -tcl borders.tcl

### 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 floatstem sig       ;# float file stem (eccen/polarstem overrides)
#set eccendir eccen      ;# eccen dir
#set polardir polar      ;# polar dir
#set realname _r         ;# real infix in wfile
#set complexname _i      ;# imaginary infix in wfile
#set realbordcntname _k  ;# output border count infix in wfile
#set smoothsteps 30      ;# csurf $page,smoothstepsbd
#set retinprogressflag 0 ;# show
#set label /tmp/$hemi-searchregion.label

### defined in tcl, adjustable
#set surfext sphere      ;# appended to $hemi.
#set retinvtxfrac 1.0    ;# fraction of vertices to seed
#set maxretinsearch 5.0  ;# quit at dist from seed in mm
#set minretindist 0.02   ;# dist in radians on init circ

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

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

### die if not sphere and can't change to it, no seeds label
if {$surfext != "sphere"} {
  set spheresurf $env(SUBJECTS_DIR)/$subject/surf/$hemi.sphere
  if ![file exists $spheresurf] {
    puts "tksurfer: [file tail $script]: ### compute borders req's $spheresurf"
    puts "tksurfer: [file tail $script]: ###### compute borders failed #######"
    exit
  }
}
unset spheresurf
if ![file exists $label] { ;# N.B.: passed via env
  puts "tksurfer: [file tail $script]: ### compute borders requires $label"
  puts "tksurfer: [file tail $script]: ###### compute borders failed #######"
  exit
}
if ![info exists eccenstem] { set eccenstem $floatstem }
if ![info exists polarstem] { set polarstem $floatstem }

#### ECCENTRICITY ####
### read and smooth imag component MRI Fourier transform of *eccen* data
puts "tksurfer: [file tail $script]: read, smooth complex Fourier comp: eccen"
setfile val */$eccendir/${eccenstem}${complexname}-$hemi.w
read_binary_values
smooth_val $smoothsteps
#shift_values              ;# old name, still works
copy_val_val2              ;# shift imag component out of way

### read and smooth real component MRI Fourier transform of *eccen* data
puts "tksurfer: [file tail $script]: read, smooth real Fourier comp: eccen"
setfile val */$eccendir/${eccenstem}${realname}-$hemi.w
read_binary_values
smooth_val $smoothsteps
#swap_values               ;# old name, still works
swap_valval2_valbakval2bak ;# swap both components eccentricity out of way

#### POLAR ANGLE ####
### read and smooth imag component MRI Fourier transform of *theta* data
puts "tksurfer: [file tail $script]: read, smooth complex Fourier comp: polar"
setfile val */$polardir/${polarstem}${complexname}-$hemi.w
read_binary_values
smooth_val $smoothsteps
#shift_values              ;# old name, still works
copy_val_val2              ;# shift imag component out of way

### read and smooth real component MRI Fourier transform of *theta* data
puts "tksurfer: [file tail $script]: read, smooth real Fourier comp: polar"
setfile val */$polardir/${polarstem}${realname}-$hemi.w
read_binary_values
smooth_val $smoothsteps
#swap_values                ;# old name, still works
swap_valval2_valbakval2bak  ;# swap again (r,th)

### optional open window to view (need tick in csurf)
if {$retinprogressflag} {
  puts "tksurfer: [file tail $script]: scale, position brain"
  open_window
  make_lateral_view       ;# rotate either hemisphere
  if {$hemi == "lh"} { rotate_brain_y  100; rotate_brain_x 25 }
  if {$hemi == "rh"} { rotate_brain_y -100; rotate_brain_x 25 }
  do_lighting_model
  set fmid 2.0
  set overlayflag 1
  set complexvalflag 1
  redraw
  after 500
}

#### SEEDS LABEL ####
### read label for retin seeds
puts "tksurfer: [file tail $script]: read label"
read_label_to_annot_using_col 120 120 255
if {$retinprogressflag} {  ;# briefly show label used
  set labelflag 1
  redraw
  after 1000
  set labelflag 0
  redraw
}

#### DO REGION GROWING ####
### run find_retin_borders
puts "tksurfer: [file tail $script]: retinvtxfrac = $retinvtxfrac"
puts "tksurfer: [file tail $script]: maxretinsearch = $maxretinsearch"
puts "tksurfer: [file tail $script]: minretindist = $minretindist"
puts "tksurfer: [file tail $script]: start find_retin_borders"
set ret [time find_retin_borders]
set runtime [format "%1.1f" [expr [lindex $ret 0]/1000000.0]]
puts "tksurfer: [file tail $script]: runtime: $runtime sec"

#### WRITE WFILE (_k, to both eccendir and polardir) ####
# count to wfile into ecccendir
setfile val */$eccendir/${borderstem}${realbordcntname}-$hemi.w
write_binary_values
# scaled by seeds/tested (~1) wfile into polardir
swap_val_val2
setfile val */$polardir/${borderstem}${realbordcntname}-$hemi.w
write_binary_values
 
### errors (if any) to log
} ret
if {$ret != ""} { puts "tksurfer: [file tail $script]: ### $ret" }

if ![info exists noexit] { exit }

