#!/usr/local/bin/perl 

if (scalar(@ARGV) == 0) {
    print "Need one or more lexicon or init file names\n";
    exit;
}

$itgfile = "itgout.gra";

# Read in init file
@lexfiles = ();
for ($i = 0; $i < @ARGV; $i++) {
    if ($ARGV[$i] eq "-i") { # Read from init file
	open(INI, $ARGV[$i+1]) or die $!;
	while ($line = <INI>) {
	    if ($line =~ m/^\s*loadlex/) {
		$line =~ s/;[^\"\n]*$//;
		$line =~ m/^\s*loadlex\s+(\S+)\s*$/;
		$lexfile = $1;
		$lexfile =~ s/\.ids$//;
		push @lexfiles, $lexfile;
	    }
	}
	close(INI);
	$i++;
    } elsif ($ARGV[$i] eq "-o") { # Where to print ITG helper grammar
	$itgfile = $ARGV[$i+1];
	$i++;
    } else {
	push @lexfiles, $ARGV[$i];
    }
}

# Read in each lex file
foreach $lexicon (@lexfiles) {
    $entries = "";
    print "Processing $lexicon\n";

    # Get all pos/constituent types
    open(DICT, $lexicon) or die $!;
    while ($line = <DICT>) {
	next if $line =~ m/^\s*;/;
	if ($line =~ m/\|:/) {
	    $line =~ m/^\s*(\S+)\:\:(\S+)/;
	    $types{$1}++;
	}
    }
}

# Print out mapping file, starting with the two ITG rules
open(ITG, "> $itgfile") or die $!;

print ITG "
LEX::LEX [LEX LEX] -> [LEX LEX]
(
 (x1::y1)
 (x2::y2)
)

LEX::LEX [LEX LEX] -> [LEX LEX]
(
 (x1::y2)
 (x2::y1)
)

";

foreach $postype (sort keys %types) {
  print ITG "
LEX::LEX [$postype] -> [$postype] (
  (x1::y1)
)
";

}
