#!/bin/bash
if [[ -z $1 ]]
    then
    cat << EOF
    $0 prog[.do] chunks

    will launch Stata under PBS-like systems, requesting [chunks] chunks
    and adjusting Stata memory allocation appropriately.

    If not specifying [chunks], uses 1 CPU and 8GB of RAM.
    Chunks are defined in units of 2CPUS:16GB of RAM
EOF
exit
    fi
chunk_default=4
#_chunks=$2
_chunks=$chunk_default

    if [[ -z $_chunks ]]
	then
	chunks=0
	cpucount=1
    else
	chunks=$_chunks
	let cpucount=${chunks}*2
    fi

let memsize=${cpucount}*8192
resources="-l ncpus=$cpucount,mem=${memsize}mb"
    prog=$1
    pbsname=$(basename $prog .do)
    pbsname=${pbsname:0:15}
    if [[ "$(basename $prog .do)" = "$prog" ]]
	then
	prog=$prog.do
    fi

# compute memsize - don't know if this is optimal
    let memsize=${cpucount}*8192


echo "
    Note that at present, $0 forces uses of $chunk_default chunks, and ignores
    the parameter, as there is no easy way to ascertain how many
    processors the DO file is requesting. This restriction may
    be lifted in the future.
"

    echo '#!/bin/bash' "
#PBS -N $pbsname
#PBS $resources
#PBS -j oe
cd $PWD
stata-mp -q -b -m$memsize $prog" | qsub

