#! /bin/sh
# next line not seen by tcl upon reentry by exec \
DYLD_LIBRARY_PATH=$CSURF_LIBRARY_PATH exec wish8.5 $0 ${1+"$@"}

##! /bin/sh
## get any wish on path \
#exec wish $0 ${1+"$@"}    # goto tcl
#exec $LOCAL_DIR/bin/wish4.0 $0 ${1+"$@"}    # goto tcl
#exec $LOCAL_DIR/bin/tixwish4.1.7.4 $0 ${1+"$@"}    # goto tcl

############################################################################
# Copyright (c) 1997 Martin Sereno and Anders Dale
############################################################################
set program bsurf
if ![info exists env(CSURF_DIR)] {
  puts "$program: ### Environment var CSURF_DIR undefined (use setenv)"
  exit
}
if ![info exists env(SUBJECTS_DIR)] {
  puts "$program: ### Environment var SUBJECTS_DIR undefined (use setenv)"
  exit
}
#if ![info exists env(LOCAL_DIR)] {
#  puts "$program: ### Environment var LOCAL_DIR undefined (use setenv)"
#  exit
#}
# rm LOCAL_DIR, set model, and next line only change from orig 1997 version
::tk::classic::restore

###### safe testing ######
set env(SUBJECTS_DIR) /tmp
##########################

set loglines 3
set logflag 0

### internal
set origext orig
set foldedext smoothwm
set inflatedext 1000a       ;# inflated
set fullpatch patch-nomid   ;# full
set partialpatch patch      ;# occip
set 3dbeginext 3d         
set flatbeginext 0
set flatendext 1000         ;# flat
set stmptcl /tmp/TmpTclSurf.[pid]
set mtmptcl /tmp/TmpTclMed.[pid]
set ctmptcl /tmp/TmpTclCmd.[pid]
set editeddat 0
set cmdpid -1
set surfpid -1
set medpid -1
set otherhemi 0

### defaults
set name nicoles   ;# nobody
set hemi rh        ;# rh lh both
set hemitype 0     ;# 0=rh 1=lh 2=both
set ext $foldedext
set patch3dext $fullpatch.$3dbeginext
set patchext $fullpatch.$flatendext
set viewtype 0     ;# 0=folded 1=inflated 2=viewcuts 3=partflat 4=fullflat
set editable wm
set mritype 3      ;# 0=orig 1=T1 2=brain 3=wm 4=filled
#set model $env(LOCAL_DIR)/lib/model/average_305.mnc
set model average_305.mnc
set datfile $program.dat
set force 0

### datfile vars
set datfilelist { \
  name scantype filepatterns firstnumbers registeravg numslices prescale \
  flipCORview thickness fov swapbytes invert \
  mniproto autonormalize \
  normdir lim3 ffrac3 lim2 ffrac2 lim1 ffrac1 lim0 ffrac0 \
  fzero fmax dfrac istilt \
  white_hilim white_lolim gray_hilim \
  manualfilldat nseed seed1 seed2 \
  callosal_imnr callosal_i callosal_j midbrain_imnr midbrain_i midbrain_j \
  max_fill_iter min_filled_per_cyc max_same_neigh \
  rhlhscale antpostscale supinfscale \
  inflate_cthk inflate_mmid inflate_whitemid inflate_graymid \
  plump_cthk plump_mmid plump_whitemid plump_graymid shrinkcycles \
  rh_patch_zrot rh_patch_scale rh_patch_xtrans rh_patch_ytrans \
  lh_patch_zrot lh_patch_scale lh_patch_xtrans lh_patch_ytrans \
  rh_full_zrot rh_full_scale rh_full_xtrans rh_full_ytrans \
  lh_full_zrot lh_full_scale lh_full_xtrans lh_full_ytrans \
}
set datfilelistparen { filepatterns firstnumbers }
set datfilelistquote { seed1 seed2 callosal_imnr callosal_i callosal_j  \
                                   midbrain_imnr midbrain_i midbrain_j }
### datfile defaults
set scantype      Siemens
set filepatterns  {1/392-4-%03d.ima 2/392-5-%03d.ima}
set firstnumbers  {1 161}
set registeravg   0
set numslices     160
set prescale      1
set flipCORview   NOFLIP
set thickness     0  ;# 1.0
set fov           0  ;# 240
set swapbytes     0  ;# 1
set invert        0  ;# 1
set mniproto   icbm
set autonormalize 1
set normdir  1
set lim3     170
set ffrac3   1.0
set lim2     145
set ffrac2   1.0
set lim1     95
set ffrac1   1.0
set lim0     75
set ffrac0   1.0
set fzero  40
set fmax   130
set dfrac  0.7
set istilt 1.0
set white_hilim  140
set white_lolim  80
set gray_hilim   100
set manualfilldat  0
set nseed   2
set seed1  {112 157 128 80}
set seed2  {112 157 132 255}
set callosal_imnr {82 160}
set callosal_i    {0 160}
set callosal_j    {128 130}
set midbrain_imnr {95 121}
set midbrain_i    {110 112}
set midbrain_j    {113 147}
set max_fill_iter      10
set min_filled_per_cyc 100
set max_same_neigh     10
set rhlhscale    1.0
set antpostscale 1.0
set supinfscale  1.0
set inflate_cthk     1.0
set inflate_mmid     45.0
set inflate_whitemid 45.0
set inflate_graymid  30.0
set plump_cthk     4.0
set plump_mmid     80.0
set plump_whitemid 80.0
set plump_graymid  80.0
set shrinkcycles 100
set rh_patch_zrot    90
set rh_patch_scale   1.4
set rh_patch_xtrans  0.0
set rh_patch_ytrans  0.0
set lh_patch_zrot    90
set lh_patch_scale   1.4
set lh_patch_xtrans  0.0
set lh_patch_ytrans  0.0
set rh_full_zrot   90
set rh_full_scale  0.7
set rh_full_xtrans 0.0
set rh_full_ytrans 0.0
set lh_full_zrot   90
set lh_full_scale  0.7
set lh_full_xtrans 0.0
set lh_full_ytrans 0.0

### source standard widget wrapper code
source $env(CSURF_DIR)/lib/tcl/wrappers.tcl

### so send works
if [catch {exec xhost -}] {  ;# IRIX-specific xhost output
  puts "$program: ### Can't run xhost--auto surfer<=>medit sendpoint won't work"
} else {
  foreach word [exec xhost] {
    if [string match INET* $word] { exec xhost - [string trimleft $word INET:] }
  }
}

### run from current subject scripts dir, else pwd
if [file exists $env(SUBJECTS_DIR)/$name/scripts] {
  cd $env(SUBJECTS_DIR)/$name/scripts
}

