#!/usr/bin/perl
#	Usage: simple-wav-fixer.pl file.wav ...

use Data::Dumper;
use Fcntl;
use IO::Handle;

foreach my $file (@ARGV) {

	if (!-f $file) {
		print STDERR "No such file: $file\n";
		next;
	}

	eval {
		process_wav($file);
	};

	if ($@) {
		print "Processing failed: $@\n";
	}
}

exit(0);

sub process_wav {
	my $file = shift;

	if (!sysopen(F, $file, O_RDWR, 0755)) {
		print STDERR "Unable to open $file: $!\n";
		return;
	}

	my $buffer;
	my $nread = sysread(F, $buffer, 44);

	if ($nread != 44 || length($buffer) != 44) {
		print STDERR "Header length problem: $file\n";
		close(F);
		return;
	}

	my $main_template = "a4 V a4 a4 V a16 a4 V";
	my $fmt_template = "v v V V v v";

	my($riff,$riff_length,$wave,$fmt,$fmt_length,$fmt_data,$data,$data_length) = unpack($main_template, $buffer);


	print "riff is $riff\n";
	print "riff_length is $riff_length\n";
	print "wave is $wave\n";
	print "fmt is $fmt.\n";
	print "fmt_length is $fmt_length\n";

	die "expecting fmt_length == 16" if ($fmt_length != 16);

	my($fmt_compression, $fmt_channels, $fmt_samplerate, $fmt_bytespersecond, $fmt_blockalign, $fmt_significantbits) = unpack($fmt_template, $fmt_data);

	print "fmt_compression is $fmt_compression\n";
	print "fmt_channels is $fmt_channels\n";
	print "fmt_samplerate is $fmt_samplerate\n";
	print "fmt_bytespersecond is $fmt_bytespersecond\n";
	print "fmt_blockalign is $fmt_blockalign\n";
	print "fmt_significantbits is $fmt_significantbits\n";

	if ($riff ne "RIFF") {
		die "Not a RIFF file";
	}

	die "Not a WAV type file" if ($wave ne 'WAVE');
	die "Expected fmt" if ($fmt ne 'fmt ');

	# Now start fixing it...

	my @stat = stat($file);

	my $file_length = $stat[7];

	$riff_length = $file_length - 8;

	# Now work on the "data" part.

	$data_length = $file_length - 44;

	$buffer = pack($main_template, $riff,$riff_length,$wave,$fmt,$fmt_length,$fmt_data,$data,$data_length);

	sysseek(F, 0, 0);
	syswrite(F, $buffer, length($buffer));

}

