#!/bin/bash

fail_exit() { echo "$@"; exit 1; }
echo "   ______________________________________     "
echo "         Running Phantom                      "
echo "   ______________________________________     "
nevt=${1}
echo "%MSG-PHANTOM number of events requested = $nevt"
rnum=${2}
echo "%MSG-PHANTOM random seed used for the run = $rnum"
ncpu=1
echo "%MSG-PHANTOM number of cputs for the run = $ncpu"
cmssw_version=CMSSW_9_3_0
scram_arch=slc6_amd64_gcc630
modify_env=false
if [ -n "$4" ]
  then
    modify_env=$4
    if [ "$modify_env" = true ]
      then
      if [ -n "$6" ]
        then
          cmssw_version=${6}
      fi
    fi  
  echo ${1}
  else
  echo "ciccia"  
fi
echo "%MSG-PHANTOM getting environment LHAPDF from CMSSW release = $cmssw_version"
echo "%MSG-PHANTOM running with architecture  = $scram_arch"
scram -a ${scram_arch} project CMSSW ${cmssw_version}
cd ${cmssw_version}/src
eval `scram runtime -sh`
cd -
wget https://cms-project-generators.web.cern.ch/cms-project-generators/phantom/compiled/phantom_1_3_p1_slc6_amd64_gcc630.tar.gz
tar xzf phantom_1_3_p1_slc6_amd64_gcc630.tar.gz
cat r_GEN.in | sed -e s/EVENTSNUM/${nevt}/ > r_tempo.in
cat r_tempo.in | sed -e s/RANDOMSEED/${rnum}/ > r.in
rm r_tempo.in
./phantom_1_3_p1_slc6_amd64_gcc630/phantom.exe >& log_GEN.txt
head -n `grep -n "<init>" phamom.dat | tr ":" " " | awk '{print $1+1}'` phamom.dat >> cmsgrid_final.lhe
tail -n 1 result | awk '{print $4" "$6" -1 -1"}' >> cmsgrid_final.lhe
tail -n +`grep -n "<init>" phamom.dat | tr ":" " " | awk '{print $1+3}'` phamom.dat >> cmsgrid_final.lhe
