#! /usr/bin/tclsh
#############################################################################
# tksurfer script: phasemovie.tcl  [save phase movie; interactive or batch]
##############################################################################
### def tcl-only on 1st entry (don't biff set-by-popup on interactive reenter)
if ![info exists userok]           { set userok 0 }
if ![info exists phasemin]         { set phasemin 0.0 }
if ![info exists phasemax]         { set phasemax 1.0 }
if ![info exists phasewidth]       { set phasewidth 0.03 }
if ![info exists phasesteps]       { set phasesteps 50 }
if ![info exists makempg1_cleanup] { set makempg1_cleanup 0}
if ![info exists justnumberframes] { set justnumberframes 0 }
if ![info exists dontsaveframesflag] { set dontsaveframesflag 0 }

### HOWTO: run interactively from tksurfer using current surface pose/data
#  select phasemovie.tcl from "tcl:" dropdown (under DEFAULT LIB SCRIPTS)
#  GO
#  adjust parms in pop-up
#  RUN SCRIPT
#

### HOWTO: run from shell/cmdline
#  copy this default lib script into a subject/session scripts dir
#  uncomment/adjust parameters below
#  example (session=140430MSa, scandir=rawavg):
#    cd $FUNCTIONALS_DIR/140430MSa/image/rawavg-all/scripts
#    tksurfer marser-qT1 rh inflated -tcl phasemovie.tcl
#

### HOWTO: reverse progression, deal with wrap around 1.0
#  to reverse order of phase progression, swap $phasemin and $phasemax
#  if desired range of phases wraps around 1.0, use $phasemax above 1.0
#

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

### set tcl-only popup parameters (not linked to tksurfer C-variables)
#set phasemin 0.0
#set phasemax 1.0
#set phasewidth 0.03
#set phasesteps 50
#set makempg1_cleanup 0
#set justnumberframes 0
#set dontsaveframesflag 0

### set tcl-variables linked to C-variables in tksurfer.c
# for complete list, see: tksurfer -help
### isession autoset to $cwd/.. if cwd="scripts" (set if cmdline elsewhere)
#set isession $env(FUNCTIONALS_DIR)/140430MSa/image
#set scandir 1-polletdilima1         ;# set scandir
### open window, read some stats to contour
#open_window
#setfile insurf ~/surf/$hemi.inflated
#read_binary_surface
#setfile curv ~/surf/$hemi.curv
#read_binary_curv
#make_lateral_view
#set overlayflag 1
#set complexvalflag 1
#set statprefix polar1
#setfile val */$scandir/${statprefix}_i-$hemi.w
#smooth_val 5
#copy_val_val2
#setfile val */$scandir/${statprefix}_r-$hemi.w
#smooth_val 5
#make_lateral_view
#rotate_brain_y 20
#redraw
##############################################################################

### old partial sweep preset parms for reference (was triggered by rgbname)
#if {$rgbname == "eccen"} {
#  set phasemin -0.3
#  set phasemax 0.5
#  set phasewidth 0.05
#}
#if {$rgbname == "polar"} {
#  set phasemin -0.5
#  set phasemax 0.2
#  set phasewidth 0.03
#}
#if {$rgbname == "downsweep"} {
#  set phasemin 0.2
#  set phasemax 0.52
#  set phasewidth 0.03
#}
#if {$rgbname == "upsweep"} {
#  set phasemin 0.3
#  set phasemax 0.7
#  set phasewidth 0.03
#}

### session tkmedit overlay
if { [info exists interfacefile] && $interfacefile == "tkmedit.tcl" } {
  set hemi both   ;# don't overlap tksurfer images
  set flag2d 0
  set surfext vol
}

### popup controls (always override nosave if on)
if ![info exists phasemoviectrls] { set phasemoviectrls "" }
if [winfo viewable .] {    ;# make popup
  if {!$userok} {
    if [winfo exists $phasemoviectrls] { raise $phasemoviectrls; return }
    set phasemoviectrls [controls "SAVE PHASE MOVIE" {
      rgbname phasemin phasemax phasewidth phasesteps
      phasecontourmodflag colphasecontourflag phasecontour_bright
      makempg1_cleanup justnumberframes dontsaveframesflag
    } "RUN SCRIPT" "set userok 1; source [info script]" 20]
    # internal controls proc hack (tickbox wins start at ck0)
    $phasemoviectrls.ck1 config -command {
      if {$colphasecontourflag} {
        set phasecontour_bright 20
      } else {
        set phasecontour_bright 255
      }
    }
    bind $phasemoviectrls <ButtonRelease-3> { helpwin script_phasemovie }
    return
  }
} else {                   ;# batch scripts; re-read env to override defaults
  source $env(CSURF_DIR)/lib/tcl/readenv.tcl
}
if [info exists nosave] {puts "phasemovie.tcl: nosave is set -- overriding it"}

