Convert Nokia VMG to plain text

Got sick of all those tiny SMS files (.vmg extension) extracted from my cell via Nokia's PC Suite. All I wanted was all messages in a single text file so that I can handle them better (reading, grepping, etc). Messages are in Unicode containing some meta-information, so this was a perfect job for Tcl. Requires newclock package for Tcl 8.4 or Tcl 8.5.

  # Convert Nokia SMS from .vmg to plain text
  #
  # Takes a directory with .vmg files, reads the unicode messages and puts
  # all messages in plaintext to stdout chronologically.

  # use new clock from Tcl 8.5 in Tcl 8.4

  package require newclock

  package require textutil

  # edit this one for displaying user names instead of numbers
  set known_numbers {+49172123456789 Joe}

  set directory [lindex $argv 0]

  if {$directory == ""} {
      puts "usage: $argv0 path-to-vmg-files"
      exit -1
  }

  set count 0

  foreach file [glob [file join $directory *.vmg]] {

      # read file

      set in [open $file]
      fconfigure $in -encoding unicode
      set message [read $in]
      close $in

      # get sender's phone number

      regexp -line -nocase {^TEL:(.*)$} $message _ sender
      foreach {number name} $known_numbers {
          if {$number == $sender} {
              set sender "$name ($number)"
          }
      }

      # extract message body

      regexp {BEGIN:VBODY\n(.*)END:VBODY} $message _ body

      # get date

      regexp -line -nocase {^Date:(.*)$} $message _ date
      set date [clock scan $date -format {%d.%m.%Y %H:%M:%S}]
      set date [clock format $date -format {%Y-%m-%d %H:%M:%S}]

      set key "$date -- $sender"

      # remove date from message body
      regsub -line -nocase {^Date:(.*)$} $body "" body

      if {[array get messages $key] != ""} {
          puts stderr "Warning: double entries at $key!"
      }
      set messages($key) $body
      incr count
  }

  set keys [array names messages]
  foreach key [lsort $keys] {
      puts [string repeat - 72]
      puts "* $key\n"
      puts [::textutil::indent [::textutil::adjust $messages($key) -length 70] "  "]
  }
  puts stderr "\nConverted $count messages."

A vmg-file looks like this:

  BEGIN:VMSG
  VERSION:1.1
  X-IRMC-STATUS:READ
  X-IRMC-BOX:INBOX
  X-NOK-DT:20071022T212100Z
  X-MESSAGE-TYPE:DELIVER
  BEGIN:VCARD
  VERSION:3.0
  N:
  TEL:+49172123456789
  END:VCARD
  BEGIN:VENV
  BEGIN:VBODY
  Date:22.10.2007 21:21:00
  Greetings from Joe!
  END:VBODY
  END:VENV
  END:VMSG

And we end up with this on stdout

  ------------------------------------------------------------------------
  * 2007-10-22 21:21:00 -- Joe (+49172123456789)

    Greetings from Joe!