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

### convertem
# vers 0.1, marty sereno, 6/10/02
# vers 0.2, marty sereno, 8/22/02
# TODO: handle sag, read more header

### constants
set beginscan 1
set endscan 25     ;# hack (TODO: stop after not finding a few)
set headsiz 6144
set 256x256size [expr $headsiz + (256*256*2)]   ;# 137216
set 512x512size [expr $headsiz + (512*512*2)]   ;# 530432
set skipTRs 2      ;# standard
set structmat 256  ;# hack (TODO: read)
set functmat 64    ;# hack (TODO: read)
set trms 4000      ;# default
set rawdir raw     ;# usu. a symbolic link
set tcnt 8         ;# mosaic tile count
set tsiz 64        ;# mosaic tile size
set blankbytes 16  ;# hack (TODO: should check 8192)
set odblank "000000 000000 000000 000000 000000 000000 000000 000000"
set binlist {thor to3d 2swap orig2cor}

### Linux: swap BRIK byteorder and HEAD parm for Linux/IRIX binary compat
proc swapbrikhead { stem } {
  set brik $stem.BRIK
  set head $stem.HEAD
  if { ![file exists $brik] || ![file exists $head] } { return }
  set tmphead TmpAfniHead.[pid]
  if { [catch {set idout [open $tmphead w 0644]}] } { return }
  exec 2swap -q $brik
  set idin [open $head r]
  set lines [split [read $idin] \n]
  close $idin
  set prev ignore
  foreach line $lines {
    if {[lindex $line 2] == "BYTEORDER_STRING"} {
      set prev foundtype
      puts $idout $line
      continue
    }
    if {"$prev" == "foundtype" && [lindex $line 0] == "count"} {
      set prev foundcount
      puts $idout $line
      continue
    }
    if {"$prev" == "foundcount"} {
      set prev ignore
      if {[lindex $line 0] == "'MSB_FIRST~"} { puts $idout "'LSB_FIRST~" }
      if {[lindex $line 0] == "'LSB_FIRST~"} { puts $idout "'MSB_FIRST~" }
      continue
    }
    puts $idout $line
  }
  close $idout   ;# TODO: extra CR appended
  exec mv -f $tmphead $head
}

### usage
proc helpquit { } {
  global rawdir binlist trms
  puts ""
  puts "usage: convertem \[-TR <msec>\] <dir1> \[<dir2> ...\]"
  puts ""
  puts "  De-mosaic, BRIK-ify Siemens Vision files into auto-numbered dirs"
  puts "  N.B.: scans are unpacked/named using original scan order"
  puts ""
  puts "  Requirements:"
  puts "    run in \$session/image"
  puts "    mosaics from single patient must in dir: \"$rawdir\" (link OK)"
  puts "    only works on 512x512 functional mosaics (17 or more slices)"
  puts "    requires single 1x1x1mm 256x256 align scan (any scan number OK)"
  puts "    needs these programs on \$path: $binlist"
  puts "    '-TR <msec>' option applies to scan/dir args that *follow* it"
  puts "    multiple '-TR <msec>' OK (default TR if no -TR option: $trms)"
  puts ""
  puts "  Strong suggestion:"
  puts "    use stimulus program name for dir names (repeats OK\!)"
  puts ""
  puts "  Example:"
  puts "    \[Make New Functional, e.g., 020425MS, from csurf\]"
puts "    cd \$FUNCTIONALS_DIR/020425MS/image                 # go to imagedir"
puts "    ln -s /rawdata/cdrom75/020425MS raw                # link raw data"
puts "    countem raw                                        # see what's there"
puts "    convertem -TR 3000 odr3 odr3 odr4 odr4 face mprage # name/num/convert"
  puts ""
  puts "      => generates following directories, BRIK's (all functs: TR=3000):"
  puts "           image/1-odr3/odr3-1+orig.BRIK"
  puts "           image/2-odr3/odr3-2+orig.BRIK"
  puts "           image/3-odr4/odr4-1+orig.BRIK"
  puts "           image/4-odr4/odr4-2+orig.BRIK"
  puts "           image/5-face/face-1+orig.BRIK"
  puts "           image/mprage/COR-"
  puts ""
  exit
}
if {$argc < 1} { helpquit }

