##############################################################################
# searchlightdiff.tcl (tksurfer): searchlight clusterID avg/count/var diff
##############################################################################
### outputs -- indiv searchlight outputs and difference ($size is: num,sqmm,mm)
# ~/label/$hemi-$labelinfix1-{avg,count,var}-$size.label
# ~/label/$hemi-$labelinfix2-{avg,count,var}-$size.label
# ~/label/$hemi-$labelinfix2-minus-$labelinfix1-{avg,count,var}-$size-diff.label

### def tcl-only on 1st entry (don't biff set-by-popup on interactive reenter)
# don't change these here: for custom script, uncomment/adjust copies below 
if ![info exists userok]        { set userok 0 }
if ![info exists labelinfix1]   { set labelinfix1 infix_to_be_subtracted }
if ![info exists labelinfix2]   { set labelinfix2 infix_to_subtract_from }
if ![info exists searchlightop] { set searchlightop 0 }
if ![info exists fillneartype]  { set fillneartype 0 }
if ![info exists num,sqmm,mm]   { set num,sqmm,mm 250 }
if ![info exists lutfile]       { set lutfile 139colours.lut }
#TODO: save var state on entry

### HOWTO: run interactively from tksurfer
#  select searchlightdiff.tcl from "tcl:" dropdown (under DEFAULT LIB SCRIPTS)
#  GO
#  adjust parms in pop-up
#  RUN SCRIPT
#
### HOWTO: run interactively from tksurfer with saved non-default parms
#  copy this lib script into subject/session scripts dir
#  uncomment/edit parameters below (N.B.: uncommented vars override popup vals!)
#  open inflated surface using csurf SURFACE button (or tksurfer cmdline)
#  find this script in "tcl:" dropdown (under LOCAL SUBJECT/FUNCT SCRIPTS)
#  GO
#  verify non-default parms in pop-up (N.B.: changes made in pop-up ignored!)
#  RUN SCRIPT
#
### HOWTO: run from shell/cmdline:
#  copy this default lib script into a subject/session scripts dir
#  uncomment/adjust parameters below
#  example (subject=marser-qT1):
#    cd $SUBJECTS_DIR/marser-qT1/scripts
#    tksurfer marser-qT1 rh inflated -tcl searchlightdiff.tcl
#

##############################################################################
# for cmdline or subj-specific tksurfer tcl script: uncomment/adj these parms
##############################################################################
### N.B.: any vars uncommented here override interactively entered popup values

### tcl-only parameters (not linked to tksurfer C-variables)
### infiles: $hemi-$labelinfix1.label,$hemi-$infix2.label in subject's label dir
### example1:
#set labelinfix1 6sub20avs_nEst10_multiclass_mmp1_dti6noR ;#infix to subtr
#set labelinfix2 6sub20avs_nEst20_multiclass_mmp1_sh27    ;#infix to subtr from
### example2:
#set labelinfix1 10Subs_multiclass_nEst20_DT6_mmp1        ;#infix to subtr
#set labelinfix2 10Subs_multiclass_nEst20_SH27_mmp1       ;#infix to subtr from
### other parms:
#set searchlightop  1           ;# 0=avg, 1=count, 2=variance
#set fillneartype   0           ;# fill-to criterion: 0=num, 1=area, 2=radius
#set num,sqmm,mm  250           ;# num vtxs (cnt), area (mm^2), or radius (mm)
#set lutfile   mmp1_shuff3.lut  ;# color lookup table in subjects script dir

### tcl-variables linked to C-variables in tksurfer.c
# for complete list, see: tksurfer -help
##############################################################################
#TODO: check/warn here if above uncommented have overriden popup-edited val

### two interactive ways to override defaults (popup or current env)
if ![info exists searchlightctrls] { set searchlightctrls "" }
if [winfo viewable .] {    ;# make popup -- N.B.: re-enters this script on OK
  set noexit 1
  if {!$userok} {
    if [winfo exists $searchlightctrls] { raise $searchlightctrls; return }
    set searchlightctrls [controls "SEARCHLIGHT DIFFERENCE\
                              \n(output = labelinfix2 - labelinfix1)\
                              \n\nFill nearest (fillneartype):\
                                \n 0:  num vertices\
                                \n 1:  area (mm^2)\
                                \n2:  radius (mm)\
                                \n        3:  neighbor ord (1-6)\
                              \n\nSearchlight Operation:\
                                \n0:  Average\
                                \n           1:  Count (int data)\
                                \n2:  Variance\
                                \n       3:  \[not relevant]\
                                \n4:  Sum        " {
      labelinfix1 labelinfix2
      whitespace
      searchlightop fillneartype num,sqmm,mm
      whitespace
      lutfile
      whitespace
    } "RUN SCRIPT" "set userok 1; source [info script]" 14]
    bind $searchlightctrls <ButtonRelease-3> { helpwin script_searchlightdiff }
    return
  }
} else {                   ;# batch scripts; re-read env to override defaults
  source $env(CSURF_DIR)/lib/tcl/readenv.tcl
}

