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

### ima2brik: marty sereno
#------------------------------------------------------------------------------
# 01 Jun 07: 0.1a -- version 0.1
# 18 Dec 07: 0.1d -- pipe grep nSize to grep asGroup (skip rare binary match)
# 02 Jan 08: 0.1e -- stripqb also strips curly braces
# 03 Jan 08: 0.1f -- option -list now writes zzNOTES (for firewire diskbak)
# 21 Jan 08: 0.1g -- move aside zzNOTES in case someone wrote one before
# 30 Jan 08: 0.1h -- print out TE too
# 31 Jan 08: 0.2a -- parse/renum already-renum'd Trio FIL, rec FIL sequences
# 13 Feb 08: 0.2b -- fix TR-finding bug, timepattern now assumes interleaved
# 18 Feb 08: 0.2c -- actual timepattern now recognized and AFNI-converted
# 24 Feb 08: 0.2d -- convert selected scans bug fixed
# 17 Mar 08: 0.2e -- recognize ralf_mdeft_sonata as mdeft
# 18 Mar 08: 0.2f -- better seqname code, user note if unrecognized seqname
# 29 Apr 08: 0.2g -- alTR bin match avoided => make better ASCII extractor
# TODO: make perl (!sed) ### ASCCONV BEGIN ### => ### ASCCONV END ###" extract
#------------------------------------------------------------------------------
set vers 0.2f

### filename examples
#standard BUCNI export
#  KANAI_RYOTA.MR.UCL_BBK_MARTY.15.0019.2008.01.07.15.05.57.171875.41235028.IMA
#  name1  name2  name3  scan#  slice#  dat1  dat2  dat3  ??  ??  ??  ??  ?? IMA
#renamed/exported to Linux from FIL Trio
#  PITCHER_David_1_3_249_1_249.ima
#  name1  name2  ??  scan#  vol#  ??  slice#|vol#  ima

### sequence names ($seqnames)
### TODO: add seqnames: 3DFSE, non-PACE epi, allegra mdeft
# 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""
# MEPI
#tSequenceFileName                        = ""%CustomerSeq%\nw_mepi""
# MDEFT Trio
#tSequenceFileName                        = ""%CustomerSeq%\nw_mdeft_trio""
# MDEFT Sonata
#tSequenceFileName                        = "%CustomerSeq%\ralf_mdeft_sonata"
### ADD NEW here: grep -a "tSequenceFileName                        =" <dicom>
### update ADD NEW elseif's below

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

### strip double quotes and backslash and curly braces
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 != "\\" && $c != "\{" && $c != "\}" } {
      set newstr "${newstr}${c}"
    }
    incr i
  }
  return $newstr
}

### help
if { [llength $argv] < 1 } {
  puts ""
  puts "use: \[cd into dir containing one set of Siemens DICOM files\]"
  puts "     ima2brik -list"
  puts "     ima2brik -afni"
  puts "     ima2brik -analyze"
  puts "     ima2brik -nifti"
  puts ""
  puts "  Checks for:"
  puts "    Siemens 14-field export-to-offline files, *.IMA (-offline)"
  puts "    FIL-renamed 8-field Trio exports to Linux, *.ima (-filtrio)"
  puts ""
  puts "  Converts Siemens DICOM file set to AFNI (or other) BRIKs:"
  puts "    --re-numbers DICOM files into default unix sorting order"
  puts "    --output briks left in subdirs ($afnidir, $analyzedir, $niftidir)"
  puts "    --AFNI programs to3d/3dANFItoANALYZE/3dAFNItoNIFTI must be on path"
  puts "    --analyze and nifti conversions first generate AFNI BRIKs"
  puts "                                                            vers=$vers"
  exit
}

### opts
set outfiletype none    ;# none,afni,analyze,nifti
set filenametype none   ;# none,offline,filtrio
set argv2 {}
for {set i 0} {$i < $argc} {incr i} {
  set arg [lindex $argv $i]
  if ![string match -* $arg] {
    lappend argv2 $arg
  } else {
    if { $arg == "-afni" } {
      set outfiletype afni
    } elseif { $arg == "-analyze" } {
      set outfiletype analyze
    } elseif { $arg == "-nifti" } {
      set outfiletype nifti
    } elseif { $arg == "-list" } {
      set outfiletype list
    } elseif { $arg == "-filtrio" } {
      set filenametype filtrio
    } elseif { $arg == "-offline" } {
      set filenametype offline
    } else { puts "ima2brik: ### bad option: $arg"; exit }
  }
}
# argv2 has (currently unused) non-option args
if { $outfiletype == "none" } {
  puts "ima2brik: ### must specify -list, -afni, -analyze, or -nifti"
  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 ""
    if {$outfiletype != "list"} { exit } else { break }
  }
}

