#!/bin/bash

if [ $# != 3 ]; then
	echo "Usage: $0 g lgr lgc" >&2
	exit 1
fi

g=$1
lgr=$2
lgc=$3
n=$((g<<lgr))
gdir="g${g}_lgr${lgr}_lgc${lgc}_n${n}"
mlow=0
mhigh=$((n/5))

runm() {
	m=$1
	h=$((n-m))
	mdir="m${m}_h${h}"
	./run_m $g $lgr $lgc $m
	# Find the lowest b0 reported
	grep FINAL ${gdir}/${mdir}/k*.out | cut -d' ' -f2 | cut -d= -f2 | sort -n | head -1
}

while [ $((mhigh > $((mlow+1)) && (mhigh-mlow)*100 > mhigh)) = 1 ]; do
	mmid=$(((mhigh + mlow)/2))
	b0mid=$(runm $mmid)
	echo $mmid $b0mid
	if [ $b0mid \< 0.25 ]; then
		mlow=$mmid
	else
		mhigh=$mmid
	fi
done
echo $mlow > ${gdir}/m.out