### check bins
foreach bin $binlist {
  if [catch {exec which $bin}] {
    puts "convertem: ### program: $bin not on path (needs: $binlist)"
    puts "  \[UCSD: forgot newdefs\?\]"
    return
  }
}
puts "convertem: found $binlist"

### go to raw subdir
if { [file tail [pwd]] != "image" } {
  puts "convertem: ### must be run inside \"image\" subdir of a funct session"
  exit
}
if ![file exists $rawdir] {
  puts "convertem: ### \"$rawdir\" subdir missing (link OK)"
  exit
}
set imagedir [pwd]
cd $rawdir

### find patient num
set list [glob -nocomplain *.ima]
if { [llength $list] == 0 } {
  puts "convertem: ### no *.ima files found in $rawdir"
  exit
}
set uniqpatientlist {}
foreach file $list {
  set patientnum [string range $file 0 [expr [string first - $file] - 1]]
  if { [lsearch -exact $uniqpatientlist $patientnum] == -1 } {
    lappend uniqpatientlist $patientnum
  }
}
if { [llength $uniqpatientlist] > 1} {
  puts "convertem: ### found more than one patient: $uniqpatientlist"
  exit
}
set patientnum $uniqpatientlist

### count scans, sorta read headers, save parms in array
set scannum $beginscan
set badlist ""
set scancnt 0
set structcnt 0
puts ""
puts "  firstfile     type  slices  startimg  reps   thick  inplane  sliceplane"
puts "-------------------------------------------------------------------------"
while {$scannum <= $endscan} {
  set files [lsort [glob -nocomplain ${patientnum}-${scannum}-*.ima]]
  if ![llength $files] { incr scannum; continue }
  set 256x256cnt 0
  set 512x512cnt 0
  set min 1000000
  set max 0
  foreach file $files {
    set num \
      [string range [file rootname $file] [expr [string last - $file] + 1] end]
    if {$num > $max} { set max $num }
    if {$num < $min} { set min $num }
    set fsize [file size $file]
    if {$fsize == $256x256size} {
      incr 256x256cnt
    } elseif {$fsize == $512x512size} {
      incr 512x512cnt
    } else {
     puts "convertem: ### bad size: ${patientnum}-${scannum}-${num}.ima\t$fsize"
      exit
    }
  }
  ### sorta read header
  set sliceplane unknown
  set firstima $patientnum-$scannum-$min.ima
  #set header [exec head $firstima | strings]  ;# faster
  set header [exec cat $firstima | strings]
  foreach line [split $header \n] {
    if { [lindex $line 0] == "SL" }  { set thick [lindex $line 1] }
    if { [lindex $line 0] == "FoV" } { set fov   [lindex $line 1] }
    if { [lindex $line 0] == "Tra" } { set sliceplane horizontal }
    if { [lindex $line 0] == "Cor" } { set sliceplane coronal }
  }
  if {$sliceplane == "unknown"} {
    puts "convertem: ### slice plane not found in header ...assuming coronal"
    set sliceplane coronal
  }
  set xfov [lindex [split $fov *] 0]
  set yfov [lindex [split $fov *] 1]

  ### save, echo parms
  if {$256x256cnt} {
    incr scancnt
    incr structcnt
    set scans($scancnt,type)    align
    set scans($scancnt,scannum) $scannum
    set scans($scancnt,slices)  $256x256cnt
    set scans($scancnt,first)   $min
    set scans($scancnt,reps)    1
    set scans($scancnt,thick)   $thick
    set scans($scancnt,xfov)    $xfov
    #set scans($scancnt,inplane) [expr $xfov.0 / $structmat]
    set scans($scancnt,inplane) 1.0   ;# hack (TODO: read)
    set scans($scancnt,sliceplane)   $sliceplane
  }
  if {$512x512cnt} {
    incr scancnt
    set scans($scancnt,type)    funct
    set scans($scancnt,scannum) $scannum
    ### find end of slices by zeros in raw mosaic (only initial 16 bytes!)
    set slices 0
    for {set row 0} {$row < $tcnt} {incr row} {
      for {set col 0} {$col < $tcnt} {incr col} {
        set offset [expr $headsiz + ($row*$tsiz*$tsiz*$tcnt*2) + ($col*$tsiz*2)]
        set odout \
          [exec od -v -j $offset -N $blankbytes $patientnum-$scannum-$min.ima]
        set testblank [lrange $odout 1 [expr [llength $odout] - 2]]
        if {"$testblank" != "$odblank"} { incr slices }
      }
    }
    set scans($scancnt,slices)  $slices
    set scans($scancnt,first)   [expr $min + $skipTRs]
    set scans($scancnt,reps)    [expr ${512x512cnt} - $skipTRs] 
    set scans($scancnt,thick)   $thick
    set scans($scancnt,xfov)    $xfov
    set scans($scancnt,inplane) [expr $xfov.0 / $functmat]
    set scans($scancnt,sliceplane) $sliceplane
  }
  puts "$firstima\t$scans($scancnt,type)\
    \t$scans($scancnt,slices)\t$scans($scancnt,first)\
    \t$scans($scancnt,reps)\t$scans($scancnt,thick)\t$scans($scancnt,inplane)\
    \t$scans($scancnt,sliceplane)"
  incr scannum
}
puts "-------------------------------------------------------------------------"
puts ""
if {$structcnt > 1} {
  puts "convertem: ### found $structcnt 256x256 scans  ...quitting"
  puts "           ### N.B.: can't deal with 4x4 mosaics (256x256)"
  exit
}