### ready 
set dicomdir [pwd]
set logfile $dicomdir/$logfilename

### get filename list (if filenametype not set, try *.IMA first, then *.ima)
if { $filenametype == "none" }    { set imsuff IMA }
if { $filenametype == "offline" } { set imsuff IMA }
if { $filenametype == "filtrio" } { set imsuff ima }
set files [glob -nocomplain *.$imsuff]
set filecnt [llength $files]
if {$filenametype == "none"} {
  if {$filecnt == 0} {
    set imsuff ima
    set files [glob -nocomplain *.$imsuff]
    set filecnt [llength $files]
    if {$filecnt == 0} {
      puts "ima2brik: ### no files match *.ima or *.IMA in $dicomdir"
      exit
    } else {
      set filenametype filtrio
    }
  } else {
    set filenametype offline
  }
}
if {$filecnt == 0} {
  puts "ima2brik: ### no files match *.$imsuff in $dicomdir"
  exit
}

### get subject name from first file
if { $filenametype == "offline" } {
  set fields [split [lindex $files 0] .]
  set name [lindex $fields 0].[lindex $fields 1].[lindex $fields 2]
}
if { $filenametype == "filtrio" } {
  set fields [split [file rootname [lindex $files 0]] _]
  set name [lindex $fields 0]_[lindex $fields 1]_[lindex $fields 2]
}
puts "\nima2brik: found $filecnt *.$imsuff files"
puts "          in $dicomdir"
puts "          for $name"
puts "          to rename/convert\n"