### tmp reset named_rgbdir if detect abspath (N.B.: mpgs still go to session)
set named_rgbdirSAV $named_rgbdir
if [string match /* $rgbname] {
  set named_rgbdir [file dirname $rgbname]
  set rgbname [file tail $rgbname]
}

### save phasemovie frames (phase in {-0.5,0.5}; before rev, inv)
puts "phasemovie.tcl: making phasemovie"
set imsuff rgb
if [info exists tiffoutflag] {
  if {$tiffoutflag} { set imsuff tiff }
}
puts "     files: $rgbname-phmov-$hemi-{currsurface}-???,ph=+?.??.$imsuff"
prompt
raise_window
set incr [expr ($phasemax-$phasemin)/$phasesteps]
set phasecontourmodflag 1
set phasecontourflag 1
set i 0
if {$incr > 0.0} { 
  set phasetest {$phase < $phasemax}
} else {
  set phasetest {$phase > $phasemax}
}

for {set phase $phasemin} $phasetest {set phase [expr $phase+$incr]} {
  ## tksurfer divides phase across max/min boundary--just wrap into [-0.5,0.5]
  set phasecontour_min [expr $phase - $phasewidth/2.0]
  if { $phasecontour_min > 0.5 } {
    set phasecontour_min [expr $phasecontour_min - 1.0]
  }
  if { $phasecontour_min < -0.5 } {
    set phasecontour_min [expr $phasecontour_min + 1.0]
  }
  set phasecontour_max [expr $phase + $phasewidth/2.0]
  if { $phasecontour_max > 0.5 } {
    set phasecontour_max [expr $phasecontour_max - 1.0]
  }
  if { $phasecontour_max < -0.5 } {
    set phasecontour_max [expr $phasecontour_max + 1.0]
  }
  redraw
  set rgbnum [format "%03d" $i]
  set phanum ph=[format "%+2.2f" $phase]
  ## name doesn't incl lat/med/etc, real patchname => OK for tmp/overwrite
  set currext ""
  if {$dontsaveframesflag} {
    # 
  } elseif {$justnumberframes} {
    save_rgb_named f[format "%05d" $i].$imsuff
  } elseif {$flag2d} {
    set currext "flat"
    save_rgb_named $rgbname-phmov-$hemi-$currext-$rgbnum,$phanum.$imsuff
  } else {
    set currext $surfext
    save_rgb_named $rgbname-phmov-$hemi-$currext-$rgbnum,$phanum.$imsuff
  }
  incr i
}

### optional convert to quality=1 mpg, test show (50X compression)
if {$makempg1_cleanup && !$justnumberframes} {
  puts "phasemovie.tcl: making mpg, deleting frames when done"
  set dirSAV [pwd]
  cd $named_rgbdir
  set impatt $rgbname-phmov-$hemi-$currext-???,ph=+?.??
  set mpgname $isession/mpg/$rgbname-phmov-$hemi-$currext.mpg
  if {$imsuff == "rgb"} {
    puts [eval exec rgb2mpg -q 1 $impatt.$imsuff $mpgname]
  }
  if {$imsuff == "tiff"} {
    puts [eval exec tiff2mpg -q 1 $impatt.$imsuff $mpgname]
  }
  puts [eval exec mpeg_play -dither color -quiet -loop $mpgname >& /dev/null &]
  foreach tmprgb [lsort [glob $impatt.$imsuff]] { exec rm $tmprgb }
  cd $dirSAV
}

### cleanup: restore tksurfer vars
set phasecontourflag 0
set named_rgbdir $named_rgbdirSAV
set userok 0
#if [info exists phasemoviectrls] { destroy $phasemoviectrls }
return   ;# else catch returns err (=last return of last command)

