#!/usr/bin/env tclsh
# (C) Stephan Beyer <s-beyer@gmx.net>, GPLv2, 2006
# tested with Tcl8.4 and Snack 2.2!
# A start without any parameters gives information

# this is a fork of silence.tcl 20060707 which does only remove
# the silence at the beginning!


# You may send feedback!

# Preferences
################

# a sample range independent value for the tolerance of "silence"
set mytol 120
# this default will be converted to a total absolute tolerance of
# 3 bytes when using sample the full sample range of 16 bit
# or 1 byte on 8 bit.


# output filename suffix, use a format-like %d anywhere. This will be 
# replaced by a number!
set outsuffix .nobegin


# Procedures
###############

proc sec {bytes} {
	global rate
	expr int(10.0*$bytes/$rate)/10.0
}

proc outname {} {
	global wavfile outsuffix
	format %s/%s%s\.wav  [file dirname $wavfile] \
	  [file rootname [file tail $wavfile]] $outsuffix
}


# Main
###########

if {$argc == 0} {
	puts stderr "Usage: $argv0 file.wav \[tolerance\]\n"
	set wavfile file.wav
	puts stderr "`tolerance' is a value between 0 and 1000000, while 0 means: only consider"
	puts stderr "amplitudes 0 being silence. 1000000 represents the maximal amplitude."
	puts stderr "This defaults to $mytol.\n"
	puts stderr "NO WARRANTY. Have fun. :)\t\t(C) Stephan Beyer, 2006, GNU GPLv2"
	exit 2;
} else {
	set wavfile [lindex $argv 0]
	if {$argc >= 2} {
		set mytol [lindex $argv 1]
		if {$argc > 2} {
			puts stderr "Warning: additional parameters are being ignored."
		}
	}
}

package require snack
snack::audio stop

puts "Loading $wavfile\..."
snack::sound snd -load $wavfile 

# sound data info
set soundinfo [snd info]
set length [lindex $soundinfo 0]
set rate [lindex $soundinfo 1]
set lensec [expr $length/$rate]
set channels [lindex $soundinfo  5]
set rmax [lindex $soundinfo 2]
set rmin [lindex $soundinfo 3]
puts "  Length: $length bytes"
puts "  Sample rate: $rate Hz"
puts "    plays [sec $length] seconds"
puts "  Sample range: $rmin .. $rmax"
puts "  Encoding: [lindex $soundinfo 4]"
puts "  Channels: $channels"
puts "  File format: [lindex $soundinfo 6]"
puts "  Header length: [lindex $soundinfo 7] Bytes\n"

set tol [expr int($mytol/2000000.0*($rmax-$rmin))]

#  $cen +/- $tol is the range of silence
set cen [expr ([join [snd sample 0] +])/$channels]
set count 0

for {set i 1} {$i < $length} {incr i} {
	set sample [snd sample $i]
	# average over all channels
	set avg [expr ([join $sample +])/$channels]

	incr count

	if {$avg < $cen - $tol || $avg > $cen + $tol} {
		puts "at sample $count"
		puts "playing one second"
		snd play -start $count -blocking 1 -end [expr $count+44100]
		snd write [outname] -start $count
		puts "written"
		exit 0
	}
}
puts "not written"
exit 0
