#!/usr/bin/perl -w
use strict;

if (@ARGV != 3) {
    print STDERR "Usage: fix_sp_model.pl <hmm out dir> <hmmdefs> <hmmlist>\n";
    exit 2;
}

my $outdir = shift @ARGV;
my $hmmdefs = shift @ARGV;
my $hmmlist = shift @ARGV;

if (! -f $hmmdefs) {
    print STDERR "HMM defs file $hmmdefs not found\n";
    exit 2;
}

my $tmpdir = "tmp";

mkdir $outdir;

my $tmphmmdefs = "$tmpdir/hmmdefs";

my $spmodel = "~h \"sp\"\n";

open IN, $hmmdefs or die "Cannot open $hmmdefs: $?";
open OUT, ">$tmphmmdefs" or die "Cannot open $tmphmmdefs: $?";
while (<IN>) {
    print OUT;
    if (/^~h "sil"/) {
	SIL: while (<IN>) {
	    print OUT;
	    my $s;
	    if (($s = $_) =~ s/<STATE>\s*(\d+)/$1/ && $s != 3) {
		while (<IN>) {
		    print OUT;
		    last if /<GCONST>/;
		}
	    } elsif (/<TRANSP>/) {
		$spmodel .= "<TRANSP> 3\n";
		$spmodel .= "0.0 1.0 0.0\n";
		$spmodel .= "0.0 0.6 0.4\n";
		$spmodel .= "0.0 0.0 0.0\n";
		while (<IN>) {
		    print OUT;
		    if (/<ENDHMM>/) {
			$spmodel .= $_;
			last SIL;
		    }
		}
	    } else {
		s/<NUMSTATES> 5/<NUMSTATES> 3/;
		s/<STATE> 3/<STATE> 2/;
		$spmodel .= $_;
	    }
	}
    }
}
print OUT $spmodel;
close OUT;
close IN;


my $hmmlist_new = "$outdir/hmmlist";

run("echo sp | cat $hmmlist - | sort > $hmmlist_new");

my $sil_hed = "$outdir/sil.hed";

open SIL_HED, ">$sil_hed";
print SIL_HED<<END;
AT 2 4 0.2 {sil.transP}
AT 4 2 0.2 {sil.transP}
AT 1 3 0.3 {sp.transP}
TI silst {sil.state[3],sp.state[2]}
END
close SIL_HED;

print "Adding extra transitions and tying sp to sil...\n";

run("HHEd32 -H '$tmphmmdefs' -M '$outdir' $sil_hed $hmmlist_new");

unlink $sil_hed;
unlink $tmphmmdefs;


sub run {
    my $command = shift;
    print "$command\n";
    system($command) == 0 || die "Failed: $?";
}
