#! /bin/sh
# (next line not seen by tcl) \
exec tclsh $0 ${1+"$@"}    # goto tcl

### hack register.dat's with linearly interpolated A/P 

### hardcoded: 2 B0's and 61 diff dirs
set ddircnt 63

### set imagedir /usr0/fspace/120606CI/image
#set imagedir /usr0/fspace/100924MSb/image
### prefix
#set pref f120606CI
#set pref f100924
### within scan A/P offsets from successive 1st img "just-A/P" register.dat's
#set repdel -2.3  ;# estimated from AFNI blink comparison on first B0 pair
#set replist "0004 0005"  ;# 2.3^3
#set repdel -3.4  ;# estimated from AFNI blink comparison on first B0 pair
#set replist "0002 0003"   ;# 1.7^3

if { [llength $argv] != 3 } {
  puts ""
  puts "usage: shiftreg.tcl <imagedir> <pref> <repdel>"
  puts ""
  puts " e.g.: shiftreg.tcl /usr0/fspace/100924MSb/image f100924-0004 -2.3"
  puts ""
  exit
}
set imagedir [lindex $argv 0]
set pref [lindex $argv 1]
set repdel [lindex $argv 2]

# since run2 piecewise aligned to run1, just add run1->run2 ramp to both
# read register.dat from 1 (prev: same register.dat copied to each ddir)
set ddir 1
set scandir $imagedir/$pref-[format "%05d" $ddir]
cd $scandir
set id [open register.dat r]  ;# read "incl ROT" reg.dat for 1st B0img
set lines [split [read $id] \n]
close $id
# modify register.dat 2-62
set ddir 2
while {$ddir < $ddircnt} { ;# lin ramp for ddirs: interpol 3rd line delta
  set scandir $imagedir/$pref-[format "%05d" $ddir]
  cd $scandir
  puts "\n### orig matrix for $scandir"
  set id [open register.dat r]
  set lines2 [split [read $id] \n]
  close $id
  foreach line $lines2 { puts $line }
  if ![file exists register.datORIG] {
    eval exec cp register.dat register.datORIG
  }
  set id [open register.datORIG w 0644]
  set i 0
  puts "\n### modified matrix for $scandir"
  foreach line $lines {
    if {$i == 6} {  ;# hack last entry of 3rd row of matrix
      # ddir-1: because first non-B0 should be offset by 1 fractional unit
      set delrepdel [expr ($ddir.0 - 1.0)/$ddircnt.0 * $repdel]
      set fixed [format "%e" [expr [lindex $line 3] + $delrepdel]]
     puts "[lindex $line 0]  [lindex $line 1]  [lindex $line 2]  $fixed"
     puts $id "[lindex $line 0]  [lindex $line 1]  [lindex $line 2]  $fixed"
    } else {
      puts "$line"
      puts $id "$line"
    }
    incr i
  }
  close $id
  incr ddir
}