### modern warning
after 1000 {
 confirmalert "bsurf: original 1997 interface\n\nN.B.: some opts don't work now"
}

#################################################################
proc surfercmd { } {
  global surflog surfbu
  global viewtype stmptcl
  global env name hemi ext
  global otherhemi
  checkbothhemi
  if {$viewtype == 0} { mk3dscript }
  if {$viewtype == 1} { mk3dscript }
  if {$viewtype == 2} { mkcutsscript }
  if {$viewtype == 3} { mkflatscript }
  if {$viewtype == 4} { mkflatscript }
  set surf $env(SUBJECTS_DIR)/$name/surf/$hemi.$ext
  if ![file exists $surf] {
    confirmalert "Surface: $name/surf/$hemi.$ext not found"
    return
  }
  set tclenv "tksurferinterface=mini"
  set command "env $tclenv tksurfer -$name $hemi $ext -tcl $stmptcl"
  runacmd "$command" $surfbu SURFER surfinput $surflog surfpid
}

proc meditcmd { } {
  global medlog medbu
  global env name mritype editable mtmptcl
  set firstim $env(SUBJECTS_DIR)/$name/mri/$editable/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/$editable/COR-* not found"
    return
  }
  set tclenv "tkmeditinterface=mini"
  set command "env $tclenv tkmedit $name $editable"
  runacmd "$command" $medbu MEDIT medinput $medlog medpid
}

proc fixeditable { varName index op } {
  global mritype editable
  if {$mritype == 0} { set editable orig }
  if {$mritype == 1} { set editable T1 }
  if {$mritype == 2} { set editable brain }
  if {$mritype == 3} { set editable wm }
  if {$mritype == 4} { set editable filled }
}


proc mk3dscript { } {
  global stmptcl
  set id [open $stmptcl w 0644]
  puts $id "open_window"
  puts $id "read_binary_curv"
  puts $id "make_lateral_view"
  puts $id "set cslope 2"
  puts $id "redraw"
  close $id
}

proc mkflatscript { } {
  global stmptcl env hemi patchext
  if ![file exists position.tcl] { mkpositiontcl }
  set id [open $stmptcl w 0644]
  set tclenv "patchname=$patchext"    ;# make setdefpatch reset from default
  puts $id "source $env(CSURF_DIR)/lib/tcl/setdefpatchview.tcl"
  puts $id "setfile patch ~/surf/$hemi.$patchext"
  puts $id "read_binary_curv; read_binary_patch"
  puts $id "open_window"
  puts $id "restore_zero_position; rotate_brain_x -90"
  # these are tcl vars set when position.tcl runs ($ in script)
  puts $id {rotate_brain_z $flatzrot}
  puts $id {translate_brain_x $flatxtrans}
  puts $id {translate_brain_y $flatytrans}
  puts $id {scale_brain $flatscale}
  puts $id "set cslope 2"
  puts $id "redraw"
  close $id
}

proc mkcutsscript { } {
  global stmptcl hemi patch3dext
  set id [open $stmptcl w 0644]
  puts $id "setfile patch ~/surf/$hemi.$patch3dext"
  puts $id "open_window"
  puts $id "read_binary_curv; read_binary_patch"
  puts $id "set flag2d 0; restore"   ;# back to 3d
  puts $id "rotate_brain_y 180"
  puts $id "set cslope 2"
  puts $id "redraw"
  close $id
}

proc mkpositiontcl { } {
  global env name
  global rh_patch_zrot rh_patch_scale rh_patch_xtrans rh_patch_ytrans
  global lh_patch_zrot lh_patch_scale lh_patch_xtrans lh_patch_ytrans
  global rh_full_zrot rh_full_scale rh_full_xtrans rh_full_ytrans
  global lh_full_zrot lh_full_scale lh_full_xtrans lh_full_ytrans
  if [file exists position.tcl] { exec mv position.tcl position.tcl~ }
  set id [open position.tcl w 0644]
  puts $id "#! /usr/local/bin/wish4.0"
  puts $id "###############################################"
  puts $id "# used by rendering scripts (funct scripts dir)"
  puts $id "###############################################"
  puts $id "set rh.patch.flatzrot $rh_patch_zrot"
  puts $id "set rh.patch.flatscale $rh_patch_scale"
  puts $id "set rh.patch.flatxtrans $rh_patch_xtrans"
  puts $id "set rh.patch.flatytrans $rh_patch_ytrans"
  puts $id "set lh.patch.flatzrot $lh_patch_zrot"
  puts $id "set lh.patch.flatscale $lh_patch_scale"
  puts $id "set lh.patch.flatxtrans $lh_patch_xtrans"
  puts $id "set lh.patch.flatytrans $lh_patch_ytrans"
  puts $id ""
  puts $id "set rh.patch-nomid.1000.flatzrot $rh_full_zrot"
  puts $id "set rh.patch-nomid.1000.flatscale $rh_full_scale"
  puts $id "set rh.patch-nomid.1000.flatxtrans $rh_full_xtrans"
  puts $id "set rh.patch-nomid.1000.flatytrans $rh_full_ytrans"
  puts $id "set lh.patch-nomid.1000.flatzrot $lh_full_zrot"
  puts $id "set lh.patch-nomid.1000.flatscale $lh_full_scale"
  puts $id "set lh.patch-nomid.1000.flatxtrans $lh_full_xtrans"
  puts $id "set lh.patch-nomid.1000.flatytrans $lh_full_ytrans"
  close $id
}

proc mknewsubj { home name } {
  global env program datfile datfilelist
  if ![file exists $home] {
    confirmalert "subjects dir not found: $home"
    return
  }
  if { [file exists $home/$name] } {
    if [okreplace $home/$name] { 
      set savsuff ~
      while { [file exists $home/$name$savsuff] } { set savsuff $savsuff~ }
      exec mv $home/$name $home/$name$savsuff
      confirmalert "subject dir: $home/$name moved aside to $home/$name$savsuff"
    } else {
      confirmalert "subject dir: $home/$name not altered"
      return
    }
  }
  exec mkdir $home/$name
  foreach dir {bem morph mpg mri rgb scripts surf tmp \
      mri/T1 mri/brain mri/filled mri/orig mri/tmp mri/transforms mri/wm} {
    if ![file exists $home/$name/$dir] { exec mkdir $home/$name/$dir }
  }
  confirmalert "made new subject dir: $home/$name"
  writecshparms $home/$name/scripts/$datfile $datfilelist
}

