#!/usr/bin/perl
use warnings;
use strict;

my $num = 3624;

my $infile = 'simon.voc';

my $tmpvocfile = 'tmp.voc';
my $offsetfile = 'offsets';
my $tmpwavfile_all = 'tmpall.wav';

system("rm $tmpwavfile_all") if stat($tmpwavfile_all);

my $outfile = $infile;
$outfile =~ s/\.voc$/.wav/;

my $tmpwavfile = $tmpvocfile;
$tmpwavfile =~ s/\.voc$/.wav/;

if (stat($outfile)) {
    die "$outfile: File exists. Exiting\n";
}

open(IN, "<$infile") || die "Could not open file: $infile\n";
binmode(IN);

my @offsets;
my @new_offsets;

my $buf;
my $i;

for ($i = 0; $i < $num; $i++) {
    seek(IN, $i * 4, 0);
    read(IN, $buf, 4);

    $offsets[$i] = unpack('I', $buf);
}
$offsets[$i] = (stat(IN))[7];

$new_offsets[0] = 0;
$new_offsets[1] = $num * 4;

for ($i = 1; $i < $num; $i++) {
    if ($offsets[$i] == $offsets[$i + 1]) {
        $new_offsets[$i + 1] = $new_offsets[$i];
        next;
    }

    seek(IN, $offsets[$i], 0);
    read(IN, $buf, 8);

    if ($buf eq 'Creative') {
        printf("Audio found at offset: %x\n", $offsets[$i]);
    } else {
        printf("ERROR: No audio found at offset: %x\n", $offsets[$i]);
        die "Exiting.\n";
    }

    seek(IN, $offsets[$i], 0);
    read(IN, $buf, $offsets[$i + 1] - $offsets[$i]);

    open(TMP, ">$tmpvocfile");
    binmode(TMP);
    print TMP $buf;
    close(TMP);
    undef $buf;

    system("sox $tmpvocfile $tmpwavfile; cat $tmpwavfile >> $tmpwavfile_all");

    $new_offsets[$i + 1] = $new_offsets[$i] + (stat($tmpwavfile))[7];
}
pop(@new_offsets);

close(IN);

open(OUT, ">$outfile");
binmode(OUT);
foreach (@new_offsets) {
    print OUT pack('I', $_);
}
close(OUT);   

system("cat $tmpwavfile_all >> $outfile");

exit(0);

