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

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

# loc
#tSequenceFileName                        = ""%SiemensSeq%\gre""
# t1se
#tSequenceFileName                        = ""%SiemensSeq%\se""
# fmap
#tSequenceFileName                        = ""%SiemensSeq%\gre_field_mapping""
# PD SE
#tSequenceFileName                        = ""%SiemensSeq%\tse""
# EPI
#tSequenceFileName                        = ""%SiemensSeq%\ep2d_pace""
# MPRAGE
#tSequenceFileName                        = ""%SiemensSeq%\tfl""

set afnidir zzAFNI
set analyzedir zzANALYZE
set niftidir zzNIFTI
set logfilename zzNOTES

### strip double quotes and backslash
proc stripqb { str } {
  set i 0
  set len [string length $str]
  set newstr ""
  while {$i < $len} {
    set c [string index $str $i]
    if {$c != "\"" && $c != "\\"} { set newstr "${newstr}${c}" }
    incr i
  }
  return $newstr
}

### help
if { [llength $argv] != 1 } {
  puts ""
  puts "use: \[cd into dir containing 14-field Siemens DICOM *.IMA files\]"
  puts "     ima2brik -afni"
  puts "     ima2brik -analyze"
  puts "     ima2brik -nifti"
  puts ""
  puts "  Converts set of Siemens DICOM files to AFNI (or other) BRIKs:"
  puts "    --output left in subdirs ($afnidir, $analyzedir, $niftidir)"
  puts "    --AFNI programs to3d/3dANFItoANALYZE/3dAFNItoNIFTI must be on path"
  puts "    --analzye and nifti conversions first generate AFNI BRIKs"
  puts ""
  exit
}

### opts
set opt [lindex $argv 0]
if { $opt == "-afni" } {
  set outfiletype afni
} elseif { $opt == "-analyze" } {
  set outfiletype analyze
} elseif { $opt == "-nifti" } {
  set outfiletype nifti
} else { puts "ima2brik: ### bad option: $arg"; exit }

### check for AFNI binaries
foreach bin { to3d 3dAFNItoANALYZE 3dAFNItoNIFTI } {
  catch { exec which $bin } ret  ;# diff ret/errs on Linux/Mac "which"
  if [string match "*no $bin*" $ret] {
    puts ""
    puts "ima2brik: ### AFNI $bin 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 dicomdir [pwd]
set logfile $dicomdir/$logfilename
set files [glob -nocomplain *.IMA]
set filecnt [llength $files]
if {$filecnt == 0} {
  puts "ima2brik: ### no files match *.IMA in $dicomdir"
  exit
}
set fields [split [lindex $files 0] .]
set name [lindex $fields 0].[lindex $fields 1].[lindex $fields 2]
puts "\nima2brik: found $filecnt *.IMA files in $dicomdir"
puts "          for $name"
puts "          to rename/convert\n"

### count/type/display 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
  }
}
### log
if [file writable ..] {
  if { ![file exists $logfile] } { 
    set idnotes [open $logfile w 0666]
  } elseif { [file exists $logfile] && [file writable $logfile] } { 
    set idnotes [open $logfile w 0666]
  } else {
    set idnotes [open /dev/null w 0666]
  }
} else {
   set idnotes [open /dev/null w 0666]
}

