#!/usr/bin/perl -w

# wav-checker to to see if there is an issue with WAV files

# Definition:
# http://ccrma.stanford.edu/courses/422/projects/WaveFormat/

use strict;

my $filename = $ARGV[0];

unless (-e $filename) {
    die("File '$filename' does not exist.\nUsage: wav-check.pl <file.wav>\n");
}

my @statresult = stat($filename);
my $filesize = ($statresult[7]);

open (F, "<$filename");
my ($a, $b, $c, $d, $pos, @chunkid, @chunksize, $format);
my $chunks = 0;

# read size of first shunk
$pos = 0; # Position for RIFF shunk descriptor
seek F, $pos, 0;
read F, $chunkid[0], 4;
read F, $d, 1;
read F, $c, 1;
read F, $b, 1;
read F, $a, 1;
read F, $format, 4;
$chunksize[0] = ord($d) + ord($c)*256 + ord($b)*256*256 + ord($a)*256*256*256;

# Read the next shunk
$pos = 12; # Position for FMT shunk descriptor
do {
    $chunks++;
    seek F, $pos, 0;
    read F, $chunkid[$chunks], 4;
    read F, $d, 1;
    read F, $c, 1;
    read F, $b, 1;
    read F, $a, 1;
    $chunksize[$chunks] = ord($d) + ord($c)*256 + ord($b)*256*256 + ord($a)*256*256*256;
    
    # Calculate position of next chunk
    $pos = $pos + 8 + $chunksize[$chunks];
} while ($pos+8 <= $filesize);


print "
Filename: $filename

-- RIFF chunk descriptor -------------------------
ChunkID                        : $chunkid[0]
Format                         : $format
Chunksize                      : $chunksize[0]
";
for (my $i = 1; $i <= $chunks; $i++) {
print "
--- sub chunk ($i) --------------------------------
ChunkID                        : $chunkid[$i]
Chunksize                      : $chunksize[$i]
";
}
print "
--- Filesize calculations ------------------------
Filesize on disk               : $filesize
Filesize using RIFF Chunksize  : ".(8 + $chunksize[0])."
Filesize summing sub Chunks    : $pos

Test complete.
";
               
