#!/usr/bin/tclsh

# I had to write my own version of this from scratch because the
# toc2cue shipped with cdrdao would not work with the vcd files I was
# testing with. -- Brad

# toc2cue copyright 2003 Brad Hudson
# toc2cue is released under the terms of the GPL
# If you find this at all useful, please let me know

proc convert sFile {
	# This process converts the toc file to a cue file
	# it is very rudimentary in nature and will need
	# to be updated to support more types of CDs in the
	# future
	set nTrack 1
	set nIndex 1
	set sNextStart "00:00:00"
	if { ![file exists $sFile.toc] } {
		puts "The file $sFile.toc does not exist, something has gone wrong!"
		return 0
	}
	set fOut [open $sFile.cue w]
	set fIn [open $sFile.toc r]
	fconfigure $fOut
	fconfigure $fIn -buffering line
	#Write basic header file
	puts $fOut "FILE \"$sFile.bin\" BINARY"
	gets $fIn data
	set sTtype ""
	# Loop through the toc file and see what we find.
	while { ![eof $fIn] } {
		if {[llength $data] > 0} {
			if {[lsearch -exact $data "FILE"] > 0 } {
				set sNextStart [lindex $data 2]
			}
			# If anyone finds an error in these track types let me know
			if {[lsearch $data "MODE2_FORM1"] > 0 } {set sTtype "MODE1/2048"}
			if {[lsearch $data "MODE2_FORM_MIX"] > 0 } {set sTtype "MODE2/2352"}
			if {[lsearch $data "MODE1_RAW"] > 0 } {set sTtype "MODE1/2336"}
			if {[lsearch $data "MODE1"] > 0 } {set sTtype "MODE1/2336"}
			if {[lsearch $data "MODE2_RAW"] > 0 } {set sTtype "MODE2/2352"}
			if {[lsearch $data "AUDIO"] > 0 } {set sTtype "AUDIO"}
			# Hey we hit a track, let's write the entry
			if { $sTtype != "" } {
				puts $fOut "  TRACK 0$nTrack $sTtype"
				puts $fOut "    INDEX 0$nIndex $sNextStart"
				set sTtype ""
				incr nTrack
				incr nIndex 1
			}
		}
		gets $fIn data
		set nIndex 1
	}

	close $fIn
	close $fOut
	return 1

}

# Usage toc2cue /path/to/file (no extensions)

set sFileName [lindex $argv 0]
if {![convert $sFileName]} { puts "Unable to create CUE file." }

