#!/usr/local/bin/tclsh8.0
proc my_exit {val} {
	if {$tcl_platform(platform) == "windows"} {
		puts "Exiting with value $val - press return to continue"
		gets stdin
	}
	exit $val
}

if {[catch {package require tclmidi 4.0}]} {
	puts stderr {Can't find tclmidi package}
	my_exit 1
}

if {$argc > 1} {
	puts stderr {Usage: minfo [filename]}
	my_exit 1
}

if {$argc == 0} {
	if {$tcl_platform(platform) != "windows"} {
		set fname stdin
		set f stdin
	} else {
		puts -nonewline "Read which file: "
		flush stdout
		set fname [gets stdin]
		regsub -all {\\} $fname / newname
		set fname $newname
		if {[catch {open $fname r} f]} {
			puts "couldn't open $fname: $f"
			my_exit 1
		}
	}
} else {
	set fname [lindex $argv 0]
	if {$tcl_platform(platform) == "windows"} {
		regsub -all {\\} $fname / newname
		set fname $newname
	}
	if {[catch {open $fname r} f]} {
		puts "couldn't open $fname: $f"
		my_exit 1
	}
}
set mf [midiread $f]
midirewind $mf

set config [midiconfig $mf tracks division format]
for {set i 0} {$i < 3} {incr i} {
	set t [string tolower [lindex [lindex $config $i] 0]]
	set v [lindex [lindex $config $i] 1]
	if {[string compare $t "tracks"] == 0} {
		set tracks $v
	} elseif {[string compare $t "division"] == 0} {
		set division $v
	} elseif {[string compare $t "format"] == 0} {
		set format $v
	}
}

puts "File: $fname"
puts "Format: $format"
puts "Tracks: $tracks"
puts "Division: $division"
for {set i 1} {$i <= $tracks} {incr i} {
	puts ""
	puts "Track: $i"
	while {[set event [midiget $mf $i next]] != "EOT"} {
		puts $event
	}
}
if {$tcl_platform(platform) == "windows"} {
	puts "Press return to exit"
	gets stdin
}
