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

if { [llength $argv] == 1 && [lindex $argv 0] != "-biff13"} {
  puts ""
  puts "use: \[cd into dir containing 14-field *.IMA files\]"
  puts "     renum-ima \[-biff13\]"
  puts ""
  puts "Pads two fields (scan:%d=>%02d, slice:%d=>%04d) to default unix"
  puts "sorting order.  For example, a file named:"
  puts ""
  puts \
"  BLOGGS.MR.UCL_BBK_TONOMAY10.6.91.2007.05.17.19.31.20.781250.1428407.IMA"
  puts ""
  puts "is renamed to:"
  puts ""
  puts \
"  BLOGGS.MR.UCL_BBK_TONOMAY10.06.0091.2007.05.17.19.31.20.781250.1428407.IMA"

  puts ""
  puts "With option: -biff13, variable 13th field replaced with a '#':"
  puts ""
  puts \
"  BLOGGS.MR.UCL_BBK_TONOMAY10.06.0091.2007.05.17.19.31.20.781250.#.IMA"
  puts ""
  puts "Ignores filenames without .IMA suffix, and without 14 period-separated"
  puts "fields.  OK to re-run in already-renamed directory (just checks)."
  puts ""
  exit
}

set biff13flag 0
if { [llength $argv] == 1 && [lindex $argv 0] == "-biff13"} {set biff13flag 1}
set files [glob -nocomplain *.IMA]
set filecnt [llength $files]
if {$filecnt == 0} {puts "renum-ima: ### no files match *.IMA in [pwd]"; exit}
if ![file writable [lindex $files 0]] {
  puts "renum-ima: ### can't rename:\n[lindex $files 0]\n  ...quitting"
  exit
}
puts "\nrenum-ima: found $filecnt *.IMA files in [pwd] to check/rename\n"
puts "<Ret> to check/rename, ctrl-C to quit without renaming\n"
read stdin 1

set i 0
foreach infile $files {
  set fields [split $infile .]
  if { [llength $fields] != 14 } {
    puts "renum-ima: ### $infile doesn't have 14 fields ...quitting"
    exit
  }
  set outfile [lindex $fields 0]
  foreach j { 1 2 } { set outfile $outfile.[lindex $fields $j] }
  # catch 008 (tcl interprets as hex) from already-converted
  set outfile $outfile.[format "%02d" [string trimleft [lindex $fields 3] 0]]
  set outfile $outfile.[format "%04d" [string trimleft [lindex $fields 4] 0]]
  if {$biff13flag} {  ;# also blow away variable 13th field
    foreach j { 5 6 7 8 9 10 11 } { set outfile $outfile.[lindex $fields $j] }
    set outfile $outfile.#   ;# 13th field (j=12) varies
    foreach j { 13 } { set outfile $outfile.[lindex $fields $j]}
  } else {
    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)"
