#!/usr/local/bin/perl
# Run the PYBMS generator
#
# Syntax: pybms-bat  'setupFile'
#                    'genIniInfo'
#                    'genName'
#                     requestedEvents
#                    'codeVersion' 
#                    'outputFile'
#                     runNumber
#                     rndmBlock
#
# Version 0.00 4-Jan-1999 GRB Creation
#
# PYBMS is a generator system created by Tim Barklow to run Pythia with
# various configurations that include beam effects.
#

use FileHandle;

# ---------------------------------------------------
#   Save arguments.
# ---------------------------------------------------

$setupFile       = @ARGV[0];
$genIniInfo      = @ARGV[1];
$genName         = @ARGV[2];
$requestedEvents = @ARGV[3];
$codeVersion     = @ARGV[4];
$outputFile      = @ARGV[5];
$runNumber       = @ARGV[6];
$rndmBlock       = @ARGV[7];

# ---------------------------------------------------
#   Define some stuff.
# ---------------------------------------------------

$workdir = "/nfs/surrey01/work/nld/tmp/";
$jobPID = getppid;
$pyScript = $workdir . "pyini" . $jobPID;
$seed = 10000*$rndmBlock + $runNumber + 19780513;
$codeVersionBin = $codeVersion . "bin/";
$codeVersionSrc = $codeVersion . "src/";
$codeVersionBinPythia = $codeVersionBin . "pythia";

# ---------------------------------------------------
#   Open the generic PYBMS Comis script to read it.
# ---------------------------------------------------

my $PYGENERIC = new FileHandle;
if ( !( $PYGENERIC->open("<$genIniInfo") ) ) {
    die "pybms-bat::Couldn't open $genIniInfo\n";
}

# ---------------------------------------------------
#   Create the job specific PYBMS Comis script.
# ---------------------------------------------------

my $PYSPECIFIC = new FileHandle;
if ( !( $PYSPECIFIC->open(">$pyScript") ) ) {   
     die "pybms-bat::Couldn't open $pyScript\n";
}

foreach $_ (<$PYGENERIC>) {

   $newline = $_;  

   if         ( /^cd / ) {
       $newline = "cd" . " " . $codeVersionSrc . "\n";
   }
   elsif ( /^pythia/ ) {
       $newline =~ s/pythia/$codeVersionBinPythia/;
   }
   elsif     ( /^ mrlu\(1\)=/ ) {
          $newline = " mrlu(1)=" . $seed . "\n";
   } 
   elsif ( /^ datfile_bms=/ ) {
          $newline = " datfile_bms=" . "'" . $outputFile . "'\n";;
   } 
   elsif ( /^ NEVENT_STD=/ ) {
          $newline = " NEVENT_STD=" . $requestedEvents . "\n"; 
   }

   print $PYSPECIFIC $newline;

}

$PYGENERIC->close;
$PYSPECIFIC->close;

# ---------------------------------------------------
#   Run the specific generator script and then delete it.
# ---------------------------------------------------

$chmodx = "chmod +x" . " " . $pyScript;
system($chmodx);
system($pyScript);
#system("rm $pyScript");


