#!/usr/local/bin/perl

# Perl client to connect to transfer server
# Erik Peterson
# Jan. 30, 2007

use IO::Socket::INET;

$remote_host = "localhost";
$remote_port = "4502";

$inputfile = "";
$outputfile = "";

for ($i = 0; $i < @ARGV; $i++) {
    if ($ARGV[$i] eq "-i" and $i+1 < @ARGV) {
	$inputfile = $ARGV[$i+1];
    } elsif ($ARGV[$i] eq "-o" and $i+1 < @ARGV) {
	$outputfile = $ARGV[$i+1];
    } elsif ($ARGV[$i] eq "-p" and $i+1 < @ARGV) {
	$remote_port = $ARGV[$i+1];
    } elsif ($ARGV[$i] eq "-s" and $i+1 < @ARGV) {
	$remote_host = $ARGV[$i+1];
    } elsif ($ARGV[$i] eq "-h") {
	print "Usage: client.pl [-p portnum -s server] -i inputfile -o outputfile 
  -i   input file name
  -o   output file name
  -s   remote server name
  -p   port number \n";
    }
}

if ($inputfile eq "" or $outputfile eq "") {
    print "Please specify input and output files\n";
}


$socket = IO::Socket::INET->new(PeerAddr => $remote_host,
				PeerPort => $remote_port,
				Proto    => "tcp",
				Type     => SOCK_STREAM)
    or die "Couldn't connect to $remote_host:$remote_port : $!\n";


open(IN, "$inputfile") or die $!;
open(OUT, "> $outputfile") or die $!;
while ($line = <IN>) {
    $line =~ s/[\r\n]*$//;
    if ($line =~ m/^\s*$/) {
	print OUT "$line\n";
	next;
    }
    print $socket "XFER $line\n";
    $trans = <$socket>;
    print OUT $trans;
}
print $socket "*EOF*\n"; # Close the connection
close($socket);
close(IN);
close(OUT);
