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

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

set afnidir zzAFNI
set analyzedir zzANALYZE
set niftidir zzNIFTI
set logfilename zzNOTES
set typenames 0      ;# insert type infix: e.g., scan03-ep2d-moco+orig.BRIK

### 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
  }
}
if [file writable ..] {
  set idnotes [open $logfile w 0666]
} else {
  set idnotes [open /dev/null w 0666]
}
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" }
  # scantype (skip first binary match to tProtocolName)
  # e.g., /usr1/raw/070620FD/FRED.MR.UCL_BBK_TONOTOPYPROTOCOLMAY07001.03.0001.*
  set patt "tProtocolName                            ="
  if { ![catch { exec grep -a "$patt" $first } ret] } {
    #puts ret=$ret
    set scantype ###
    if [string match *localizer* $ret] { set scantype loc }
    if [string match *MPRAGE* $ret] { set scantype mprage }
    if [string match *ep2d* $ret] { set scantype ep2d }
    if [string match *t1+AF8-se+AF8-tra* $ret] { set scantype t1se }
    if [string match *gre+AF8-field+AF8-mapping* $ret] { set scantype fmap }
    if [string match *t2+AF8-tse+AF8-tra+AF8-512+AF8-pat2* $ret] {
      set scantype t2tse
    }
    if [string match *AAScout* $ret] { set scantype aasco }
    # 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 (skip first binary match to nSize)
  # e.g., /usr1/raw/070619JD/JOE.MR.UCL_BBK_TONOPROTOCOL-MAY23.14.00101.*
  set patt "\\.nSize             ="
  if { ![catch { exec grep -a "nSize             =" $first } ret] } {
    #puts ret=$ret
    set slicess($scan) [lindex $ret 2]
  } else { set slicess($scan) 0 }
  if {$scantype == "mprage" || $scantype == "t1se" || $scantype == "fmap" || \
      $scantype == "t2tse" || $scantype == "aasco" } {
     set slicess($scan) $scans($scan)
  }
  # TR (skip first bin match) 3 backslashes: pass 1 to grep, block tcl bracket
  # e.g., /usr1/raw/070620FD/FRED.MR.UCL_BBK_TONOTOPYPROTOCOLMAY07001.03.0001.*
  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\
      --- $scantype (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=$scantype\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 scantype $scantypes($scan)
  set slices $slicess($scan)
  set reps $repss($scan)
  set tr $trs($scan)
  if { $moco($scan) } { set mocotype -moco } else { set mocotype "" }
  if { $typenames } { set infix -${scantype}${mocotype} } else { set infix "" }
  set outfile scan${fscan}${infix}+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
  }
  # localizer
  if { $scantype == "loc" } {
    # skip
  }
  # struct scans
  if { $scantype == "mprage" } {
    if { $typenames } { set infix -${scantype}${mocotype} } else {set infix ""}
    set cmd "to3d -prefix scan${fscan}${infix} $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 $idnotes "###########################################################"
    puts $idnotes "running: $cmd"
    puts $idnotes "###########################################################"
    catch { exec csh $tmpcmdfile } ret
    puts $ret
    puts $idnotes $ret
    exec rm $tmpcmdfile
    lappend outfilelist $outfile
    set convertedscans($scan) $scans($scan)
  }
  # funct scans
  if { $scantype == "ep2d" } {
    if { $typenames } { set infix -${scantype}${mocotype} } else {set infix ""}
     set cmd "to3d -prefix scan${fscan}${infix} -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 $idnotes "###########################################################"
    puts $idnotes "running: $cmd"
    puts $idnotes "###########################################################"
    catch { exec csh $tmpcmdfile } ret
    puts $ret
    puts $idnotes $ret
    exec rm $tmpcmdfile
    lappend outfilelist $outfile
    set convertedscans($scan) $scans($scan)
  }
  # TODO: maybe other scantypes 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 {
  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 scantype $scantypes($scan)
    if { $moco($scan) } { set mocotype -moco } else { set mocotype "" }
    if { $typenames } { set infix -${scantype}${mocotype} } else {set infix ""}
    set infile ../$afnidir/scan${fscan}${infix}+orig.BRIK
    set outfile scan${fscan}${infix}
    # 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 scantype $scantypes($scan)
    if { $moco($scan) } { set mocotype -moco } else { set mocotype "" }
    if { $typenames } { set infix -${scantype}${mocotype} } else {set infix ""}
    set infile ../$afnidir/scan${fscan}${infix}+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
}