### foreach first file, read some info from Siemens extra ascii info
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 -nocomplain *.*.*.[format "%02d" $scan].0001.*]
  }
  if {$first == ""} { puts "ima2brik: ### first file of scan $scan not found" }
  ## seq name 
  set patt "tSequenceFileName                        ="
  if { ![catch { exec grep -a "$patt" $first } ret] } {
    #puts ret=$ret
    set seqname [lindex [stripqb $ret] 2]
    if [string match *%SiemensSeq%* $seqname] {
      set seqname [string range $seqname 12 end]
    }
    if [string match ep2d* $seqname] { set seqname ep2d }
  } else { set seqname noseqname }
  set seqnames($scan) $seqname
  ## prot name (can be changed by user)
  set patt "tProtocolName                            ="
  if { ![catch { exec grep -a "$patt" $first } ret] } {
    #puts ret=$ret
    set protname [lindex [stripqb $ret] 2]
  } else { set protname noprotname }
  set protnames($scan) $protname    ;# not now printed, hack to find localizer
  ## seq dicom name
  if { ![catch { exec strings $first | grep ^\* } ret] } {
    set seqdname [lindex [stripqb $ret] 0]
    set seqdnames($scan) $seqdname  ;# not now printed
  }
  ## reps
  if { $seqname == "ep2d" } {
    set repss($scan) $scans($scan)
  } else { set repss($scan) 1 }
  ## slices (skip first binary match to nSize)
  set patt "nSize             ="
  if { ![catch { exec grep -a "$patt" $first } ret] } {
    #puts ret=$ret
    set slicess($scan) [lindex [stripqb $ret] 2]
  } else { set slicess($scan) 0 } ;# failed
  if {$seqname != "ep2d"} {  ;# epi's have one TR per 'slice'
     set slicess($scan) $scans($scan)
  }
  ## TR (skip first bin match) 3 backslashes: pass 1 to grep, block tcl bracket
  set patt "alTR\\\[0\\\]                                  ="
  if { ![catch { exec grep -a "$patt" $first } ret] } {
    #puts ret=$ret
    set trs($scan) [expr [lindex $ret 2]/1000]
  } else { set trs($scan) "" }
  ## moco flag
  set moco($scan) [string match *MoCoSeries* [exec strings $first]]
  # print
  if { $scans($scan) != $slicereps($scan) } {
    puts "scan [format "%2d" $scan]: [format "%4d" $scans($scan)] files\
      --- $seqname (max image index = $slicereps($scan))"
    puts "ima2brik: ### num files doesn't match index in filename  ...quitting"
    exit
  } else {
    if {$moco($scan)} { set mocotag "(MoCoSeries)" } else { set mocotag "" }
    set line "scan [format "%2d" $scan]: [format "%4d" $scans($scan)] files \
      seq=$seqname\t[format "%3d" $repss($scan)] reps \
      [format "%3d" $slicess($scan)] slices   TR=$trs($scan) $mocotag"
    puts "$line"
    puts $idnotes "$line"
  }
}
puts ""
puts $idnotes ""
puts "(1) Verify that files/reps/slices/TRs are correct"
puts "(2) one of the following:"
puts "     -- ctrl-D to convert all"
puts "     -- space-separated subset of scan nums to convert, <Ret>, ctrl-D"
puts "     -- ctrl-C to quit without doing anything"
set resp [read stdin]
if [llength $resp] { set selectedscans $resp }
puts $resp

