#!/bin/bash
#
#  After a survey has been run and created results.dat to determine
#  which channels in each process are important, this routine can 
#  run to give an accurate integration of the cross section.
#
#  Usage: integrate accuracy parallel [name]
#
#  
#   First we need to get into the main directory
#
if [[  ! -d ./bin  ]]; then
    cd ../
    if [[ ! -d ./bin ]]; then
	echo "refine 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/internal
# Begin Local versions
# set dirbin = /home/tstelzer/bin/MG_ME
# End Local versions 
qsub=qsub

if [[  "$1" == ""  ]]; then
    echo 'Desired accuracy (< 1), or number of unweighted events (>1)' 
    read a 
else
    a=$1
fi
if [[  "$2" == ""  ]]; then
    echo 'Enter 1 for parallel 0 for serial run' 
     read p 
else
     p=$2
fi
np=1
if [[  $p -gt 0 ]]; then
   if [[  "$3" == ""  ]]; then
    echo 'Enter name for jobs on pbs queue'
       read n
   else
       n=$3
   fi
   if [[ $# -gt 3 ]]; then
      np=$4
   fi
fi
#if [[ -d Source ]]; then
#    echo "Compiling Libraries" >& status
#    cd Source
#    make ../bin/sum_html >& /dev/null
#    make ../bin/gen_ximprove >&/dev/null
#    make all >& /dev/null
#    cd ..
#else
#    echo 'Error Source directory not found'
#    exit
#fi
if [[ -d SubProcesses ]]; then
    if [[  $p -gt 0 ]]; then    
	echo "Creating Jobs" >& status
    else
	echo " " >& status
    fi
    cd SubProcesses
    r=0
    if [[ -e randinit ]]; then
	source ./randinit
    fi
#    echo "Using random number seed offset = " $r
    for i in `cat subproc.mg` ; do
	cd $i
	echo $i
#	rm -f ajob* >& /dev/null	
#	rm -f wait.ajob* >& /dev/null
#	rm -f run.ajob* >& /dev/null
#	rm -f done.ajob* >& /dev/null
	echo $a $np F | ../../bin/internal/gen_ximprove >& gen_ximprove.log

	if [[ -e ajob1 ]]; then
#	    make madevent > /dev/null
	    chmod +x ajob*
	    for j in ajob*  ; do
	      touch wait.$j
	      if [[ $p == 1 ]]; then
		$qsub -N $n $j>> ../../running_jobs
	      else
		nice ./$j > /dev/null
		../../bin/internal/sum_html >/dev/null
	      fi
	    done
	fi

	cd ..
	if [[ $p == 0  ]]; then 
	    ../bin/internal/sum_html 
	fi
    done
#    echo "r=" $r >& randinit
else
    echo "Error unable to find SubProcesses directory"
    exit
fi
if [[ $p == 1 ]]; then
    $dirbin/monitor $5
fi
    cd ../SubProcesses
    echo "Combining runs" >& ../status
    ../bin/internal/sumall
cd ..
$dirbin/gen_crossxhtml-pl $5
