#!/bin/sh
#
# Create a directory which is a subdirectory of the current one
# and is unique
#
 set -- `getopt e:hN:M:p: $*`
 if [ $? -ne 0 ] ; then
    cat <<!

Usage: rfluka -e <fluka executable> -N <run N> -M <final run N>
       -p <pemf> <input file>

!
    exit 2
 fi
#

 NUM=0
 MAX=5

 while [ $# -gt 0 ] ; do 
    case $1 in
    -h)
cat <<!

       rfluka [-e <fluka executable> -N <number of previous run>
              -M <number of final run> -p <name of the pemf file>
              -h (print this help)] <input file>

       rfluka runs fluka. A unique name subdirectory is created and
       the program is run from there. Links are created to the files
       in the parent directory. After a successful run of fluka all
       the temporary links are removed and the newly created files
       are copied to the parent directory with the prefix
       <input_name><cycle number>.
       This operation is repeated from the cycle after the one indicated
       on the -N option (default 0) to the one indicated on the -M
       option (default 5). 

       -e<file>  name of the fluka executable to be run

       -N<run N> number of the previous run

       -M<final run N>  final run number

       -p<pemf>  name of the pemf file. The suffix .pemf will be added
                 automatically. The default is 
                 /user2/fluka/libec_thihecufealw_10t.

       -h        print this help file

       <input file> input file for fluka, without .inp


!
	exit
	;;
    -e) 
       EXE=${2}
       shift 2
       ;;
    -N) 
       NUM=${2}
       shift 2
       ;;
    -M) 
       MAX=${2}
       shift 2
       ;;
    -p) 
       PEMF=${2}
       shift 2
       ;;
    --)
       shift
       break
       ;;
    esac
 done
#

 while [ $NUM -lt $MAX ] ; do 

    NUM=`expr $NUM + 1`

#  Export a variable with the NUM value
    FLUKA_CUR_RUN="$NUM"
    export FLUKA_CUR_RUN

    if [ $NUM -lt 10 ] ; then
       PST=${NUM}
    elif [ $NUM -lt 100 ] ; then
       PST=${NUM}
    elif [ $NUM -lt 1000 ] ; then
       PST=${NUM}
    else
       PST=${NUM}
    fi

    NUP=`expr $NUM`
    if [ $NUP -lt 10 ] ; then
       PSP=000${NUP}
    elif [ $NUP -lt 100 ] ; then
       PSP=00${NUP}
    elif [ $NUP -lt 1000 ] ; then
       PSP=0${NUP}
    else
       PSP=${NUP}
    fi
# Start run
   
cp /afs/slac/g/theory/simu/vol1/rouven/batchMG/Events125MeV3pt3GeV_many/W_3pt3GeV_Ap125MeV_farm_${PST}_unweighted_events.lhe.gz aprime.lhe.gz

fs=`ls -l aprime.lhe.gz | awk '{print $5}' `

if [ $fs -gt 6000 ] ; then
gunzip -f aprime.lhe.gz
aprime > aprime.dat
sdrun
/afs/slac/package/cernlib/cern/2003/bin/pawX11 -b recon
selectap
cp apsel.dat ~tvm/hps/ap/ap3.3gev125mevsel_${PSP}.dat
fi

done