### check/rename
if ![file writable [lindex $files 0]] {
  puts "ima2brik: ### 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 "ima2brik: checked $filecnt files: (renamed $i)\n"

### convert IMA sets to BRIKs (do always: -analyze and -nifti imply -afni)
set outfilelist ""
foreach scan [lsort -integer [array names scans]] {
  if {[info exists selectedscans] && ![string match *$scan* $selectedscans]} {
    puts "\n############## skipping scan $scan ##############\n"
    puts $idnotes "\n############## skipping scan $scan ##############\n"
    continue
  }
  # setup
  set fscan [format "%02d" $scan]
  set seqname $seqnames($scan)
  set protname $protnames($scan)
  set seqdname $seqdnames($scan)
  set slices $slicess($scan)
  set reps $repss($scan)
  set tr $trs($scan)
  if { $moco($scan) } { set mocotype -moco } else { set mocotype "" }
  set outfile scan${fscan}+orig.BRIK
  if { [file exists $afnidir] && [file exists $afnidir/$outfile] } {
    puts "ima2brik: ### outfile $afnidir/$outfile exists  ...skipping this one"
    set convertedscans($scan) $scans($scan)
    continue
  }
  if [file exists $outfile] {
    puts "ima2brik: ### outfile $outfile exists  ...skipping this one"
    set convertedscans($scan) $scans($scan)
    continue
  }
  ## convert to BRIK
  if { $protname == "localizer" } {  ;# skip (it's a gre)
    # skip
  } elseif { $seqname == "tfl" || $seqname == "tse" ||  $seqname == "se" || \
             $seqname == "gre"} {  ;# 3D (incl. gre)
    set cmd "to3d -prefix scan${fscan} $name.$fscan.*.IMA"
    set tmpcmdfile /tmp/TmpCshConvert.[pid]
    set idcsh [open $tmpcmdfile w 0777]
    puts $idcsh "$cmd"
    close $idcsh
    puts "####################################################################"
    puts "running: $cmd"
    puts "####################################################################"
    puts "\nsequence dicom name = $seqdname"
    puts "scanner protocol name = $protname\n"
    puts $idnotes "###########################################################"
    puts $idnotes "running: $cmd"
    puts $idnotes "###########################################################"
    puts $idnotes "\nsequence dicom name = $seqdname"
    puts $idnotes "scanner protocol name = $protname\n"
    catch { exec csh $tmpcmdfile } ret
    puts $ret
    puts $idnotes $ret
    exec rm $tmpcmdfile
    lappend outfilelist $outfile
    set convertedscans($scan) $scans($scan)
  } elseif { $seqname == "ep2d" } {  ;# funct scans
     set cmd "to3d -prefix scan${fscan} -time:zt $slices $reps $tr \
               alt+z $name.$fscan.*.IMA"
    set tmpcmdfile /tmp/TmpCshConvert.[pid]
    set idcsh [open $tmpcmdfile w 0777]
    puts $idcsh "$cmd"
    close $idcsh
    puts "####################################################################"
    puts "running: $cmd"
    puts "####################################################################"
    puts "\nsequence dicom name = $seqdname"
    puts "scanner protocol name = $protname\n"
    puts $idnotes "###########################################################"
    puts $idnotes "running: $cmd"
    puts $idnotes "###########################################################"
    puts $idnotes "\nsequence dicom name = $seqdname"
    puts $idnotes "scanner protocol name = $protname\n"
    catch { exec csh $tmpcmdfile } ret
    puts $ret
    puts $idnotes $ret
    exec rm $tmpcmdfile
    lappend outfilelist $outfile
    set convertedscans($scan) $scans($scan)
  }
  # TODO: maybe other seqnames w/different layout (DTi)
}
# move BRIKs into subdir if possible
if ![file writable ..] {
  puts "ima2brik: ### can't create directory $afnidir in $dicomdir"
  puts "          ### AFNI BRIKs left in $dicomdir"
}
if ![file exists $afnidir] { exec mkdir $afnidir } 
# report
puts "ima2brik: outfiles generated:\n"
puts $idnotes "ima2brik: outfiles generated:\n"
foreach outfile $outfilelist {
  if [file exists $outfile] { 
    puts "  $outfile"
    puts $idnotes "  $outfile"
    exec mv $outfile $afnidir
    exec mv [file rootname $outfile].HEAD $afnidir
  }
}
if { [file exists $afnidir] && [llength $outfilelist] } {
  puts "\nBRIKs moved into $afnidir"
  puts $idnotes "\nBRIKs moved into $afnidir"
}
puts ""; puts $idnotes ""
close $idnotes

### maybe convert BRIKs to ANALYZE
if { $outfiletype == "analyze" } {
  if ![file exists $analyzedir] { exec mkdir $analyzedir } 
  cd $dicomdir/$analyzedir
  foreach scan [lsort -integer [array names convertedscans]] {
   if {[info exists selectedscans] && ![string match *$scan* $selectedscans]} {
      puts "\n############## skipping scan $scan ##############\n"
      continue
    }
    set fscan [format "%02d" $scan]
    set seqname $seqnames($scan)
    if { $moco($scan) } { set mocotype -moco } else { set mocotype "" }
    set infile ../$afnidir/scan${fscan}+orig.BRIK
    set outfile scan${fscan}
    # TOOD: generate outfile name, check if it already exists, skip
    set cmd "3dAFNItoANALYZE -4D $outfile $infile"
    exec echo ##################################################### >> $logfile
    exec echo $cmd >> $logfile
    exec echo ##################################################### >> $logfile
    catch { eval exec $cmd } ret
    puts $ret
    exec echo "$ret\n" >> $logfile
  }
  # TODO: puts outfile names
}

### maybe convert BRIKs to NIFTI
if { $outfiletype == "nifti" } {
  if ![file exists $niftidir] { exec mkdir $niftidir } 
  cd $dicomdir/$niftidir
  foreach scan [lsort -integer [array names convertedscans]] {
   if {[info exists selectedscans] && ![string match *$scan* $selectedscans]} {
      puts "\n############## skipping scan $scan ##############\n"
      continue
    }
    set fscan [format "%02d" $scan]
    set seqname $seqnames($scan)
    if { $moco($scan) } { set mocotype -moco } else { set mocotype "" }
    set infile ../$afnidir/scan${fscan}+orig.BRIK
    # TODO: generate outfile name, check if it already exists, skip
    set cmd "3dAFNItoNIFTI $infile"
    exec echo ##################################################### >> $logfile
    exec echo $cmd >> $logfile
    exec echo ##################################################### >> $logfile
    catch { eval exec $cmd } ret
    puts $ret
    exec echo "$ret\n" >> $logfile
  }
  # TODO: puts outfile names
}