proc fixhome { varName index op } {
  global editeddat datfile env name
  if {$editeddat} {
    set resp [okclose $datfile]
    if {$resp == 0} {        }                              ;# cancel
    if {$resp == 1} {        }                              ;# don't save
    if {$resp == 2} { writecshparms $datfile $datfilelist } ;# save
    set editeddat 0
  }
  set newscripts $env(SUBJECTS_DIR)/$name/scripts
  if [file exists $newscripts] { cd $newscripts }
}

proc readcshparms { datfile } {
  global env name
  set scriptsdir $env(SUBJECTS_DIR)/$name/scripts
  if ![file exists $datfile] {
    confirmalert "datfile: $datfile not found in scripts dir: $scriptsdir"
    return
  }
  set id [open $datfile r]
  foreach line [split [read $id] \n] {
    set nocomm $line
    set comm [string first # $line]
    if {$comm >= 0} { set nocomm [string range $line 0 [expr $comm - 1]] }
    if { [string trim $nocomm] != "" } {
      set args [split $nocomm " "]
      set var [lindex $args 1]
      set val [join [lrange $args 3 end] " "]
      set val [string trim $val]
      set val "[string trim $val "\"()"]"   ;# also read tcl style?
      uplevel #0 "set $var {$val}"  ;# (*),"*" => tcl list
    }
  }
  close $id
}

proc writecshparms { datfile datfilelist } {
  global env name datfilelistparen datfilelistquote
  set scriptsdir $env(SUBJECTS_DIR)/$name/scripts
  if ![file exists $scriptsdir] { 
    confirmalert "subject scripts dir: $scriptsdir not found"
    return
  }
  if [file exists $datfile] {
    if ![okreplace $datfile "$datfile in $scriptsdir exists--overwrite?"] { 
      confirmalert "$datfile in $scriptsdir not altered"
      return
    } else {
      exec mv $datfile $datfile~
    }
  }
  set id [open $datfile w 0644]
  foreach parm $datfilelist {
    global $parm
    set val [set $parm]
    if { [lsearch -exact $datfilelistparen $parm] >= 0 } { set val ($val) }
    if { [lsearch -exact $datfilelistquote $parm] >= 0 } { set val \"$val\" }
    puts $id "set $parm = $val"
  }
  close $id
}

proc convertcmd { } {
  global cmdlog convertbu
  global env name force
  global scantype filepatterns firstnumbers registeravg numslices
  global prescale flipCORview thickness fov swapbytes invert
  if { [llength $filepatterns] != [llength $firstnumbers] } {
    confirmalert "Convert: list lengths filepatterns, firstnumbers don't match"
    return
  }
  set options "-p $prescale"
  if { $thickness != 0 } { set options "$options -t $thickness" }
  if { $fov != 0 }       { set options "$options -f $fov" }
  if { $swapbytes != 0 } { set options "$options -s" }
  if { $invert != 0 }    { set options "$options -i" }

  if { $registeravg } {
    confirmalert "  (1) convert each scan (auto)\n \
                    (2) register each -> 1st (SAVE REG,quit)\n \
                    (3) average to make orig (auto)"
    ### check for subdirs
    set regdirlist ""
    foreach patt $filepatterns {
      set regdir [file dirname $patt]
      if {$regdir == "."} {
        confirmalert \
          "Register avg: scans must be in separate ~/$name/mri/orig subdirs"
        return
      }
      set regdirlist "$regdirlist $regdir"
    }
    ### convert each scan to COR
    set i 0
    while {$i < [llength $filepatterns] } {  ;# no subdirs in subdirs
      set firstnumber [lindex $firstnumbers $i]
      set regdir [lindex $regdirlist $i]
      set regtail [file tail [lindex $filepatterns $i]]
      set fullregdir $env(SUBJECTS_DIR)/$name/mri/orig/$regdir
      if ![file exists $fullregdir] {
        confirmalert "Register avg: single scan dir: $fullregdir not found"
        return
      }
      cd $fullregdir
      if {!$force} {
        set firstim $env(SUBJECTS_DIR)/$name/mri/orig/$regdir/COR-001
        if [file exists $firstim] {
          if ![okreplace $firstim "Images: \
                $name/mri/orig/$regdir/COR-* exist--overwrite?"] {
            confirmalert "Images: $name/mri/orig/$regdir/COR-* not altered"
            cd $env(SUBJECTS_DIR)/$name/scripts
            return
          }
        }
      }
      set command \
         "orig2cor $options $scantype local $regtail $firstnumber $numslices"
      runacmd "$command" $convertbu CONVERT cmdinput $cmdlog cmdpid
      tkwait variable cmdpid
      set firstim $env(SUBJECTS_DIR)/$name/mri/orig/$regdir/COR-001
      if ![file exists $firstim] {
        confirmalert \
           "Images: $name/mri/orig/$regdir/COR-* not found  ...convert failed"
        cd $env(SUBJECTS_DIR)/$name/scripts
        return
      }
      if {$flipCORview != "NOFLIP"} { ;# flip separately so register looks right
        set id [open $ctmptcl w 0644]
        puts $id "flip_corview_xyz $flipCORview"
        puts $id "write_images"
        puts $id "exit"
        close $id
        set command "tkmedit local -tcl $ctmptcl"
        runacmd "$command" $convertbu CONVERT cmdinput $cmdlog cmdpid
        tkwait variable cmdpid
      }
      incr i 1
    }
    ### register each to first
    set regtarg [lindex $regdirlist 0]
    cd $env(SUBJECTS_DIR)/$name/mri/orig/$regtarg
    exec tkregister -readinfo   ;# make register.dat (identity) for target
    cd $env(SUBJECTS_DIR)/$name/scripts
    set i 1
    while {$i < [llength $filepatterns] } {
      set regdir [lindex $regdirlist $i]
      confirmalert "Register avg: orig/$regdir => orig/$regtarg \
                    \nSAVEREG and QUIT to start next"
      set command "tkregister $name orig/$regdir orig/$regtarg"
      runacmd "$command" $convertbu CONVERT cmdinput $cmdlog cmdpid
      tkwait variable cmdpid
      incr i 1
    }
    ### regcor average
    set prefregdirlist ""
    set i 0
    while {$i < [llength $filepatterns]} {
      set regdir [lindex $regdirlist $i]
      set prefregdirlist "$prefregdirlist orig/$regdir"  ;# regcor needs orig/
      incr i 1
    }
    set command "regcor $name $prefregdirlist orig"  ;# COR-.info from target
    runacmd "$command" $convertbu CONVERT cmdinput $cmdlog cmdpid
    tkwait variable cmdpid
    foreach regdir $regdirlist {
      eval exec rm -f [glob $env(SUBJECTS_DIR)/$name/mri/orig/$regdir/COR-???]
    }

  } else {  ;# simple average, flip averaged
    set intercalated ""
    set i 0
    while {$i < [llength $filepatterns]} {
      set firstnumber [lindex $firstnumbers $i]
      set filepattern [lindex $filepatterns $i]
      set intercalated "$intercalated $filepattern $firstnumber"
      incr i 1
    }
    set command "orig2cor $options $scantype $name $intercalated $numslices"
    runacmd "$command" $convertbu CONVERT cmdinput $cmdlog cmdpid
    tkwait variable cmdpid
    set firstim $env(SUBJECTS_DIR)/$name/mri/orig/COR-001
    if ![file exists $firstim] {
      confirmalert "Images: $name/mri/orig/COR-* not found  ...convert failed"
      cd $env(SUBJECTS_DIR)/$name/scripts
      return
    }
    if {$flipCORview != "NOFLIP"} {  ;# abusable flip
      set id [open $ctmptcl w 0644]
      puts $id "flip_corview_xyz $flipCORview"
      puts $id "write_images"
      puts $id "exit"
      close $id
      set command "tkmedit $name orig -tcl $ctmptcl"
      runacmd "$command" $convertbu CONVERT cmdinput $cmdlog cmdpid
      tkwait variable cmdpid
    }
  }
  foreach subdir {T1 brain wm filled} {
    exec cp $env(SUBJECTS_DIR)/$name/mri/orig/COR-.info \
            $env(SUBJECTS_DIR)/$name/mri/$subdir
  }
  cd $env(SUBJECTS_DIR)/$name/scripts
}

proc talairachcmd { } {
  global cmdlog talairachbu
  global env name force
  global mniproto model
  set xformfile $env(SUBJECTS_DIR)/$name/mri/transforms/talairach.xfm
  set origdir $env(SUBJECTS_DIR)/$name/mri/orig
  set mincfile $origdir/orig.mnc
  set logfile $origdir/orig.log
  set headerfile $origdir/COR-.info

  set firstim $env(SUBJECTS_DIR)/$name/mri/orig/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/orig/COR-* not found  ...convert first"
    return
  }
  set command "mri_convert $origdir $mincfile"  ;# cortominc orig orig/orig.mnc
  runacmd "$command" $talairachbu TALAIRACH cmdinput $cmdlog cmdpid
  tkwait variable cmdpid
  if ![file exists $mincfile] {
    confirmalert "Images: convert to minc failed   ...autotalairach aborted"
    return
  }

  if ![file exists $env(SUBJECTS_DIR)/$name/mri/transforms] {
    exec mkdir $env(SUBJECTS_DIR)/$name/mri/transforms
  }
  if [file exists $xformfile]  { exec mv $xformfile $xformfile~ }
  set command "mritotal -clobber -protocol $mniproto $mincfile $xformfile"
  runacmd "$command" $talairachbu TALAIRACH cmdinput $cmdlog cmdpid
  tkwait variable cmdpid
  if ![file exists $xformfile] {
    confirmalert "Images: autotalairach failed (talairach.xfm not written)"
    exec rm -f $mincfile
    if [file exists $xformfile~]  { exec mv $xformfile~ $xformfile }
    return
  }

  exec rm -f $mincfile
  exec mv $headerfile $headerfile~
  set id [open $headerfile~ r]
  set idout [open $headerfile w 0644]
  foreach line [split [read $id] \n] {
    set args [split $line " "]
    if { [lindex $args 0] == "ti" } {
      puts $idout "xform [file rootname $xformfile]"
    } else {
      puts $idout "$line"
    }
  }
  close $id
  close $idout
  foreach subdir {T1 brain wm filled} {
    exec cp $env(SUBJECTS_DIR)/$name/mri/orig/COR-.info \
            $env(SUBJECTS_DIR)/$name/mri/$subdir
  }
}

