##############################################################################
# flatten movie
##############################################################################
# N.B.: assumes ExpertPrefs "write every x iter" not 0 (else no steps saved)
# N.B.: req's first/last file, skips any missing intermediate, can force skip
# interactive, or: tksurfer marty rh smoothwm -tcl flattenmovie.tcl
### N.B.: caller should init $userok to 0

### hard defaults
if ![info exists userok] { set userok 0 }

### adjustable parms (interactive adj w/popup, or edit here for cmdline script)
if {!$userok} {  ;# don't blow away reset by controls on re-entry
  set patchinfix full.patch.flat
  set patchzrot     90   ;# math degrees
  set patchscale   0.3   ;# 
  set patchxtrans  0.0   ;# percent of current display width
  set patchytrans  0.0   ;# percent of current display width
  set f             0    ;# can reset to append
  set minflat        0   ;#
  set maxflat      600   ;# skips any missing intermediate
  #set skip          0   ;# how many surfaces to skip each step
  set every          1   ;# easier to understand
  set outdir      /tmp   ;# or: $env(SUBJECTS_DIR)/$subject/rgb
  set mkmpg1flag     0   ;# turn on to make mpg (doesn't delete tiffs)
  set normarea       1   ;# do every step
}

#############################################################################
### init patchinfix from current $patch
set patchinfix [string range [file rootname [file tail $patch]].flat 3 end]

### start w/pose from current position.tcl if there
set postcl $env(SUBJECTS_DIR)/$subject/scripts/position.tcl
if [file exists $postcl] {
  set type full
  source $postcl
  if [string match $hemi.cortex*.patch.flat $patch] { set type full }
  if [string match $hemi.full*.patch.flat $patch] { set type full }
  if [string match $hemi.occ*.patch.flat $patch] { set type occip }
  # N.B.: next blows away any interface settings so entries disabled
  puts "flattenmovie.tcl: using ExpertPrefs Views (position.tcl) for type=$type"
  set patchzrot [set $hemi.$type.patch.flat.flatzrot]
  set patchscale [set $hemi.$type.patch.flat.flatscale]
  set patchxtrans [set $hemi.$type.patch.flat.flatxtrans]
  set patchytrans [set $hemi.$type.patch.flat.flatytrans]
}

### for cmdline use
if {!$openglwindowflag} { open_window }

### popup controls (N.B.: buttonname "RUN SCRIPT" req'd for purplekillcontrols)
if ![info exists flattenmoviectrls] { set flattenmoviectrls "" }
if [winfo viewable .] {  ;# popup
  if {!$userok} {
    if [winfo exists $flattenmoviectrls] { raise $flattenmoviectrls; return }
    set flattenmoviectrls [controls "FLATTEN MOVIE\
          \nExpertPrefs \"write every x iter\" != 0\
          \nPatch pose from ExpertPrefs -> Views" {
      patchinfix patchzrot patchscale patchxtrans patchytrans f \
      minflat maxflat every outdir
    } "RUN SCRIPT" "set userok 1; source [info script]" 20]
    bind $flattenmoviectrls <ButtonRelease-3> { helpwin script_flattenmovie }
    # hack internals
    if [file exists $postcl] {
      $flattenmoviectrls.patchzrot.e config -state disabled
      $flattenmoviectrls.patchscale.e config -state disabled
      $flattenmoviectrls.patchxtrans.e config -state disabled
      $flattenmoviectrls.patchytrans.e config -state disabled
    }
    return
  }
} else {                 ;# batch scripts; re-read env to override defaults
  source $env(CSURF_DIR)/lib/tcl/readenv.tcl
}
set skip [expr $every - 1]

### report, even if aborted
puts ""
puts "flattenmovie.tcl: patchinfix = $patchinfix"
puts "flattenmovie.tcl: patchzrot = $patchzrot"
puts "flattenmovie.tcl: patchscale = $patchscale"
puts "flattenmovie.tcl: patchxtrans = $patchxtrans"
puts "flattenmovie.tcl: patchytrans = $patchytrans"
puts "flattenmovie.tcl: f = $f"
puts "flattenmovie.tcl: minflat = $minflat"
puts "flattenmovie.tcl: maxflat = $maxflat"
puts "flattenmovie.tcl: every = $every (skip = $skip)"
puts "flattenmovie.tcl: outdir = $outdir"
puts "flattenmovie.tcl: mkmpg1flag = $mkmpg1flag"
puts "flattenmovie.tcl: normarea = $normarea"
puts ""

### check first/last req'd input patch there
set patchbeg \
  $env(SUBJECTS_DIR)/$subject/surf/$hemi.$patchinfix[format "%04d" $minflat]
if ![file exists $patchbeg] {
  confirmalert "first flatten step missing:\n\n    $patchbeg\n\n...quitting"
  return
}
set patchend \
  $env(SUBJECTS_DIR)/$subject/surf/$hemi.$patchinfix[format "%04d" $maxflat]
if ![file exists $patchend] {
  confirmalert "last flatten step missing:\n\n    $patchend\n\n...quitting"
  return
}

### resize window -- TODO: script start before done, would need redrawdoneflag
#resize_window 800 $tiffsize 
#redraw
#update  

### go
puts "flattenmovie.tcl: #####################################"
puts "flattenmovie.tcl: begin saving tiffs (startframe=f[format "%04d" $f])"
puts "flattenmovie.tcl: #####################################"
if {$skip != 0} { puts "flattenmovie.tcl: skipping $skip frames each step" }
set dstep [expr $skip + 1]
set tiffcnt 0

### save movie
set drawnflag 0
for {set flatstep $minflat} {$flatstep <= $maxflat} {incr flatstep $dstep} {
  setfile patch $hemi.$patchinfix[format "%04d" $flatstep]
  if ![file exists $patch] {
    puts "flattenmovie.tcl: skip $patch (not found)"
    continue
  }
  read_binary_patch
  if {$normarea} { normalize_area }
  restore_zero_position
  rotate_brain_x -90
  rotate_brain_z $patchzrot
  translate_brain_x $patchxtrans
  translate_brain_y $patchytrans
  scale_brain $patchscale
  if {!$drawnflag} { redraw; set drawnflag 1 } else { redraw_cached }
  raise_window
  set rgb $outdir/f[format "%04d" $f].tiff  ;#next not rec by QuickTime as seq
  #set rgb $outdir/f[format "%04d" $f].p[format "%04d" $flatstep].tiff
  #set rgb $outdir/f[format "%04d" $f]-p[format "%04d" $flatstep].tiff
  save_rgb
  incr f
  incr tiffcnt
  update
  if {$purplekillcontrols} {
    set purplekillcontrols 0
    confirmalert "Script interrupted:\n\n$script"
    return
  }
}

### done
puts "flattenmovie.tcl: ########################"
puts "flattenmovie.tcl: done saving $tiffcnt tiffs"
puts "flattenmovie.tcl: ########################"

### make mpg
if {$mkmpg1flag} {
  set mpgname $subject-$patchinfix-$hemi.mpg
  puts [eval exec tiff2mpg -q 1 $outdir/f????.tiff $mpgname]
  puts [eval exec mpeg_play -dither color -quiet -loop $mpgname >& /dev/null]
}

### cleanup (don't destroy window or reset userok to save so many re-settable)
#if [info exists flattenmoviectrls] { destroy $flattenmoviectrls }

