#!/bin/bash
#
#  This runs survey,refine,unweight_events, one after the other
#  
#   First we need to get into the main directory
#
#
#  Usage: generate_events compression events parallel [name]
#

if [[  ! -d ./bin  ]]; then
    cd ../
    if [[ ! -d ./bin ]]; then
        echo "Error: it must be executed from the main, or bin directory"
        exit
    fi
fi
#
#  Now let shell know where to find important executables
#
main=`pwd`
dirbin=$main/bin
pydir=$main/../pythia-pgs/src
pgsdir=$pydir
ERAdir=$main/../ExRootAnalysis
webbin=$dirbin
td=$dirbin/td
web=0

echo $$ >> myprocid

#if ( "$1" == "" ) then
#    echo 'Number of unweighted events. This is ingnored and read from run_card.dat ' 
#    set a  = $< 
#else
#    set a = $1
#endif
if [[  "$1" == ""  ]]; then
    echo 'Enter 1 for parallel 0 for serial run' 
     read p 
else
     p=$1
fi
n=MadEvent
if [[  $p -gt 0 ]]; then
   if [[  "$2" == ""  ]]; then
    echo 'Enter name for jobs on pbs queue'
       read n
   else
       n=$2
   fi
   if [[  "$3" == ""  ]]; then
       echo 'Enter run name'
       read t
   else
       t=$3
   fi
else
   if [[  "$2" == ""  ]]; then
      echo 'Enter run name'
      read t
   else
      t=$2
   fi
fi
#set t = TeV2
if [[  ${#argv} -gt 3  ]]; then
    web=1
    webbin="$MADGRAPH_BASE/MG_ME/WebBin"
    pydir="$webbin/pythia-pgs"
    pgsdir=$pydir
    ERAdir="$MADGRAPH_BASE/MG_ME/ExRootAnalysis"
    td=$webbin/td
    touch Online
fi
date
a=`awk '/^.*=.*nevents/{print $1}' Cards/run_card.dat`
echo Generating $a events
#
#  Check if run already exists. If so, store run w/ new name
#  and remove old run before starting.
#

if [[  -e status  ]]; then
  rm status
fi
if [[  -e error  ]]; then
  rm error
fi
touch RunWeb
echo "Cleaning directories" > status
$dirbin/gen_crossxhtml-pl $t
$dirbin/clean
touch survey
echo "Starting jobs" > status
$dirbin/gen_crossxhtml-pl $t
$dirbin/survey $p $n $t
if [[  -e error  ]]; then
  cat error
  date
  cp -f error status
  rm refine
  rm RunWeb
  $dirbin/gen_crossxhtml-pl $t
  $dirbin/gen_cardhtml-pl
  exit
fi
#
#  Now collect the events - just to get the banner in fact
#
echo "Combining Events" >& status
echo "Combining Events" 
$dirbin/gen_crossxhtml-pl $t
pushd ./Source > /dev/null
make ../bin/combine_events
popd > /dev/null
pushd SubProcesses > /dev/null
$dirbin/run_combine $p
mv events.lhe ../Events/
mv unweighted_events.lhe ../Events/
popd > /dev/null
#
#  do the banner
#
cd ./Events
echo "putting the banner"
$dirbin/put_banner events.lhe
$dirbin/put_banner unweighted_events.lhe
cd ../
#
#  Store Events
#
echo "Storing Events" >& status
$dirbin/gen_crossxhtml-pl $t
$dirbin/store $t
rm -f RunWeb
echo " " >& status
$dirbin/gen_crossxhtml-pl $t
$dirbin/gen_cardhtml-pl
date