proc normalizecmd { } {
  global cmdlog normalizebu
  global env name force mtmptcl
  global autonormalize normdir
  global lim3 ffrac3 lim2 ffrac2 lim1 ffrac1 lim0 ffrac0
  set firstim $env(SUBJECTS_DIR)/$name/mri/orig/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/orig/COR-* not found  ...convert first"
    return
  }
  if {!$force} {
    set firstim $env(SUBJECTS_DIR)/$name/mri/T1/COR-001
    if [file exists $firstim] {
      if ![okreplace $firstim \
           "Images: $name/mri/T1/COR-* exist--overwrite?"] {
        confirmalert "Images: $name/mri/T1/COR-* not altered"
        return
      }
    }
  }
  if {$autonormalize} {
    set xformfile $env(SUBJECTS_DIR)/$name/mri/transforms/talairach.xfm
    if ![file exists $xformfile] {
      confirmalert "Datfile: $xformfile not found  ...auto talairach first"
      return
    } else {
      set command "mri_normalize $env(SUBJECTS_DIR)/$name/mri/orig \
                                 $env(SUBJECTS_DIR)/$name/mri/T1"
    }
  } else {
    set id [open $stmptcl w 0644]
    puts $id "setfile abs_imstem ~/mri/T1/COR-"
    puts $id "set lim0 $lim0; set ffrac0 $ffrac0"
    puts $id "set lim1 $lim1; set ffrac1 $ffrac1"
    puts $id "set lim2 $lim2; set ffrac2 $ffrac2"
    puts $id "set lim3 $lim3; set ffrac3 $ffrac3"
    puts $id "norm_allslices $normdir"
    puts $id "write_images"
    puts $id "exit"
    close $id
    set command "tkmedit $name orig -tcl $mtmptcl"
  }
  runacmd "$command" $normalizebu NORMALIZE cmdinput $cmdlog cmdpid
}

proc stripskullcmd { } {
  global cmdlog stripskullbu
  global env name force
  global fzero fmax dfrac istilt
  set firstim $env(SUBJECTS_DIR)/$name/mri/T1/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/T1/COR-* not found  ...normalize first"
    return
  }
  if {!$force} {
    set firstim $env(SUBJECTS_DIR)/$name/mri/brain/COR-001
    if [file exists $firstim] {
      if ![okreplace $firstim \
           "Images: $name/mri/brain/COR-* exist--overwrite?"] {
        confirmalert "Images: $name/mri/brain/COR-* not altered"
        return
      }
    }
  }
  set tclenv "fzero=$fzero fmax=$fmax dfrac=$dfrac istilt=$istilt" ;# !brain.dat
  set command "env $tclenv tktrishrink $name 0 -tcl stripskull.tcl"
  runacmd "$command" $stripskullbu STRIPSKULL cmdinput $cmdlog cmdpid
}

