#!/bin/bash
#
#  This runs hep2lhe on the unweighted_events.dat
#
#  Usage: run_hep2lhe [pydir [para/serial [run_name]]]
#  where pydir is the path to the hep2lhe executable

if [ "$1" != "" ]
then
  pydir=$1
else
  pydir=../../pythia-pgs/src
fi

p=$2
run=$3
main=`pwd`

if [ ! -e ../Cards/pythia_card.dat ]; then
  echo "No pythia_card.dat found. Quitting..."
  exit
fi

echo $$ >> ../myprocid

if [ "$run" != "" ]; then
  if [ ! -e ${run}_pythia_events.hep.gz ]; then
    echo "No file  ${run}_pythia_events.hep.gz. Quitting..."
    exit
  fi
  echo gunzip ${run}_pythia_events.hep.gz
  gunzip -c ${run}_pythia_events.hep.gz > pythia_events.hep
fi

rm -f hep2lhe.log > /dev/null
rm -f hep2lhe.err > /dev/null
rm -f hep2lhe.out > /dev/null

echo "Running hep2lhe"
if [ "$p" = "1" ]; 
then 
echo '#!/bin/bash' > hep2lhe.pbs
echo "cd $main;$pydir/hep2lhe;touch hep2lhe.out" >> hep2lhe.pbs
chmod u+x hep2lhe.pbs
qsub -N hep2lhe_run -e hep2lhe.err -o hep2lhe.log -V -q madgraph hep2lhe.pbs >> ../running_jobs
while [ ! -e hep2lhe.out ]
do
  sleep 5
done
rm -f hep2lhe.pbs
else
$pydir/hep2lhe >& hep2lhe.log
fi

if [ -e pythia_events.lhe ] && [ -e pythia_events.init ]; then
   echo "<LesHouchesEvents version=\"1.0\">" > temp.lhe
   cat pythia_events.init >> temp.lhe
   cat pythia_events.lhe >> temp.lhe
   mv temp.lhe pythia_events.lhe
   rm pythia_events.init
fi

if [ "$run" != "" ]; then
  echo "Storing files"
  if [ -e pythia_events.lhe ]; then
# pythia_card.dat
   echo "#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" >> ${run}_banner.txt
   echo "# Begin pythia_card.dat" >>${run}_banner.txt
   echo "#">>${run}_banner.txt
   if [ -e ../Cards/pythia_card.dat ] ; then 
      cat ../Cards/pythia_card.dat   >> ${run}_banner.txt
   fi
   echo "#" >> ${run}_banner.txt
   echo "# End pythia_card.dat" >>${run}_banner.txt
   echo "#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<">>${run}_banner.txt
   echo \<LesHouchesEvents version=\"1.0\"\> > temp.lhe
   echo \<\!-- >> temp.lhe
   cat ${run}_banner.txt >> temp.lhe
   sed /'<LesHouchesEvents version=\"1.0\">'/s//'-->'/ pythia_events.lhe >> temp.lhe
   rm pythia_events.lhe
   mv -f temp.lhe ${run}_pythia_events.lhe
   gzip -f ${run}_pythia_events.lhe
   mv -f hep2lhe.log ${run}_hep2lhe.log
  fi
  rm -f pythia_events.hep  
fi
