#!/usr/bin/perl -w

# eval_rec.pl final/stoneage-swe.dct final/stoneage-swe.net test_utts.txt test_data final/hmm_tri/hmmlist final/hmm_tri/macros final/hmm_tri/hmmdefs

use strict;
use File::Basename;

my $prompts2mlf = check_prog("prompts2mlf");

if (@ARGV < 6) {
    print STDERR "Usage: eval_rec.pl <dictionary> <network> "
	         . "<test utterance file> <test data dir> "
		 . "<hmmlist> <mmf> [<mmf> ...]\n";
    exit 2;
}

my $dict = shift;
my $network = shift;
my $test_utts = shift;
my $test_data = shift;
my $hmmlist = shift;
my @mmfs = @ARGV;

if (! -f $dict) {
    print STDERR "Dictionary '$dict' not found\n";
    exit 2;
}

if (! -f $network) {
    print STDERR "SLF file '$network' not found\n";
    exit 2;
}

if (! -f $test_utts) {
    print STDERR "Test utterance file '$test_utts' not found\n";
    exit 2;
}

if (! -d $test_data) {
    print STDERR "Test data directory '$test_data' not found\n";
    exit 2;
}

if (! -f $hmmlist) {
    print STDERR "HMM list '$hmmlist' not found\n";
    exit 2;
}

foreach (@mmfs) {
    if (! -f $_) {
	print STDERR "MMF '$_' not found\n";
	exit 2;
    }
}

my $tmpdir = "tmp";

if (! -d $tmpdir) {
    mkdir $tmpdir;
}

my $test_mlf = "$tmpdir/test_utts_words.mlf";

print "Creating word-level MLF file for test utterances...\n";
run("$prompts2mlf '$test_utts' > $tmpdir/test_utts_words.mlf");

my $config = "$tmpdir/test_config";

my $wordpen = "-10.0";

open TEST_CONFIG, ">$config";
print TEST_CONFIG<<END;
SOURCERATE   = 625
TARGETKIND   = MFCC_0_D_A
TARGETRATE   = 100000.0
WINDOWSIZE   = 250000.0
ENORMALISE   = F
USEHAMMING   = T
PREEMCOEF    = 0.97
NUMCHANS     = 26
CEPLIFTER    = 22
NUMCEPS      = 12
END
close TEST_CONFIG;

my $test_scp = "$tmpdir/test.scp";

system "ls $test_data/*.wav > '$test_scp'";

if ((stat($test_scp))[7] == 0) {
    print STDERR "No files files found in '$test_data'\n";
    exit 2;
}

my $outmlf = "$tmpdir/test_out.mlf";

print "Running recognizer...\n";

my $mmf_opts = join(' ',map {"-H '$_'"} @mmfs);

system "HVite32 -A -T 1 -p '$wordpen' -C '$config' -o F $mmf_opts -S '$test_scp' -w '$network' -i '$outmlf' '$dict' '$hmmlist'";

print "Analyzing results...\n";

system "HResults32 -t -I '$test_mlf' '$hmmlist' $outmlf";

sub run {
    my $command = shift;
    print "$command\n";
    system $command;
}

sub check_prog {
    my $prog_dir = (fileparse($0, qr/\.[^.]*/))[1];
    my $prog = ($prog_dir ne "") ? 
	         (($prog_dir =~ /\/$/) ? $prog_dir.$_[0] : $prog_dir."/".$_[0])
		 : $_[0];

    if (! -x $prog) {
	print STDERR "$prog is not an executable file.\n";
	print STDERR "Maybe you need to run 'make'?\n";
	exit 1;
    }

    return $prog;
}