### check input labels there
foreach infix "$labelinfix1 $labelinfix2" {
  set labelfile $env(SUBJECTS_DIR)/$subject/label/$hemi-$infix.label
  if ![file exists $labelfile] {
    puts "tksurfer: [file tail $script]: ### $hemi-$infix.label not found"
    if [winfo viewable .] {  ;# tcl tools window
      if {"$infix" == "$labelinfix1"} {
        confirmalert "First input label file:\
                  \n\n    $hemi-$infix.label\n\nnot found"
        return
      }
      if {"$infix" == "$labelinfix2"} {
        confirmalert "Second input label file:\
                  \n\n    $hemi-$infix.label\n\nnot found"
        return
      }
    } else { exit }  ;# cmdline script
  }
}

### check searchlightop, convert to readable
if {$searchlightop == 0} {
  set typeinfix avg 
} elseif {$searchlightop == 1} {
  set typeinfix count
} elseif {$searchlightop == 2} {
  set typeinfix var
} elseif {$searchlightop == 4} {
  set typeinfix sum 
} else {
  puts \
"tksurfer: [file tail $script]: ### bad searchlightop: $searchlightop(OK:0-2,4)"
  if [winfo viewable .] {  ;# tcl tools window
    confirmalert "Bad searchlightop:\n\n    $searchlightop\
              \n\nOK:\n    0 -> avg\n    1 -> count\n    2 -> var\n    4 -> sum"
    return
  } else { exit }  ;# cmdline script
}

### check fillneartype
if {$fillneartype < 0 || $fillneartype > 3} {
  puts \
   "tksurfer: [file tail $script]: ### bad fillneartype: $fillneartype (OK:0-3)"
  if [winfo viewable .] {  ;# tcl tools window
    confirmalert "Bad fillneartype:\n\n    $fillneartype\
  \n\nOK:\n\n    0 -> num\n    1 -> area\n    2 -> rad\n    3 -> neighbor order"
    return
  } else { exit }  ;# cmdline script
}
if {$fillneartype == 3} {
  if {${num,sqmm,mm} < 1 || ${num,sqmm,mm} > 6} {
    puts "tksurfer: [file tail $script]: ### bad num,sqmm,mm (neighbor order): ${num,sqmm,mm} (OK:1-6)"
    if [winfo viewable .] {  ;# tcl tools window
      confirmalert \
        "Bad num,sqmm,mm (neighbor order):  ${num,sqmm,mm}\n\nOK: 1-6"
      return
    } else { exit }  ;# cmdline script
  }
}

### check output labels (always overwrite, no popup err)
set lfiledir $env(SUBJECTS_DIR)/$subject/label
foreach lfile "
 $hemi-$labelinfix1-$typeinfix-${num,sqmm,mm}.label
 $hemi-$labelinfix2-$typeinfix-${num,sqmm,mm}.label
 $hemi-$labelinfix2-minus-$labelinfix1-$typeinfix-${num,sqmm,mm}-diff.label" {
  if [file exists $lfiledir/$lfile] {
    puts "tksurfer: [file tail $script]: ### overwriting output label:"
    puts "tksurfer: [file tail $script]:  $lfiledir/$lfile"
  }
}

### go: read/show data each stem, run searchlights, save outputs
confirmalert "interface unresponsive during (multithreaded) calc\n\nOK to start"
if {!$openglwindowflag} {
  open_window
  logcmd "open_window"
  make_lateral_view
  logcmd "make_lateral_view"
}
set complexvalflag 0
logcmd "set complexvalflag 0"
set overlayflag 1
logcmd "set overlayflag 1"
foreach infix "$labelinfix1 $labelinfix2" {
  if {"$infix" == "$labelinfix1"} {
    puts "tksurfer: [file tail $script]: ==== run searchights on infix1 ===="
  } 
  if {"$infix" == "$labelinfix2"} {
    puts "tksurfer: [file tail $script]: ==== run searchights on infix2 ===="
  }
  clear_values
  logcmd "clear_values"
  clear_stats
  logcmd "clear_stats"
  # read label into val field
  setfile label ~/label/$hemi-$infix.label
  logcmd "setfile label ~/label/$hemi-$infix.label"
  read_label_to_val 0         ;# 0 means don't re-cut label
  logcmd "read_label_to_val 0"
  # display input
  if {$searchlightop == 1} {  ;# count: init view special case
    set colscale 12
    logcmd "set colscale 12"
    if [file exists $env(SUBJECTS_DIR)/$subject/scripts/$lutfile] {
      setfile val2rgblut ~/scripts/$lutfile
      logcmd "setfile val2rgblut ~/scripts/$lutfile"
      read_val2rgblut
      logcmd "read_val2rgblut"
    }
  }
  redraw
  logcmd "redraw"
  # run searchlight (interface unresponsive)
  if {$fillneartype == 0 || $fillneartype == 1 || $fillneartype == 2} {
    searchlightop_val2stat $fillneartype ${num,sqmm,mm} $searchlightop
    logcmd "searchlightop_val2stat $fillneartype ${num,sqmm,mm} $searchlightop"
  }
  if {$fillneartype == 3} {
    neighop_val2stat ${num,sqmm,mm} $searchlightop
    logcmd "neighop_val2stat ${num,sqmm,mm} $searchlightop"
  }
  # get/save result
  swap_stat_val
  logcmd "swap_stat_val"
  setfile label ~/label/$hemi-$infix-$typeinfix-${num,sqmm,mm}.label
  logcmd "setfile label ~/label/$hemi-$infix-$typeinfix-${num,sqmm,mm}.label"
  write_val_visible_vertices
  logcmd "write_val_visible_vertices"
  # display output (5 sec)
  set colscale 6
  logcmd "set colscale 6"
  if {$searchlightop == 0} {  ;# avg
    set fmid 0.0
    logcmd "set fmid 0.0"
    set fslope 0.25
    logcmd "set fslope 0.25"
  }
  if {$searchlightop == 1} {  ;# count (assume int data)
    set fmid 0.0
    logcmd "set fmid 0.0"
    set fslope 0.25
    logcmd "set fslope 0.25"
  }
  if {$searchlightop == 2} {  ;# variance
    set fmid 600
    logcmd "set fmid 600"
    set fslope 0.002
    logcmd "set fslope 0.002"
  }
  redraw
  logcmd "redraw"
  raise_window
  logcmd "raise_window"
  update idletasks
  after 5000
}