### count/type/display files, allow escape
foreach infile $files {
  if { $filenametype == "offline" } {
    set fields [split $infile .]
    if { [llength $fields] != 14 } {
      puts \
"ima2brik: ### $infile doesn't have 14 dot-separated 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 { $filenametype == "filtrio" } {
    set fields [split [file rootname $infile] _]
    if { [llength $fields] != 7 } {  ;# one less because .ima stripped
      puts \
"ima2brik: ### $infile doesn't have 7 underscore-separated 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 6] 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 owned .] && $outfiletype != "none"} {  ;# file writable . .. fails
  if { ![file exists $logfile] } { 
    set idnotes [open $logfile w 0666]
  } elseif { [file exists $logfile] && [file writable $logfile] } { 
    if ![file exists $logfile~] {
      exec mv $logfile $logfile~
    } else {
      if [file writable $logfile~] { exec mv $logfile $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
  if { $filenametype == "offline" } {
    set first [glob -nocomplain ${name}.${scan}.1.*.$imsuff]
  }
  if { $filenametype == "filtrio" } {
    set first [glob -nocomplain ${name}_${scan}_1_*_1.$imsuff]
  }
  if {$first == ""} {
    set fscan [format "%02d" $scan]
    if { $filenametype == "offline" } {
      set first [glob -nocomplain ${name}.${fscan}.0001.*.$imsuff]
    }
    if { $filenametype == "filtrio" } {
      set first [glob -nocomplain ${name}_${fscan}_0001_*_0001.$imsuff]
    }
  }
  if {$first == ""} { puts "ima2brik: ### first file of scan $scan not found" }
  set firstcnt [llength $first]
  if { $firstcnt != 1 } {
    puts ""
    puts "ima2brik: ### found multiple ($firstcnt) first files for scan $scan"
    foreach firstfile $first { puts "  $firstfile" }
    puts \
"ima2brik: ### exp offline to new dir (Leonardo), re-transfer to new dir (here)"
    puts \
"ima2brik: ### multiple sessions may have accidentally been exported-to-offline"
    puts ""
    exit
  }
  ## 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]
    } elseif [string match *%CustomerSeq%* $seqname] {
      set seqname [string range $seqname 13 end]
    }
    ### ADD NEW: add new recognized seqnames here (shorten some to 6 for table)
    set recseqflag 1
    if [string match gre $seqname] {
      set seqname gre
    } elseif [string match se $seqname] {
      set seqname se
    } elseif [string match tse $seqname] {
      set seqname tse
    } elseif [string match gre_field_mapping $seqname] {
      set seqname fmap
    } elseif [string match AAScout $seqname] {
      set seqname AAscou
    } elseif [string match tfl $seqname] {
      set seqname mprage                          ;# could be non-prep
    } elseif [string match nw_mdeft_trio $seqname] {
      set seqname mdeft
    } elseif [string match ralf_mdeft_sonata $seqname] {
      set seqname mdeft
    } elseif [string match tse_vfl $seqname] {
      set seqname tseSP
    } elseif [string match ep2d_pace $seqname] {
      set seqname ep2d
    } elseif [string match ep2d* $seqname] {      ;# TODO: get non-pace name
      set seqname ep2d
    } elseif [string match nw_mepi $seqname] {
      set seqname mepi
    } else { set recseqflag 0 }                   ;# unrec seqname unchanged
    # TODO: dti
    ### end ADD NEW
  } else { set seqname noseq; set recseqflag 0 }
  set seqnames($scan) $seqname
  set recseqflags($scan) $recseqflag
  ## 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] } {
    #puts ret=$ret
    set seqdname [lindex [stripqb $ret] 0]
  } else { set seqdname none }  ;# this string is not found in FIL sequences
  set seqdnames($scan) $seqdname  ;# not now printed
  ## reps (for epi, one time point per file)
  if { $seqname == "ep2d" || $seqname == "mepi" } {
    set repss($scan) $scans($scan)
  } else { set repss($scan) 1 }
  ## slices (skip first binary match to nSize)
  if { ![catch { exec grep -a "nSize             =" $first \
                 | grep -a asGroup } ret] } {
    #puts ret=$ret
    set slicess($scan) [lindex $ret 2]
  } else { set slicess($scan) 0 } ;# failed
  if {$seqname != "ep2d" && $seqname != "mepi"} {  ;# epi's have 1 TR/'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 \
                 | grep -a "                                  = "} ret] } {
    #puts ret=$ret
    #set tr [expr [lindex $ret 2]/1000]    ;# full line sometimes in binary
    set tr [expr [lindex $ret end]/1000]  ;# avoid first binary match
    # N.B.: nw_mepi TR is one slice, not one volume
    if {$seqname == "mepi"} { set tr [expr $tr * $slicess($scan)] }
    set trs($scan) $tr
  } else { set trs($scan) "" }
  ## TE (skip first bin match) 3 backslashes: pass 1 to grep, block tcl bracket
  set patt "alTE\\\[0\\\]                                  ="
  if { ![catch { exec grep -a "$patt" $first } ret] } {
    #puts ret=$ret
    set tes($scan) [expr [lindex $ret 2]/1000.0]
  } else { set tes($scan) "" }
  ## slice order (from Doug Greve)
  set patt "sSliceArray.ucMode                       ="
  if { ![catch { exec grep -a "$patt" $first } ret] } {
    #puts ret=$ret
    set sordflag [lindex $ret 2]
    set sord unknown
    if {"$sordflag" == "0x1"} { set sord asc } ;# ascending (inf up)
    if {"$sordflag" == "0x2"} { set sord des } ;# descending (sup down)
    if {"$sordflag" == "0x4"} { set sord int } ;# interleaved (inf up, o=1,e=2)
    set sords($scan) $sord
  } else { set sords($scan) unknown }
  ## moco flag
  set moco($scan) [string match *MoCoSeries* [exec strings $first]]
  ## print
  if { $scans($scan) != $slicereps($scan) } {  ;# error exit
    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"
    puts "ima2brik: (transfer in progress not finished?)"
    exit
  } else { ;# print line of table
    if {$moco($scan)} { set mocotag "MoCo" } 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=[format "%4d" $trs($scan)]\
      TE=$tes($scan) OR=$sords($scan) $mocotag"
    puts "$line"
    puts $idnotes "$line"
  }
} ;# foreach scan
## note if some unrecognized
set unrecs 0
foreach scan [lsort -integer [array names scans]] {
  if { $recseqflags($scan) == 0 } { set unrecs 1 }
}
if {$unrecs} {
  puts ""
  puts "ima2brik: ### unrecognized scantype(s)  ...leave note for Marty"
  foreach scan [lsort -integer [array names scans]] {
    if {$recseqflags($scan) == 0} {
      puts "  scan [format "%2d" $scan]: $seqnames($scan)"
    }
  }
}
puts ""
if { $outfiletype == "list" } { close $idnotes; exit }
## ready to convert, wait for user input
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 {
  if { $filenametype == "offline" } {
    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 }
  }
  if { $filenametype == "filtrio" } {
    set fields [split [file rootname $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]]
   set outfile ${outfile}_[lindex $fields 5]
   set outfile ${outfile}_[format "%04d" [string trimleft [lindex $fields 6] 0]]
   set outfile $outfile.ima   ;# tack back on
    if {"$infile" != "$outfile"} { exec mv $infile $outfile; incr i }
  }
}
if { $filenametype == "offline" } { set usertype "14-field offline" }
if { $filenametype == "filtrio" } { set usertype "8-field filtrio" }
puts "ima2brik: checked $filecnt $usertype 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] {
    set found 0
    foreach s $selectedscans { if [string match $s $scan] { set found 1 } }
    if {!$found} {
      puts "\n############## skipping scan $scan ##############\n"
      puts $idnotes "\n############## skipping scan $scan ##############\n"
      continue
    }
  }
  ## setup vars
  set fscan [format "%02d" $scan]
  set seqname $seqnames($scan)
  set protname $protnames($scan)
  set seqdname $seqdnames($scan)
  set slices $slicess($scan)
  set sord $sords($scan)
  if {$sord == "asc"} { set tpattern seqplus }
  if {$sord == "des"} { set tpattern seqminus }
  if {$sord == "int"} {
    if { [expr $slices%2] == 0 } {   ;# tested for transverse
      set tpattern alt+z2   ;# even: first slice is second-most inferior
    } else {
      set tpattern alt+z    ;# odd: first slice is most inferior
    }
  }
  set reps $repss($scan)
  set tr $trs($scan)
  if { $moco($scan) } { set mocotype -moco } else { set mocotype "" }
  set outfile scan${fscan}+orig.BRIK
  ## check exist
  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 in"
    puts "                $dicomdir ...skipping this one"
    puts "ima2brik: ### N.B.: ima2brik interrupt? -- safest: clean-up, redo"
    set convertedscans($scan) $scans($scan)
    continue
  }
  ## convert to BRIK
  if { $protname == "localizer" } {
    ### skip localizer (usu. a "gre")
    puts "\n##################################################################"
    puts "skipping converting localizer scan: $scan (sequence name: $seqname)"
    puts "##################################################################\n"
  } elseif { $seqname == "gre" || $seqname == "se" || $seqname == "tse" || \
             $seqname == "mprage" || $seqname == "mdeft" || \
             $seqname == "tseSP" } {
    ### 2D/3D struct scans (include non-localizer gre's) -- simple to3d
    if { $filenametype == "offline" } {
      set cmd "to3d -prefix scan${fscan} $name.$fscan.*.$imsuff"
    }
    if { $filenametype == "filtrio" } {
      set cmd "to3d -prefix scan${fscan} ${name}_${fscan}_*.$imsuff"
    }
    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" || $seqname == "mepi" } {
    ### functional scans -- to3d with args
    if { $filenametype == "offline" } {
      set cmd "to3d -prefix scan${fscan} -time:zt $slices $reps $tr \
		       $tpattern $name.$fscan.*.$imsuff"
	    }
	    if { $filenametype == "filtrio" } {
	      set cmd "to3d -prefix scan${fscan} -time:zt $slices $reps $tr \
		       $tpattern ${name}_${fscan}_*.$imsuff"
    }
    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)
  } else {
    ### TODO: other seqnames w/different layout (DTi)
    puts "/n##################################################################"
    puts "skipping converting scan: $scan (sequence name: $seqname)"
    puts "##################################################################\n"
  }
} ;# foreach scan
# 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)  ;# not (yet) used
    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)  ;# not yet used
    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
}

