#!/bin/sh

# -----------------------------
# external file dependencies: 2
# -----------------------------
# file	./crack
# file	./mk_crack
field2bb="awk -f $HOME/dvt/rheolef/post/scripts/fld2bb.awk"

bamg_suffix=msh

# ----------------------
# parameters
# ----------------------
hinit=0.5
nstep=8 # last will be hinit^nstep
approx=P1

usage="$0 [-nstep int=${nstep}] [-approx string=${approx}]"

while test $# -ne 0; do
    case $1 in
      -h|-help)     echo $usage >&2; exit 0;;
      -nstep)       nstep=$2; shift;;
      -approx)      approx=$2; shift;;
      -*)           /bin/echo "invalid option $1" 1>&2 ; echo $usage >&2; exit 1;;
      *)            /bin/echo "invalid option $1" 1>&2 ; echo $usage >&2; exit 1;;
    esac
    shift
done

# ----------------------
# usage: put_info i current
# ----------------------
name=crack
dat=${name}-uniform-${approx}.dat
/bin/rm -f $dat
echo "# $name uniform meshes with:"  > $dat
echo "# i n_node n_elt h err_l2 err_infty err_h1" >> $dat
echo "! file '$dat' created." >&2
cat $dat

function put_info() {
    h=$1
    current=$2
    log=$3

    n_node="`geo -noverbose -n-node $current`"
    n_elt="`geo -noverbose -size $current`"
    error_l2=`grep error_l2 $log | awk '{print $2}'`
    error_infinity=`grep error_infinity $log | awk '{print $2}'`
    error_h1=`grep error_h1 $log | awk '{print $2}'`

    line="  $i ${n_node} ${n_elt} $h ${error_l2} ${error_infinity} ${error_h1}"
    echo $line
    echo $line >> $dat
}
# ----------------------
# start loop
# ----------------------
i=1
h=${hinit}

while test ${i} -le ${nstep}; do

	current="${name}-${h}"

	mk_crack ${h} >/dev/null 2>/dev/null
	if test ! -f $current.${bamg_suffix}; then
	    echo "$0: failed at mk_crack." 1>&2
	    exit 1
	fi

        cat $current.${bamg_suffix} $name.dmn | geo -input-bamg -upgrade -geo - > $current.geo 2>/dev/null
	if test $? -ne 0; then
	    echo "$0: failed at bamg2geo." 1>&2
	    exit 1
	fi

	crack $current.geo $approx > $current-${approx}.field 2> $current-${approx}.log
	if test $? -ne 0; then
	    echo "$0: failed at crack." 1>&2
	    exit 1
	fi
	put_info $h $current $current-${approx}.log

	i=`expr $i + 1`
	h=`echo $h | awk '{print ($1)/2.}'`
done

