#! /pkg/bin/perl
# ------------- Program Help ----------------
sub printhelp
{
    print <<ENDOFHELP;
    
    Syntax:  $THIS <machine_file> <port> <exec> <args> [-h]
      
    $THIS is a PERL script to set up the UCTuplets environment.

    <machine_file>   Specifies the file containing the machines
		     from which to launch UCTuplets.  See the
		     UCTuplets manual for details on the
		     organization of this file. 

    <port>	     Specifies the port number on which to run
		     the tuple manager.

    <exec>	     Specifies the executable file to run in the
		     UCTuplets environment.

    <args>	     Specifies the arguments that should be passed
		     to the given executable.

    -h               Will print out this help screen.

ENDOFHELP
exit(1);
}

if ($0 =~ /\/([^\/]+)$/) { $THIS = $1;}
else {$THIS = $0;}

# -------------- Defaults ----------------------

# -------------- Parse Arguments ---------------

$machine_file	= shift(@ARGV);
$port		= shift(@ARGV);
$exec		= shift(@ARGV);

$temp = @ARGV;

for ($i=0; $i < $temp; $i++) {
  $arguments = $arguments . " " . (shift(@ARGV));
}

&printhelp unless ($machine_file && $port && $exec);


# -------------- Main Program ---------------

&parse_machine_file;
&run_shells;

# -------------- Subs -----------------------

sub parse_machine_file {
  open (IN, "<$machine_file") || die "Could not open $machine_file for reading.\n";

  while ($line = <IN>) {
    if($line =~ /(\w+)/) {
       push @machines, $1;
    }
  }
}

sub run_shells {
  $numnodes = @machines;
  ($numnodes > 1) || die "More than one node is required for UCTuplets.\n";

  $mgr = shift @machines;

# system("touch $outname");

  $count = 1;
  while ($machine = shift @machines) {
    system("rsh $machine $exec $mgr $port $count $numnodes $arguments &");
    $count++;
  }

  system("sleep 3");
  system("rsh $mgr $exec $mgr $port 0 $numnodes $arguments");
}