### check cmdline dir count, save dir names in array
set arg 0
set i 1        ;# first scan is "1"
set dircnt 0
set currtr $trms
while {$arg < $argc} {
  if { [lindex $argv $arg] == "-TR"} {
    set currtr [lindex $argv [incr arg]]
    if { $arg == [expr $argc - 1] } {
      puts "convertem: ### no scans follow final -TR option ...ignored\n"
    }
    if [catch {set ival [expr int($currtr)]} ] {
      puts "convertem: ### bad -TR: $currtr"
      exit
    }
    incr arg
    continue
  }
  set scans($i,tr) $currtr
  set scans($i,dname) [lindex $argv $arg]
  incr i
  incr arg
  incr dircnt
}
if {$scancnt != $dircnt} {
  puts \
  "convertem: ### dir arg count ($dircnt) doesn't match scan count ($scancnt)"
  exit
}

### increment brikstemname number with repeated dir names
set i 1
while {$i <= $scancnt} {
  set samenamecnt 1
  set j 1
  while {$j < $i} {
    if {"$scans($i,dname)" == "$scans($j,dname)"} { incr samenamecnt }
    incr j
  }
  set scans($i,scanstem) $scans($i,dname)-$samenamecnt
  incr i
}

### back to imagedir, check writable, quit if scandirs already there
cd $imagedir
if ![file writable [pwd]] {
  puts "convertem: ### [pwd] not writable  ...quitting"
  exit
}
set i 1
while {$i <= $scancnt} {
  foreach dir "$i-$scans($i,dname) $scans($i,dname)" { ;# struct not numbered
    if [file exists $dir] {
      puts "convertem: ### dir $dir already exists: remove it (rm -r) to redo"
      exit
    }
  }
  incr i
}

### last chance
puts "Current plan:\n"
set i 1
while {$i <= $scancnt} {
  if {"$scans($i,type)" == "funct"} {
    set first $scans($i,first)
    set last [expr $first + $scans($i,reps)]
    puts " $rawdir/$patientnum-$scans($i,scannum)-\[$first-$last\]-.ima \t->\
           $i-$scans($i,dname)/$scans($i,scanstem)+orig.BRIK \
           (TR = $scans($i,tr))"
  }
  if {"$scans($i,type)" == "align"} {
    set first $scans($i,first)
    set last [expr $first + $scans($i,slices)]
    puts " $rawdir/$patientnum-$scans($i,scannum)-\[$first-$last\]-.ima \t->\
           $i-$scans($i,dname)/COR-"
  }
  incr i
}
puts "\n<Ret> to mkdirs/unpack, ctrl-C to quit"
gets stdin

