#! @SH_JOB@
if test x"`echo $1 | egrep '^[0-9]*$'`" = x; then
    echo "Syntax: $0 <num-split> [mpb arguments...]" 1>&2
    exit 1
fi

tmpname=/tmp/mpb-split.$$.tmp # unique temporary filename
subprocesses="" # keep a list of the subprocess ids launched

# If a SIGINT or SIGHUP is received, kill subprocesses and delete temp. files:
trap 'echo "killing subprocesses: $subprocesses"; kill -9 $subprocesses; rm -f $tmpname.*; exit 1' 1 2

# Run num-split instances of mpb, each with a chunk of k-points, with
# the first chunk going to stdout and the rest going to temporary files
# to be output later.
./mpb interactive?=false k-split-index=0 k-split-num=$* &
subprocesses="$subprocesses $!"
i=0
while test `expr $i \< $1` = 1; do
    ./mpb interactive?=false k-split-index=$i k-split-num=$* > $tmpname.$i &
    subprocesses="$subprocesses $!"
    i=`expr $i + 1`
done

# After all mpb processes have finished, concatenate their outputs in order.
wait
i=0
while test `expr $i \< $1` = 1; do
    cat $tmpname.$i
    rm -f $tmpname.$i
    i=`expr $i + 1`
done
