#!/usr/bin/tclsh

# workmandb-to-tcd converter.
# Reads ~/.workmandb and generates lots of files in current directory.
# If directory is ~/.tcd, it well may happen that lots of files will
# be read by tcd as a disc/tracks description.

# Added by Tim...
# In other words, this program generates lots of files in the current
# directory. If you'd like to use this program with no hassle, cd to
# ~/.tcd/, and then run it. :)

# Copyright (c) 1997 Boris V. Tobotras
# Free for any use

set workmandb "$env(HOME)/.workmandb"

set db [open $workmandb "r"]

proc firstWord { line } {
    return [string trim [string range $line 0 [string wordend $line 0]]]
}

while { 1 } {
    
    # skip stuff until "tracks" keyword read
    
    set trackLine [gets $db]
    if { [eof $db] } break
    if { [firstWord $trackLine] != "tracks" } continue

    set Ntracks [lindex $trackLine 1]
    set totalTime [lindex $trackLine [expr $Ntracks + 2]]
    set uin 0
    for {set i 0} {$i < $Ntracks} {incr i} {
	set start [lindex $trackLine [expr $i + 2]]
	set length [expr $start / 75]
	set uin [expr $uin + ( $length * $totalTime )]
    }
    for {set i 0} {$i < $Ntracks} {incr i} {
	set trackLine [gets $db]
	set keyword [firstWord $trackLine]
	regsub -all "//" [string range $trackLine \
			      [string wordend $trackLine 0] end] \
	    " " arg
	set arg [string trim $arg]
	switch -regexp $keyword {
	    (cdname|artist) {
		set cdinfo($keyword) $arg
		incr i -1
	    }
	    track {
		set cdinfo($i) $arg
	    }
	    default {
		incr i -1
	    }
	}
    }
    set tcdFile [open "${uin}.tcd" "w"]
    puts $tcdFile $cdinfo(cdname)
    puts $tcdFile $cdinfo(artist)
    for {set i 0} {$i < $Ntracks} {incr i} {
	puts $tcdFile $cdinfo($i)
    }
    close $tcdFile
    puts "$cdinfo(cdname)"
}

#Local variables:
#mode: tcl
#End:
