#!/usr/bin/perl

use utf8;
use POSIX qw/strftime/;
binmode(STDOUT, utf8);
binmode(STDERR, utf8);
binmode(STDIN, utf8);

$usage = "Usage: $0 <supertagger model> [input file]\n";
$defaultid = 80000000;
$MODEL = shift @ARGV or die $usage;
$stcmd = "tnt -v0 -z2 $MODEL -";

if ($in = shift @ARGV) {
	open($IN, "<:utf8", $in) or die "Couldn't open $in: $!\n$usage";}
else { $IN = STDIN;}

$fsc_orig = "";

while(<$IN>)
{
	$fsc_orig .= $_;
	chomp;
	if(/chart id="(\d+)"/)
	{$id = $1;}
	if(/<lattice init="v\d+" final="v(\d+)">/)
	{$length = $1;}
	if(/\+FORM"><str><!\[CDATA\[(.*)\]\]/)
	{$toks .= $1."\n";}
	if (/<\/fsc>/) {
		$toks .= "\n";
		my $fullstcmd = "echo \"$toks\"|".$stcmd;
		$taggedtext = `$fullstcmd`;
		while($fsc_orig =~ /(.*)\n/g)
		{
			$_ = $1;
			$fsc .= $_;
			if(/PRBS/)
			{
				$fsc .= "</fs></f>";
				$taggedtext =~ /^(.*)\n/;
				$token = $1;
				$taggedtext =~ s/^(.*)\n//;
				@tagpairs = split /\s+/, $token;
				$fsc .= "<f name=\"+STAG\"><fs type=\"stag\">";
				$fsc .= "<f name=\"+TAG\" org=\"list\">";
				for($x=1; $x<$#tagpairs;$x+=2) {	
					$fsc .= "<str>".$tagpairs[$x]."</str>"; }
				$fsc .= "</f><f name=\"+PRB\" org=\"list\">";
				for($x=2; $x <= $#tagpairs; $x+=2) {	
					$fsc .= sprintf("<str>%.4f</str>",($tagpairs[$x]+0));}
				$fsc .= "</f>";
			}
		}
		$id = $defaultid++ if($id == "");
		print "$id\@unknown\@formal\@none\@1\@S\@$fsc\@1\@$length\@\@"
			.$ENV{USER}."\@".strftime('%F', localtime)."\n";
		$id = "";
		$fsc = "";
		$fsc_orig = "";
		$toks = "";
	}
}
