# DO NOT MODIFY
# This script is required for PerlEdit
use strict;

foreach (@ARGV) {if (/ |\"/) { $_ =~ s/\"/\\\"/g; $_ = "\"$_\""; } } # quote the arguments

if ($ARGV[0] eq "-redir") {
  # redirect stderr to stdout and run specified command
  shift @ARGV;
  open (STDERR, ">&STDOUT");
  my $cmd = join(" ", @ARGV);
  my $rc = system $cmd;
  exit $rc;
}

my $prompt = 0; if ($ARGV[0] eq "-prompt") { shift @ARGV; $prompt = 1; }
my $port = 1956; if ($ARGV[0] eq "-port") { shift @ARGV; $port = shift; }
my $host = "127.0.0.1"; if ($ARGV[0] eq "-host") { shift @ARGV; $host = shift; }

my $cmd = join(" ", @ARGV);
if ($^O eq "MSWin32" && Win32::IsWin95()) {
	$cmd = "$^X $0 -redir $cmd";
} else {
	$cmd = "$cmd 2>&1";
}
#print "cmd = '$cmd'\n";
              
my $sock = OpenConnection($host, $port);
open(PIPE, "$cmd|");
select PIPE; $| = 0; select STDOUT;
my $data;

#while($data = <PIPE>) {               # read a line at a time
while ( sysread(PIPE, $data,1000) ) {    # read up to n chars at a time
	Send($sock, $data);
    print STDOUT "$data";
}
if ($prompt) {
    print "Press Enter to continue";
	<STDIN>;
}
close($sock);
exit 0;


sub OpenConnection #(host)
{
    my ($host, $port) = @_;
    my($name,$aliases,$type,$len,$thataddr);
    my ($hostname,$ipaddr);
    my ($fh) = \*S;

    #calculate $ipaddr from $host
    if ($host =~ m/[^\d\.]/) {
        # format is foo@foo.com
        ($hostname,$aliases,$type,$len,$ipaddr) = gethostbyname($host);
    }
    else {
        #123.456.789.012 format
        $ipaddr = pack('C4', split(/\./, $host));
        # if we need hostname, get it like this
        #($hostname,$aliases,$type,$len,$ipaddr) = gethostbyaddr($ipaddr, 2);
    }

    #print "host = $host\n";
    #print "ipaddr = ", sprintf("[%d.%d.%d.%d]", unpack('C4', $ipaddr)), "\n";

    my $address = pack("S n a4 x8", 2, $port, $ipaddr);
    socket($fh, 2, 1, 0);
    if (!connect($fh, $address)) {
        return undef;
    }
    return $fh;
}


sub Send
{
    my($socket, $data) = @_;
    send ($socket, $data, 0);
}

