#!/bin/bash
#
#  This runs pgs on the pythia_events.hep
#
#  Usage: run_pgs [pgsdir [para/serial [run_name]]]
#  where pgsdir is the path to the pgs executable

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

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

if [ "$4" != "" ]
then
  ERAdir=$4
else
  ERAdir=../../ExRootAnalysis
fi

if [ ! -e ../Cards/pgs_card.dat ]; then
  echo "No pgs_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
  echo Running PGS
fi

export PDG_MASS_TBL=$pgsdir/mass_width_2004.mc

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

if [ "$p" = "1" ]; then
  echo '#!/bin/bash' > pgs.pbs
  echo "export PDG_MASS_TBL=$pgsdir/mass_width_2004.mc;cd $main;$pgsdir/pgs;touch pgs.out" >> pgs.pbs
  chmod u+x pgs.pbs
  qsub -N pgs_run -e pgs.err -o pgs.log -V -q madgraph pgs.pbs >> ../running_jobs 

  while [ ! -e pgs.out ]; do
    sleep 5
  done  
  rm pgs.pbs
else
  $pgsdir/pgs >& pgs.log
fi

# Remove tauola output file
rm -f fort.45 > /dev/null

if [ "$run" != "" ]; then
  if [ -e pgs_events.lhco ]; then
    if [[ -x $ERAdir/ExRootLHCOlympicsConverter && -e pgs_events.lhco ]]; then
      echo "Creating PGS Root File" > ../status
      echo "Creating PGS Root File"
      ../bin/gen_crossxhtml-pl $run
      $ERAdir/ExRootLHCOlympicsConverter pgs_events.lhco ${run}_pgs_events.root
    fi
   echo Storing files
   echo Storing PGS files > ../status
    ../bin/gen_crossxhtml-pl $run
# pgs_card.dat
   if [ -e ../Cards/pgs_card.dat ]; then
     echo "<MGPGSCard>" >>${run}_banner.txt
     cat ../Cards/pgs_card.dat   >> ${run}_banner.txt
     echo "</MGPGSCard>" >>${run}_banner.txt
   fi
# write the pgs banner
    sed -e "s/^/#/g" ${run}_banner.txt > temp.dat
    cat pgs_events.lhco >> temp.dat
    rm -f pgs_events.lhco
    mv -f temp.dat ${run}_pgs_events.lhco
    gzip -f ${run}_pgs_events.lhco
    mv -f pgs.log ${run}_pgs.log
  fi
  rm -f pythia_events.hep
fi