proc wmfiltercmd { } {
  global cmdlog wmfilterbu
  global env name force
  global white_hilim white_lolim gray_hilim minim maxim planefilterflag
  if [checkconcurrent] { return }
  set firstim $env(SUBJECTS_DIR)/$name/mri/brain/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/brain/COR-* not found  ...stripskull first"
    return
  }
  if {!$force} {
    set firstim $env(SUBJECTS_DIR)/$name/mri/wm/COR-001
    if [file exists $firstim] {
      if ![okreplace $firstim \
         "Images: $name/mri/wm/COR-* exist--overwrite? (may be edited!!)"] {
        confirmalert "Images: $name/mri/wm/COR-* not altered"
        return
      }
    }
  }
  if {$white_hilim < $white_lolim} {
    confirmalert "Images: bad limits: white_hilim < white_lolim (=> all black)"
    return
  }
  if ![file writable wmfilter.dat] {
    confirmalert \
      "Can't write file: wmfilter.dat in $env(SUBJECTS_DIR)/$name/scripts"
    return
  }
  set id [open wmfilter.dat w 0644]
  puts $id "white_hilim $white_hilim"
  puts $id "white_lolim $white_lolim"
  puts $id "gray_hilim $gray_hilim"
  puts $id "minim $wmfilter_minim"
  puts $id "maxim $wmfilter_maxim"
  puts $id "planefilterflag $planefilterflag"
  close $id
  set filter_cycles 1
  set command "wmfilter $name $filter_cycles"
  runacmd "$command" $wmfilterbu WMFILTER cmdinput $cmdlog cmdpid
}

proc initfillcmd { } {
  global cmdlog initfillbu
  global env name
  if [checkconcurrent] { return }
  set firstim $env(SUBJECTS_DIR)/$name/mri/wm/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/wm/COR-* not found  ...wmfilter,edit first"
    return
  }
  set command "mkfilldat $name fill.dat"
  runacmd "$command" $initfillbu INITFILL cmdinput $cmdlog cmdpid
  tkwait variable cmdpid
  readfilldat
}