### read labels into tksurfer stack, get difference, write diff label, display
# N.B.: orange means infix2 is higher/worse than infix1 (more counts, more var)
clear_values
logcmd "clear_values"
clear_stats
logcmd "clear_stats"
setfile label ~/label/$hemi-$labelinfix1-$typeinfix-${num,sqmm,mm}.label
logcmd \
  "setfile label ~/label/$hemi-$labelinfix1-$typeinfix-${num,sqmm,mm}.label"
read_label_to_val 0           ;# read infix1 into top of stack (.val)
logcmd "read_label_to_val 0"
swap_valval2_valbakval2bak    ;# move infix1 to bottom of stack (.valbak)
logcmd "swap_valval2_valbakval2bak"
setfile label ~/label/$hemi-$labelinfix2-$typeinfix-${num,sqmm,mm}.label
logcmd \
  "setfile label ~/label/$hemi-$labelinfix2-$typeinfix-${num,sqmm,mm}.label"
read_label_to_val 0           ;# read infix2 into top of stack (.val)
logcmd "read_label_to_val 0"
subtr_valbak_from_val         ;# stat = infix2 - infix1
logcmd "subtr_valbak_from_val"
swap_stat_val                 ;# see result
logcmd "swap_stat_val"
setfile label ~/label/$hemi-$labelinfix2-minus-$labelinfix1-$typeinfix-${num,sqmm,mm}-diff.label
logcmd "setfile label ~/label/$hemi-$labelinfix2-minus-$labelinfix1-$typeinfix-${num,sqmm,mm}-diff.label"
write_val_visible_vertices     ;# save
logcmd "write_val_visible_vertices"
# display
set colscale 6
logcmd "set colscale 6"
if {$searchlightop == 0} {
  set fmid 0.0
  logcmd "set fmid 0.0"
  set fslope 0.5
  logcmd "set fslope 0.5"
}
if {$searchlightop == 1} {
  set fmid 0.0
  logcmd "set fmid 0.0"
  set fslope 0.5
  logcmd "set fslope 0.5"
}
if {$searchlightop == 2} {
  set fmid 50
  logcmd "set fmid 50"
  set fslope 0.01
  logcmd "set fslope 0.01"
}
redraw
logcmd "redraw"

### explain outputs
puts "tksurfer: [file tail $script]: output files directory:"
puts "tksurfer: [file tail $script]:   [file dirname $label]"
puts "tksurfer: [file tail $script]: indiv $typeinfix labels:"
puts "tksurfer: [file tail $script]:   $hemi-$labelinfix1-$typeinfix-${num,sqmm,mm}.label"
puts "tksurfer: [file tail $script]:   $hemi-$labelinfix2-$typeinfix-${num,sqmm,mm}.label"
puts "tksurfer: [file tail $script]: diff output label (orange: infix2>infix1):"
puts "tksurfer: [file tail $script]:   [file tail $label]"
if [winfo viewable .] {
  confirmalert "Individual output labels (operation=$typeinfix):\
            \n\n    $hemi-$labelinfix1-$typeinfix-${num,sqmm,mm}.label\
              \n    $hemi-$labelinfix2-$typeinfix-${num,sqmm,mm}.label\
\n\n    (operation=$typeinfix, neartype=$fillneartype, size=${num,sqmm,mm})\
            \n\nDifference output label (infix2 minus infix1):\
            \n\n    [file tail $label]\
            \n\n    (orange:  infix2 > infix1)\
              \n    (blue:       infix1 > infix2)\
            \n\nOutput directory:\
            \n\n    [file dirname $label]"
}

### cleanup
if ![info exists noexit] { exit }  ;# cmdline script
set userok 0
#if [info exists searchlightctrls] {destroy $searchlightctrls}
unset lfiledir lfile typeinfix   ;# cleanup tmp script vars
return   ;# else catch in tksurfer.tcl returns err (=last return of last cmd)

