#!/bin/bash
#
#  This runs a quick survey over all of the processes to determine
#  which channels in each process are important. This must be run
#  before you call integrate since it sets up important information
#  about each process. Must be run from main directory or bin directory
#
#  Usage: survey compression parallel [name]
#
#  
#   First we need to get into the main directory
#
if [[  ! -d ./bin  ]]; then
    cd ../
    if [[ ! -d ./bin ]]; then
	echo "Error: survey 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
# Begin Local versions
# set dirbin = /home/tstelzer/bin/MG_ME
# End Local versions 
qsub=qsub

if [[  "$1" == ""  ]]; then
    echo 'Enter 1 for parallel 0 for serial run' 
     read p 
else
     p=$1
fi
if [[  $p -gt 0 ]]; then
   if [[  "$2" == ""  ]]; then
    echo 'Enter name for jobs on pbs queue'
       read n
   else
       n=$2
   fi
fi
echo "Compiling libraries"
if [[ -d Source ]]; then
    echo "Compiling Libraries" >& status
    cd Source
    make ../bin/sum_html >/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
    for i in P*_* ; do
	r=`expr $r + 1`
    done
#    echo "Using random number seed offset = " $r
    echo "r=$r" >& randinit
    echo "Working on subprocess:"
    for i in P*_* ; do
	cd $i
	echo -n "   " $i "   "
	rm -f ajob* >& /dev/null
	rm -f wait.ajob* >& /dev/null
	rm -f run.ajob* >& /dev/null
	rm -f done.ajob* >& /dev/null
	make gensym > /dev/null
	./gensym >& gensym.log
	chmod +x ajob*
	make madevent > /dev/null
	for j in ajob*  ; do
	    touch wait.$j
	    if [[ $p == 1 ]]; then
		$qsub -N $n $j >> ../../running_jobs
	    else
	        echo "running $j" #NT
	        time nice ./$j  # >/dev/null
	        exit             #NT
		../../bin/sum_html >/dev/null
	    fi
	done
	cd ..
	if [[ $p == 0  ]]; then 
	    ../bin/sum_html 
	fi
    done
    if [[ $p == 1 ]]; then
	$dirbin/monitor $n $3
	../bin/sumall
    fi
    cd ../
else
    echo "Error could not find SubProcesses"
    exit
fi
$dirbin/gen_crossxhtml-pl $3