proc readfilldat { } {
  global env name
  set scriptsdir $env(SUBJECTS_DIR)/$name/scripts
  if ![file exists fill.dat] {
    confirmalert "Datfile: fill.dat not found in scripts dir: $scriptsdir"
    return
  }
  set i 0
  set id [open fill.dat r]
  foreach line [split [read $id] \n] {
    set args [split $line " "]
    set var [lindex $args 0]
    set val [string trim [join [lrange $args 1 end]]]
    if {$i == 0}  { uplevel #0 "set nseed {$val}" }
    if {$i == 1}  { uplevel #0 "set seed1 {[lrange $val 0 2] 80}" } ;# fix cols
    if {$i == 2}  { uplevel #0 "set seed2 {[lrange $val 0 2] 255}" }
    if {$i == 3}  { uplevel #0 "set callosal_imnr {$val}" }
    if {$i == 4}  { uplevel #0 "set callosal_i {$val}" }
    if {$i == 5}  { uplevel #0 "set callosal_j {$val}" }
    if {$i == 6}  { uplevel #0 "set midbrain_imnr {$val}" }
    if {$i == 7}  { uplevel #0 "set midbrain_i {$val}" }
    if {$i == 8}  { uplevel #0 "set midbrain_j {$val}" }
    incr i 1
  }
  close $id
}

proc dofillcmd { } {
  global cmdlog dofillbu
  global env name force
  global nseed seed1 seed2 
  global callosal_imnr callosal_i callosal_j midbrain_imnr midbrain_i midbrain_j
  global max_fill_iter min_filled_per_cyc max_same_neigh 
  if [checkconcurrent] { return }
  set firstim $env(SUBJECTS_DIR)/$name/mri/wm/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/wm/COR-* not found  ...wmfilter,edit first"
    return
  }
  if {!$force} {
    set firstim $env(SUBJECTS_DIR)/$name/mri/filled/COR-001
    if [file exists $firstim] {
      if ![okreplace $firstim \
                     "Images: $name/mri/filled/COR-* exist--overwrite?"] {
        confirmalert "Images: $name/mri/filled/COR-* not altered"
        return
      }
    }
  }
  if ![file writable $env(SUBJECTS_DIR)/$name/scripts] {
    confirmalert \
      "Can't write file: fill.dat in $env(SUBJECTS_DIR)/$name/scripts"
    return
  }
  set id [open fill.dat w 0644]
  puts $id "nseed [join $nseed]"
  puts $id "seed1 [join $seed1]"
  puts $id "seed2 [join $seed2]"
  puts $id "imnr  [join $callosal_imnr]"
  puts $id "i     [join $callosal_i]"
  puts $id "j     [join $callosal_j]"
  puts $id "imnr  [join $midbrain_imnr]"
  puts $id "i     [join $midbrain_i]"
  puts $id "j     [join $midbrain_j]"
  puts $id "max_fill_iter       $max_fill_iter"
  puts $id "min_filled_per_cyc  $min_filled_per_cyc"
  puts $id "max_same_neigh      $max_same_neigh"
  close $id
  set command "fill $name 0"
  runacmd "$command" $dofillbu DOFILL cmdinput $cmdlog cmdpid
}

proc tessellcmd { } {
  global cmdlog tessellbu
  global env name hemi force
  global origext
  global seed1 seed2
  if [checkconcurrent] { return }
  checkbothhemi
  set firstim $env(SUBJECTS_DIR)/$name/mri/filled/COR-001
  if ![file exists $firstim] {
    confirmalert "Images: $name/mri/filled/COR-* not found ...init/dofill first"
    return
  }
  if {!$force} {
    set origsurf $env(SUBJECTS_DIR)/$name/surf/$hemi.$origext
    if { [file exists $origsurf] && ![okreplace $origsurf] } {
      confirmalert "Surface: $name/surf/$hemi.$origext not altered"
      return
    }
  }
  if {$hemi == "rh"} { set seedval [lindex $seed1 3] }
  if {$hemi == "lh"} { set seedval [lindex $seed2 3] }
  set command "surf $name $seedval $hemi"
  runacmd "$command" $tessellbu TESSELL cmdinput $cmdlog cmdpid
}

proc inflatecmd { } {
  global cmdlog inflatebu
  global env name hemi force
  global origext foldedext inflatedext
  global inflate_cthk inflate_mmid inflate_whitemid inflate_graymid
  if [checkconcurrent] { return }
  checkbothhemi
  set origsurf $env(SUBJECTS_DIR)/$name/surf/$hemi.$origext
  if ![file exists $origsurf] {
    confirmalert "Surface: $name/surf/$hemi.$origext not found ...tessell first"
    return
  }
  if {!$force} {
    set smoothwmsurf $env(SUBJECTS_DIR)/$name/surf/$hemi.$foldedext
    if { [file exists $smoothwmsurf] && ![okreplace $smoothwmsurf] } {
      confirmalert "Surface: $name/surf/$hemi.$smoothwmsurf not altered"
      return
    }
    set inflatedsurf $env(SUBJECTS_DIR)/$name/surf/$hemi.$inflatedext
    if { [file exists $inflatedsurf] && ![okreplace $inflatedsurf] } {
      confirmalert "Surface: $name/surf/$hemi.$inflatedsurf not altered"
      return
    }
  }
  catch {exec rm -f $env(SUBJECTS_DIR)/$name/surf/$hemi.area}
  set tclenv "cthk=$inflate_cthk tksurferinterface=macro \
       mmid=$inflate_mmid whitemid=$inflate_whitemid graymid=$inflate_graymid"
  set command "env $tclenv tksurfer -$name $hemi $origext -tcl inflate.tcl"
  runacmd "$command" $inflatebu INFLATE cmdinput $cmdlog cmdpid
}

proc flattencmd { } {
  global cmdlog flattenbu
  global env name hemi force
  global inflatedext 3dbeginext flatbeginext flatendext patchext
  if [checkconcurrent] { return }
  checkbothhemi
  if ![file exists position.tcl] { mkpositiontcl }
  # inpatch
  set patchroot [file rootname $patchext]
  set inpatch $env(SUBJECTS_DIR)/$name/surf/$hemi.$patchroot.$3dbeginext
  if ![file exists $inpatch] {
    set inpatch $env(SUBJECTS_DIR)/$name/surf/$hemi.$patchroot.$flatbeginext
  }
  if ![file exists $inpatch] {
    confirmalert "Patch: inpatch not found--tried:\n \
      $env(SUBJECTS_DIR)/$name/surf/$hemi.$patchroot.$3dbeginext\n \
      $env(SUBJECTS_DIR)/$name/surf/$hemi.$patchroot.$flatbeginext"
    return
  }
  # outpatch
  if { [file ext $patchext] != "$flatendext" } {
    confirmalert "Patch: bad outpatch extension: [file ext $patchext]"
    return
  }
  set outpatch $env(SUBJECTS_DIR)/$name/surf/$hemi.$patchroot.$flatendext
  if {!$force} {
    if { [file exists $outpatch] && ![okreplace $outpatch] } {
      confirmalert "Patch: $outpatch not altered"
      return
    }
  }
  set tclenv "shrinkcycles=$shrinkcycles \
                   inpatch=[file tail $inpatch] outpatch=[file tail $outpatch]"
  set command "env $tclenv tksurfer -$name $hemi $inflatedext -tcl flatten.tcl"
  runacmd "$command" $flattenbu FLATTEN cmdinput $cmdlog cmdpid
}

proc checkconcurrent { } {
  global cmdpid
  if {$cmdpid != -1} {
    set currproc [lrange [exec ps -af | grep $cmdpid] 7 end]      ;# sys5
    #set currproc [lrange [exec ps -uxww | grep $cmdpid] 10 end]  ;# BSD
    confirmalert "Running: $currproc\nCan't start second process"
    return 1
  }
  return 0
}

proc checkbothhemi { } {
  global hemi otherhemi hemitype
  if {$hemi == "both"} {
    set otherhemi 1
    set hemi rh
    set hemitype 0
  }
}

proc runacmd { command bu bulabel inpnam log pidnam } {
  upvar $inpnam inp
  global $pidnam
  global runbgcol runactbgcol
  ### TODO: bad returns from command line now only in log
  if [catch {open "|$command |& cat" a+} inp] {
    $log insert end $inp\n
  } else {
    set cmdproc [$bu cget -command]
    fileevent $inp readable "readcmdlog $cmdproc $bu $bulabel $inp $log $pidnam"
    $log insert end $command\n
    #set qlabel $bulabel
    set qlabel [string range $bulabel 0 [expr [string length $bulabel] -5]]
    $bu config -text "quit$qlabel" \
       -background $runbgcol -activebackground $runactbgcol \
       -command "quitacmd $cmdproc $bu $bulabel $inp $log $pidnam"
    set $pidnam [lindex [pid $inp] 0]    ;# 2nd arg is cat pid
  }
}

proc readcmdlog { cmdproc bu bulabel inp log pidnam } {
  if [eof $inp] {
    catch {close $inp}
    quitacmd $cmdproc $bu $bulabel $inp $log $pidnam   ;# killbox
  } else {
    gets $inp line
    $log insert end $line\n
    $log see end
    update idletasks     ;# else tk dead; also fflush(stdout) printf's
  }
}

proc quitacmd { cmdproc bu bulabel inp log pidnam } {
  global $pidnam stmptcl mtmptcl ctmptcl
  global env name
  global bgcol actbgcol
  set pidval [set $pidnam]
  if {$pidval != -1} { catch { exec kill -9 $pidval } }
  #TODO: should return if not killed, but would have to wait for death
  set $pidnam -1
  $bu config -text "$bulabel" -command $cmdproc \
     -background $bgcol -activebackground $actbgcol
  exec rm -f $stmptcl $mtmptcl $ctmptcl
  cd $env(SUBJECTS_DIR)/$name/scripts
  repeatifboth $bu
}

proc repeatifboth { bu } {
  global otherhemi hemi
  if {$otherhemi} {
    if {$hemi == "rh"} {
      set hemi lh; set hemitype 1
    } else {
      set hemi rh; set hemitype 0
    }
    set otherhemi 0
    $bu invoke
  }
}

proc testclose { } {
  global stmptcl mtmptcl ctmptcl editeddat datfile datfilelist
  if {$editeddat} {
    set resp [okclose $datfile]
    if {$resp == 0} { return }                              ;# cancel
    if {$resp == 1} {        }                              ;# don't save, quit
    if {$resp == 2} { writecshparms $datfile $datfilelist } ;# save, quit
  }
  exec rm -f $stmptcl $mtmptcl $ctmptcl fill.dat wmfilter.dat
  exit
}

proc hidelogs { } {
  set winlist { .cmd .med.lg .sur.lg }
  foreach win $winlist { pack forget $win }
  pack .med.bu .sur.bu
  pack .med .sur -fill x
}

proc showlogs { } {
  pack .cmd -after .but -fill x
  pack .med .sur .med.lg .sur.lg
  pack .med.lg.log -side left -fill both -expand true
  pack .sur.lg.log -side left -fill both -expand true
}

#################################################################
wm title . "$program"
wm geometry . +8+32 ;# +0-0
wm protocol . WM_DELETE_WINDOW testclose

frame .but
pack .but -side top
  frame .but.left
  pack .but.left -side left
    frame .but.left.top
    pack .but.left.top -side top -anchor w
    frame .but.left.mid
    pack .but.left.mid -side top -anchor w
    frame .but.left.bot
    pack .but.left.bot -side top -anchor w
    frame .but.left.bot2
    pack .but.left.bot2 -side top -anchor w
    frame .but.left.con
    pack .but.left.con -side top -anchor w
    frame .but.left.con1
    pack .but.left.con1 -side top -anchor w
    frame .but.left.con2
    pack .but.left.con2 -side top -anchor w
    frame .but.left.con3
    pack .but.left.con3 -side top -anchor w
  frame .but.right
  pack .but.right -side left
    frame .but.right.tal
    pack .but.right.tal -side top -anchor w
    frame .but.right.nor
    pack .but.right.nor -side top -anchor w
    frame .but.right.nor1
    pack .but.right.nor1 -side top -anchor w
    frame .but.right.nor2
    pack .but.right.nor2 -side top -anchor w
    frame .but.right.str
    pack .but.right.str -side top -anchor w
    frame .but.right.wm
    pack .but.right.wm -side top -anchor w
    frame .but.right.in
    pack .but.right.in -side top -anchor w
    frame .but.right.in1
    pack .but.right.in1 -side top -anchor w
    frame .but.right.in2
    pack .but.right.in2 -side top -anchor w
    frame .but.right.do
    pack .but.right.do -side top -anchor w
frame .cmd -borderwidth 3 -relief sunken
pack .cmd -side top
  frame .cmd.lg
  pack .cmd.lg -side top
frame .med -borderwidth 3 -relief sunken
pack .med -side top
  frame .med.bu
  pack .med.bu -side top
  frame .med.lg
  pack .med.lg -side top
frame .sur -borderwidth 3 -relief sunken
pack .sur -side top
  frame .sur.bu
  pack .sur.bu -side top
  frame .sur.lg
  pack .sur.lg -side top

#################################################################
### main buttons
set f .but.left.top
# first entries
edlabval $f "home"     $env(SUBJECTS_DIR) n 5 17 col
checks $f.home "" "logs" logflag row
$f.home.alogs.ck config -command { if {$logflag} {showlogs} else {hidelogs} }
edlabval $f "parm"     $datfile          rw 5 10
$f.home.e     config -textvariable env(SUBJECTS_DIR)
$f.parm.e     config -textvariable datfile
$f.parm.br config -padx 5
$f.parm.bw config -padx 5
$f.parm.br  config -command { readcshparms $datfile }
$f.parm.bw  config -command { writecshparms $datfile $datfilelist }
edlabval $f "subject"  $name     n 8 12 row
$f.subject.e  config -textvariable name
trace variable env(SUBJECTS_DIR) w fixhome
trace variable name w fixhome
buttons $f "NEWSUBJ" { mknewsubj $env(SUBJECTS_DIR) $name } row 1 7

# more buttons
set f .but.left.mid
radios $f "hemisph" "rh"   hemitype 0 8 row
radios $f ""        "lh"   hemitype 1 8 row
radios $f ""        "both" hemitype 2 8 row
$f.arh.la   config -font $ffont
$f.arh.ra   config -command { set hemi rh }
$f.alh.ra   config -command { set hemi lh }
$f.aboth.ra config -command { set hemi both }

# more entries
set f .but.left.bot
edlabval $f "surface"  $ext      n 8 10 row
$f.surface.e  config -textvariable ext
checks $f "" "force" force row

set f .but.left.bot2
edlabval $f "patch"    $patchext n 8 17
$f.patch.e    config -textvariable patchext

set f .but.left.con
buttons $f "CONVERT" { convertcmd } row 1 9
set convertbu $f.aCONVERT.bu
edlabval $f "type" $scantype n 5 7 row
checks $f "" "reg" registeravg row
$f.type.e config -textvariable scantype

set f .but.left.con1
edlabval $f "files" $filepatterns n 6 25 row
$f.files.e config -textvariable filepatterns

set f .but.left.con2
edlabval $f "nm" $firstnumbers n 3 5 row
edlabval $f "sl" $numslices n 3 3 row
edlabval $f "flip" $flipCORview n 5 6 row
$f.nm.e config -textvariable firstnumbers
$f.sl.e config -textvariable numslices
$f.flip.e config -textvariable flipCORview

set f .but.left.con3
edlabval $f "thick" $thickness n 6 3 row
edlabval $f "fov" $numslices n 4 3 row
edlabval $f "prescl" $prescale n 7 2 row
$f.thick.e config -textvariable thickness
$f.fov.e config -textvariable fov
$f.prescl.e config -textvariable prescale

set f .but.right.tal
buttons $f "TALAIRACH" { talairachcmd } row 1 9
set talairachbu $f.aTALAIRACH.bu
edlabval $f "mniproto" $mniproto n 9 4 row
edlabval $f "model"    $model    n 6 16 row
$f.mniproto.e config -textvariable mniproto
$f.model.e config -textvariable model

set f .but.right.nor
buttons $f "NORMALIZE" { normalizecmd } row 1 9
set normalizebu $f.aNORMALIZE.bu
checks $f "" "auto" autonormalize row
radios $f "manual" "P/A" normdir 0 8 row
radios $f ""       "I/S" normdir 1 3 row
radios $f ""       "R/L" normdir 2 3 row
$f.aP/A.la config -font $ffont

set f .but.right.nor1
edlabval $f "lim0"  $lim0 n 7 4 row
edlabval $f "lim1"  $lim1 n 6 4 row
edlabval $f "lim2"  $lim2 n 6 4 row
edlabval $f "lim3"  $lim3 n 6 4 row
$f.lim0.e config -textvariable lim0
$f.lim1.e config -textvariable lim1
$f.lim2.e config -textvariable lim2
$f.lim3.e config -textvariable lim3

set f .but.right.nor2
edlabval $f "frac0"  $ffrac0 n 7 4 row
edlabval $f "frac1"  $ffrac1 n 6 4 row
edlabval $f "frac2"  $ffrac2 n 6 4 row
edlabval $f "frac3"  $ffrac3 n 6 4 row
$f.frac0.e config -textvariable ffrac0
$f.frac1.e config -textvariable ffrac1
$f.frac2.e config -textvariable ffrac2
$f.frac3.e config -textvariable ffrac3

set f .but.right.str
buttons $f "STRIPSKULL" { stripskullcmd } row 1 9
set stripskullbu $f.aSTRIPSKULL.bu
edlabval $f "fzero"  $fzero  n 6 3 row
edlabval $f "fmax"   $fmax   n 5 4 row
#edlabval $f "dfrac" $dfrac  n 6 3 row
edlabval $f "istilt" $istilt n 7 3 row
$f.fzero.e config -textvariable fzero
$f.fmax.e config -textvariable fmax
#$f.dfrac.e config -textvariable dfrac
$f.istilt.e config -textvariable istilt

set f .but.right.wm
buttons $f "WMFILTER" { wmfiltercmd } row 1 9
set wmfilterbu $f.aWMFILTER.bu
edlabval $f "low"      $white_lolim n 6 3 row
edlabval $f "high"     $white_hilim n 5 4 row
edlabval $f "grayhigh" $gray_hilim  n 9 4 row
$f.low.e config -textvariable white_lolim
$f.high.e config -textvariable white_hilim
$f.grayhigh.e config -textvariable gray_hilim

set f .but.right.in
buttons $f "INITFILL" { initfillcmd } row 1 9
set initfillbu $f.aINITFILL.bu
edlabval $f "seeds"  $seed1 n 6 15 row
edlabval $f "none1"  $seed2 n 0 15 row
$f.seeds.e config -textvariable $seed1
$f.none1.e config -textvariable $seed2

set f .but.right.in1
edlabval $f "callosumboxP/A" $callosal_imnr n 16 7 row
edlabval $f "aI/S"    $callosal_i    n 4 7 row
edlabval $f "aR/L"    $callosal_j    n 4 7 row
$f.callosumboxP/A.e config -textvariable callosal_imnr
$f.aI/S.e config -textvariable callosal_i
$f.aR/L.e config -textvariable callosal_j
$f.callosumboxP/A.la config -text "callosumbox P/A:"  ;# manually add space
$f.aI/S.la config -text I/S:      ;# manually rm 'a' (lower case widget name)
$f.aR/L.la config -text R/L:

set f .but.right.in2
edlabval $f "midbrainboxP/A" $midbrain_imnr n 16 7 row
edlabval $f "aI/S"    $midbrain_i    n 4 7 row
edlabval $f "aR/L"    $midbrain_j    n 4 7 row
$f.midbrainboxP/A.e config -textvariable midbrain_imnr
$f.aI/S.e config -textvariable midbrain_i
$f.aR/L.e config -textvariable midbrain_j
$f.midbrainboxP/A.la config -text "midbrainbox P/A:"
$f.aI/S.la config -text I/S:
$f.aR/L.la config -text R/L:

set f .but.right.do
buttons $f "DOFILL" { dofillcmd } row 1 9
set dofillbu $f.aDOFILL.bu
buttons $f "TESSELL" { tessellcmd } row 1 9
set tessellbu $f.aTESSELL.bu
buttons $f "INFLATE" { inflatecmd } row 1 9
set inflatebu $f.aINFLATE.bu
buttons $f "FLATTEN" { flattencmd } row 1 9
set flattenbu $f.aFLATTEN.bu
edlabval $f "cyc" $shrinkcycles n 0 3
$f.cyc.e config -textvariable shrinkcycles

# run buttons
set f .med.bu
buttons $f "MEDIT" { meditcmd } row 1
set medbu $f.aMEDIT.bu

# mritype radio
set f .med.bu
radios $f "mri image set" "orig"   mritype 0 14 row
radios $f ""           "T1"        mritype 1 11 row
radios $f ""           "brain"     mritype 2 11 row
radios $f ""           "wm"        mritype 3 11 row
radios $f ""           "filled"    mritype 4 11 row
trace variable mritype w fixeditable
edlabval $f "none1" $editable n 0 7 row
$f.none1.e  config -textvariable editable

# cmd log
set f .cmd.lg
set cmdlog [text $f.log -width 80 -height $loglines -borderwidth 2 \
 -relief sunken -font $ffont -setgrid true -yscrollcommand {.cmd.lg.scroll set}]
scrollbar $f.scroll -command {.cmd.lg.log yview}
pack $f.scroll -side right -fill y
pack $f.log -side left -fill both -expand true

# tkmedit log
set f .med.lg
set medlog [text $f.log -width 80 -height $loglines -borderwidth 2 \
 -relief sunken -font $ffont -setgrid true -yscrollcommand {.med.lg.scroll set}]
scrollbar $f.scroll -command {.med.lg.log yview}
pack $f.scroll -side right -fill y
pack $f.log -side left -fill both -expand true

# run buttons
set f .sur.bu
buttons $f "SURFER" { surfercmd } row 1
set surfbu $f.aSURFER.bu

# surf viewtype radio
set f .sur.bu
radios $f "surf" "folded"    viewtype 0 5 row
radios $f ""     "inflated"  viewtype 1 5 row
radios $f ""     "viewcuts"  viewtype 2 5 row
radios $f ""     "partflat"  viewtype 3 5 row
radios $f ""     "fullflat"  viewtype 4 5 row
$f.afolded.ra   config -command { set ext $foldedext }
$f.ainflated.ra config -command { set ext $inflatedext }
$f.aviewcuts.ra config -command { set ext $inflatedext }
$f.apartflat.ra config -command { set ext $inflatedext; \
                                  set patchext $partialpatch.$flatendext }
$f.afullflat.ra config -command { set ext $inflatedext; \
                                  set patchext $fullpatch.$flatendext }
# tksurfer log
set f .sur.lg
set surflog [text $f.log -width 80 -height $loglines -borderwidth 2 \
 -relief sunken -font $ffont -setgrid true -yscrollcommand {.sur.lg.scroll set}]
scrollbar $f.scroll -command {.sur.lg.log yview}
pack $f.scroll -side right -fill y
pack $f.log -side left -fill both -expand true

############################################################################
### TODO: put named right click help files in: ~/mri/lib/tcl/bsurf/*
bind $convertbu <ButtonRelease-3> { helpwin convert }
bind $talairachbu <ButtonRelease-3> { helpwin talairach }
bind $stripskullbu <ButtonRelease-3> { helpwin stripskull }
bind $wmfilterbu <ButtonRelease-3> { helpwin wmfilter }
bind $initfillbu <ButtonRelease-3> { helpwin initfill }
bind $dofillbu <ButtonRelease-3> { helpwin dofill }
bind $inflatebu <ButtonRelease-3> { helpwin inflate }
bind $tessellbu <ButtonRelease-3> { helpwin tessell }
bind $flattenbu <ButtonRelease-3> { helpwin flatten }
bind $medbu <ButtonRelease-3> { helpwin medit }
bind $surfbu <ButtonRelease-3> { helpwin surfer }

############################################################################
if {!$logflag} {hidelogs}
fixcolors 
.but.right.tal.model.e xview end
wm resizable . 0 0

