#!/usr/bin/perl -w
# Author:       Matthew Hearn
# Date:         3/23/10
# File:         split-case-restore.pl
# Description:  Calls the splitter, then restores the case in the
#               given results.

use IO::Socket;
use Clean;

if ($#ARGV + 1 < 3)
{
    print "USAGE:  split-case-restore.pl <identifier> <language> <number-of-splits-to-output>\n";
    exit(1);
}

my $id = &clean($ARGV[0]);
my $lang = &clean($ARGV[1]);
my $n = $ARGV[2];

if ($n ne '-1')
{
    $n = &clean($n);
}

if ($id !~ /^[a-zA-Z\$\_\-]+$/)
{
    die("Illegal characters in id.");
}
if ($n !~ /^[+\-]?[0-9]+$/)
{
    die("Illegal characters in n.");
}

my $remote = IO::Socket::INET->new(Proto => 'tcp',
                                   PeerAddr => 'pyro2.cs.loyola.edu',
                                   PeerPort => '3333')
             or die("Cannot connect to server\n");
my $msg = "$id $lang $n\n";
print $remote $msg;

# Log that a split occurred at this time.

my $data_file = "split-times.dat";
my @time = localtime(time);

# The following code taken from:  http://perl.about.com/od/perltutorials/a/perllocaltime_2.htm for convenience

my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
my @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
my $year = 1900 + $yearOffset;
$theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";

open(DATA, ">>", $data_file) or die("Cannot open file.");
print DATA "$theTime\n";
close(DATA);

# Call splitter using given args

#my @splits = ServerFunctions::read_message($remote);
#my @splits = <$remote>;

my $last_word_num = "-1";
my $curr_id_index = 0;

#foreach $split (@splits)
my @id_chars = split(//, $id);
my $split = "";

while (defined($split = <$remote>))
{
    my @split_line = split(/\t/, $split);
    my @split_chars = split(//, $split_line[1]);
    my $curr_word_num = $split_line[0];

    # Loop through the original identifiers chars

    if ($curr_word_num eq $last_word_num)
    {
        $curr_id_index = $last_id_index;
    }

    my $i;
    for ($i = $curr_id_index, my $j = 0; $i < $#id_chars + 1; $i++, $j++)
    {
        if ($id_chars[$i] eq "_")
        {
            $j--;
            next;
        }
        if ($split_chars[$j] eq "_")
        {
            $i--;
            next;
        }

        if (lc($id_chars[$i]) ne $split_chars[$j])
        {
            last;
        }
        else
        {
            $split_chars[$j] = $id_chars[$i];
        }
    }


    $last_id_index = $curr_id_index;
    $curr_id_index = $i;

    $last_word_num = $curr_word_num;
    
    # Join the characters together and split them by '\n'
    
    my @corrected = split(/\n/, join("", @split_chars));

    # Print the corrected split

    for (my $i = 0; $i < $#corrected + 1; $i++)
    {
        print "$split_line[0]\t$corrected[$i]\n";
    }
}

