#!/usr/bin/env perl

die "Usage: $0 avifile ...\n" if $#ARGV < 0;

foreach $filename (@argv) {
	open AVIFILE,"+<$filename"  or  die "Cannot open $filename: $!\n";
	seek AVIFILE,8,0       or  die "Failed seeking to position 8 of $filename\n";
	read AVIFILE,$chunkname,8;
	if ($chunkname ne "AVI LIST") {
		die "$filename: Not an AVI file\n";
	}

	$pos=16;
	$size=0;
	do {
		$pos += $size;
		seek AVIFILE,$pos,0   or die "Failed seeking to position $pos in $filename\n";
		if ((read AVIFILE,$nextsize,4) != 4) {  die "Couldn't read size at $pos in $filename\n"; }
		$size = unpack "i",$nextsize;
		if ((read AVIFILE,$chunkname,4) != 4) {  die "Couldn't read name at $pos in $filename\n"; }
		$pos += 8;
	} while ($chunkname ne "movi");

	$streamstart = $pos - 4;
	$streamsize = $size;
	if (($streamstart + $streamsize) / ( -s $filename) < 0.75) {
		die "Refusing to truncate $filename at " . ($streamstart + $streamsize) . " - ratio suspiciously high\n";
	}
	truncate AVIFILE,$streamstart + $streamsize   or die "Cannot truncate index in $filename\n";
	seek AVIFILE,$streamstart - 4,0                 or die "Cannot seek to start of stream in $filename, whatever that means\n";
	print AVIFILE pack "i",$streamsize;
	close AVIFILE;
}