### do functscans: mkdirs, de-mosaic, run to3d to get HEAD, rm identical
set i 1
while {$i <= $scancnt} {
  if {"$scans($i,type)" != "funct"} { incr i; continue }
  puts "\n####################################################################"
  cd $imagedir
  set cmd "mkdir $i-$scans($i,dname)"
  puts "$cmd"
  puts [eval exec $cmd]

  # IRIX thor -clearfirst => kills IRIX to3d (test Linux)
  # Linux thor -noswap => same binary file as IRIX, but then to3d needs -2swap
  set cmd "thor $rawdir/$patientnum $scans($i,first) $scans($i,reps) \
    $i-$scans($i,dname)/$scans($i,scanstem) -no_int -wong"
  puts "\n$cmd"
  catch { eval exec $cmd } output    ;# (bad code on normal exit?)
  puts $output

  ### run special cases of to3d to make HEAD
  cd $imagedir/$i-$scans($i,dname)  ;# to3d: infile composite path OK, stem=>no
  set inbrik $scans($i,scanstem).brik
  set zt [expr $scans($i,slices) * $scans($i,reps)]
  set halfx [expr $functmat * $scans($i,inplane)/2.0]  ;# hack (TODO: read)
  set halfy [expr $functmat * $scans($i,inplane)/2.0]  ;# hack (TODO: read)
  set halfz [expr $scans($i,slices) * $scans($i,thick)/2.0] ;# hack (TODO: read)
  set skipoutliers "-skip_outliers"
  #set skipoutliers ""    ;# TODO: allow on both (on linux 2.31, not IRIX 2.29)
  if {$scans($i,sliceplane) == "coronal"} {
    set interleave alt-z
    set cmd "to3d -prefix $scans($i,scanstem) -session [pwd] -epan \
      $skipoutliers \
      -time:zt $scans($i,slices) $scans($i,reps) $scans($i,tr) $interleave \
      -xFOV ${halfx}R-L \
      -yFOV ${halfy}S-I \
      -zFOV ${halfz}P-A \
      3D:0:0:${functmat}:${functmat}:${zt}:${inbrik}"
  }
  if {$scans($i,sliceplane) == "horizontal"} {
    set interleave alt-z
    set cmd "to3d -prefix $scans($i,scanstem) -session [pwd] -epan \
      $skipoutliers \
      -time:zt $scans($i,slices) $scans($i,reps) $scans($i,tr) $interleave \
      -xFOV ${halfx}R-L \
      -yFOV ${halfy}A-P \
      -zFOV ${halfz}S-I \
      3D:0:0:${functmat}:${functmat}:${zt}:${inbrik}"
  }
  puts "\n$cmd"
  puts [eval exec $cmd]
  exec rm $scans($i,scanstem).head

  ### swap bytes back for IRIX/Linux binary compat
  if { [exec uname] == "Linux" } {
    puts "\nBinary compat: swap bytes in BRIK, fix byte order parm in HEAD"
    swapbrikhead $scans($i,scanstem)+orig
  }

  ### delete identical brik (swapped in case of Linux!)
  exec rm -f $inbrik
  puts "\nIdentical brik ($inbrik) removed"
  #set outbrik $scans($i,scanstem)+orig.BRIK
  #if { [exec diff $inbrik $outbrik | wc -l] == 0 && \
  #     [file exists $outbrik] } { 
  #  exec rm -f $inbrik
  #  puts "\nIdentical brik ($inbrik) removed"
  #}

  incr i
}

### do alignscan (only one): mkdir, convert to COR
set i 1
while {$i <= $scancnt} {
  if {"$scans($i,type)" != "align"} { incr i; continue }
  puts "\n####################################################################"
  cd $imagedir
  set cmd "mkdir $scans($i,dname)"
  puts "$cmd"
  puts [eval exec $cmd]

  # orig2cor output already binary-compat
  cd $imagedir/$scans($i,dname)
  set cmd "orig2cor \
    Siemens local ../$rawdir/$patientnum-$scans($i,scannum)-%d.ima \
    $scans($i,first) $scans($i,slices)"
  puts "\n$cmd"
  puts [eval exec $cmd]


  incr i
}
puts "\n####################################################################"
puts "done unpacking"

