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

### ima2brik: marty sereno, version 0.1, 27 Jun 07

# help
if { [llength $argv] != 0 } {
  puts ""
  puts "use: \[cd into dir containing 14-field *.IMA files\]"
  puts "     ima2brik"
  puts ""
  puts "  convert set of Siemens DICOM files to AFNI BRIKs using to3d"
  puts "  N.B.: AFNI to3d must be on user's path"
  puts ""
  exit
}

# check for AFNI to3d
if [catch {exec which to3d} ] {
  puts ""
  puts "ima2brik: ### AFNI to3d not found on your \$path"
  puts "try adding something like this to your .cshrc:"
  puts ""
  puts "  # add to \$path (can be re-run without adding duplicates)"
  puts "  set addpathlist = ( /usr/local/afni/linux_xorg7 )"
  puts "  foreach dir ( \$addpathlist )"
  puts "    if (\"\$path\" !~ *\$dir*) set path = (\path \$dir)"
  puts "  end"
  puts "  unset addpathlist dir"
  puts ""
  exit
}

# init file check
set files [glob -nocomplain *.IMA]
set filecnt [llength $files]
if {$filecnt == 0} {puts "renum-ima: ### no files match *.IMA in [pwd]"; exit}
set fields [split [lindex $files 0] .]
set name [lindex $fields 0].[lindex $fields 1].[lindex $fields 2]
puts "\nrenum-ima: found $filecnt *.IMA files in [pwd]"
puts "           for $name"
puts "           to rename/convert\n"

# count/show files, allow escape
foreach infile $files {
  set fields [split $infile .]
  if { [llength $fields] != 14 } {
    puts "renum-ima: ### $infile doesn't have 14 fields ...quitting"
    exit
  }
  # catch already-converted with leading 0's (tcl interprets as octal/hex)
  set scan [string trimleft [lindex $fields 3] 0]
  set slicerep [string trimleft [lindex $fields 4] 0]
  if ![info exists scans($scan)] {set scans($scan) 1} else {incr scans($scan)}
  if { ![info exists slicereps($scan)] || $slicerep > $slicereps($scan) } {
    set slicereps($scan) $slicerep
  }
}
foreach scan [lsort -integer [array names scans]] {
  # find (possibly renumbered) first slice
  set loccnt 0; set ep2dcnt 0; set mpragecnt 0
  set first [glob -nocomplain *.*.*.$scan.1.*]
  if {$first == ""} { set first [glob *.*.*.[format "%02d" $scan].0001.*] }
  if {$first == ""} { puts "first file of scan $scan not found" }
  # scantype
  if { ![catch { exec grep -a "tProtocolName " $first } ret] } {
    #puts ret=$ret  ;# ret gets output or error msg
    set scantype unknown
    if [string match *localizer* $ret] { set scantype loc }
    if [string match *MPRAGE* $ret] { set scantype mprage }
    if [string match *ep2d* $ret] { set scantype ep2d }
    # TODO: others here
  } else { set scantype noprot }
  set scantypes($scan) $scantype
  # reps
  if { $scantype == "ep2d" } {
    set repss($scan) $scans($scan)
  } else { set repss($scan) 1 }
  # slices
  if { ![catch { exec grep -a "\\.nSize " $first } ret] } {
    set slicess($scan) [lindex $ret 2]
  } else { set slicess($scan) 0 }
  if { $scantype == "mprage" } { set slicess($scan) $scans($scan) }
  # TR
  if { ![catch { exec grep -a "alTR" $first } ret] } {
    set trs($scan) [expr [lindex $ret 2]/1000]
  } else { set trs($scan) "" }
  # print
  if { $scans($scan) != $slicereps($scan) } {
    puts "scan [format "%2d" $scan]: [format "%4d" $scans($scan)] files\
      --- $scantype (max image index = $slicereps($scan))"
    puts "num files doesn't match index found in filename  ...quitting"
    exit
  } else {
    puts "scan [format "%2d" $scan]: [format "%4d" $scans($scan)] files \
      seq=$scantype\t[format "%3d" $repss($scan)] reps \
      [format "%3d" $slicess($scan)] slices    TR=$trs($scan)"
  }
}
puts ""
puts "(1) Verify that files/reps/slices/TRs are correct"
puts "(2) <Ret> to rename/convert, ctrl-C to quit without doing anything"
read stdin 1

### check/rename
if ![file writable [lindex $files 0]] {
  puts "renum-ima: ### can't write/rename:\n[lindex $files 0]\n  ...quitting"
  exit
}
set i 0
foreach infile $files {
  set fields [split $infile .]
  set outfile [lindex $fields 0]
  foreach j { 1 2 } { set outfile $outfile.[lindex $fields $j] }
  # catch already-converted w/leading 0's (tcl interprets as octal/hex)
  set outfile $outfile.[format "%02d" [string trimleft [lindex $fields 3] 0]]
  set outfile $outfile.[format "%04d" [string trimleft [lindex $fields 4] 0]]
  foreach j {5 6 7 8 9 10 11 12 13} {set outfile $outfile.[lindex $fields $j]}
  if {"$infile" != "$outfile"} { exec mv $infile $outfile; incr i }
}
puts "renum-ima: checked $filecnt files: (renamed $i)\n"

### convert to BRIK
set outfilelist ""
foreach scan [lsort -integer [array names scans]] {
  set fscan [format "%02d" $scan]
  set scantype $scantypes($scan)
  set slices $slicess($scan)
  set reps $repss($scan)
  set tr $trs($scan)
  set outfile scan$fscan+orig.BRIK
  if [file exists $outfile] {
    puts "ima2brik: ### outfile $outfile exists  ...skipping this convert"
    continue
  }
  if { $scantype == "mprage" } {
    set cmd "to3d -prefix scan$fscan $name.$fscan.*.IMA"
    set tmpcmdfile /tmp/TmpCshConvert.[pid]
    set id [open $tmpcmdfile w 0777]
    puts $id "$cmd"
    close $id
    puts "####################################################################"
    puts "running: $cmd"
    puts "####################################################################"
    catch { exec csh $tmpcmdfile } ret
    puts $ret
    exec rm $tmpcmdfile
    lappend outfilelist $outfile
  }
  if { $scantype == "ep2d" } {
    set cmd "to3d -prefix scan$fscan -time:zt $slices $reps $tr alt+z \
             $name.$fscan.*.IMA"
    set tmpcmdfile /tmp/TmpCshConvert.[pid]
    set id [open $tmpcmdfile w 0777]
    puts $id "$cmd"
    close $id
    puts "####################################################################"
    puts "running: $cmd"
    puts "####################################################################"
    catch { exec csh $tmpcmdfile } ret
    puts $ret
    exec rm $tmpcmdfile
    lappend outfilelist $outfile
  }
}
puts "ima2brik outfiles generated:\n"
foreach outfile $outfilelist { puts "  $outfile" }
puts ""

### TODO: convert BRIK to ANALYZE

