#!/usr/local/bin/perl

# Mapudungun morphology wrapper by Erik Peterson, eepeter@cs.cmu.edu
# May, 2005

# Change these variables to match local situation
$tmpdir = "/tmp";                                    # Directory where temporary files will go
$javaexec = "/usr/local/libexec/j2re1.4.2/bin/java"; # or just "java" if in your path
$dirdelim = ":";                                     # or ";" for Windows
$morphdir = "/afs/cs.cmu.edu/project/avenue-1/Avenue/Mapu-MT/Morph"; # dir with jar/parse subdirs

use IO::Socket::INET;
use Net::hostent;
use FileHandle;
use File::Temp "tempfile";
#use Encode;

use POSIX ":sys_wait_h";


@classpaths = ("");
$ENV{'CLASSPATH'} = join $dirdelim, @classpaths;

# Default server port number is 5762; 
# Include port number as argument if want different port
if (scalar(@ARGV) == 1 and $ARGV[0] =~ m/^\d+$/) {
    $serverport = $ARGV[0];
} else {
    $serverport = 5780;
}

# Auto-flush
$| = 1;

# Open server port
$server = IO::Socket::INET->new(LocalPort => $serverport,
				Type => SOCK_STREAM,
				Reuse => 1,
				Listen => 12)
    or die "Couldn't be a tcp server on port $serverport: $!\n";

print "Starting Mapudungun morphology server on port $serverport\n"; #; $cachecount words cached\n";

$SIG{CHLD} = sub { wait };

# Wait for connections
while ($client = $server->accept()) {
    if ($kidpid = fork) {
	close $client;
	next;
    }

    defined($kidpid) or die "cannot fork: $!";

    close $server;

    print "[Connection established]\n";

    # Read Hebrew sentence
    while ($sent = <$client>) {
	if ($sent eq "**EXIT**") {
	    last;
	}

	$sent =~ s/[\r\n]*$//;

	print "Processing incoming sentence $sent\n";
	
	($morphfd, $morphin) = tempfile("morphXXXXXX",
					DIR => $tmpdir,
					SUFFIX => '.txt');

	print $morphfd $sent;
	close($morphfd);
	($morphprefix) = ($morphin =~ m/^(.+?)\.txt$/);
	$morphout = $morphprefix . ".out";
	
        print "Executing: Morphology program\n";

	# Process input, read analyzed form, convert to feature structure
	# ...
	
	$fss = "";

	# Processing into exact format expected by transfer engine
        open(FS, $morphout) or warn $!;
	while ($line = <FS>) {
	    print $line;
	    $line =~ s/\s+/ /g;
	    $line =~ s/\" \)/\"\)/;
	    #$line =~ s/masculine and feminine/\(\*or\* masculine feminine\)/;
	    $line =~ s/\( LEX\s+\)/\( LEX \"\"\)/;

	    $line =~ s/[\r\n]*$/ /;
	    $line =~ s/\( LEX /\( lex /;
	    $line =~ s/\( POS /\( pos /;
	    $fss .= $line;
	}
        close(FS);

        # Send feature structures back to xfer engine
        print $client "$fss\n";

	# Clean up temp files
        unlink $morphin, $morphout;
        $morphin = $morphprefix = $morphout = "";
    }

    print "[Connection closed]\n";
}

