#!/bin/bash
#
# This script creates an template observation file named <outputfile> for
# invert, with data points placed at a regular grid.
#
# Dependencies on external programs:
#  gawk
#
# (C) 2008 Peter L. Smilde
#

#==============================================================================

function usage()
{
		echo "Usage: `basename $0` [-x xmin] [-X xmax] [-n number of x lines]"
	  echo "       [-y ymin] [-Y ymax] [-m number of y lines] [-g grav] [-s stdev]"
		echo "       [-z height] [-c datacode] [-h] outputfile"
}

function showhelp()
{
		usage
		echo
		echo " This script creates an template observation file named <outputfile> for"
		echo " invert, with data points placed at a regular grid."
		echo
		echo " - Options -x,-X define the range of of x-grid lines. If -n is less or equal"
		echo "     only one grid line is created at the mean range coordinates."
		echo " - Options -n number of grid lines in x-direction."
		echo " - Options -y, -Y and -m are similar to -x, -X and -n for y-direction."
		echo " - Option -g defines the common gravity value."
		echo " - Option -s defines the common standard deviation of the gravity value."
		echo " - Option -z defines the common observation point height."
    echo " - Option -c defines the common data code value."
}

#==============================================================================

XMIN=0
XMAX=0
NX=1
YMIN=0
YMAX=0
NY=1
G0=0
S0=1
Z0=0
C0=0

#-------------------------
# Get commandline options
#-------------------------

while getopts "x:X:n:y:Y:m:g:s:z:c:h" OPTIONS ; do
		case $OPTIONS in
				x ) XMIN=$OPTARG;;
				X ) XMAX=$OPTARG;;
				n ) NX=$OPTARG;;
				y ) YMIN=$OPTARG;;
				Y ) YMAX=$OPTARG;;
				m ) NY=$OPTARG;;
				g ) G0=$OPTARG;;
				s ) S0=$OPTARG;;
				z ) Z0=$OPTARG;;
				c ) C0=$OPTARG;;
				h ) showhelp; exit 0;;
				\? ) usage; exit 1;;
				* ) usage; exit 0;;
		esac
 
done
shift $(($OPTIND-1))

if [ $# -lt 1 ] ; then
		echo "ERROR: please enter the name of the output file."
		usage; exit 1 
else
		FILE="$1"
fi

LANG=C;gawk -v xmin=$XMIN -v xmax=$XMAX -v nx=$NX -v ymin=$YMIN -v ymax=$YMAX -v ny=$NY -v g0=$G0 -v s0=$S0 -v z0=$Z0 -v c0=$C0 '
BEGIN {
	if (nx<1) nx=1;
	if (nx==1) {
		xmin=(xmin+xmax)/2;
		xmax=xmin;
		dx=0.;
 	}
	else {
		dx=(xmax-xmin)/(nx-1)
	};

	if (ny<1) ny=1;
	if (ny==1) {
		ymin=(ymin+ymax)/2;
		ymax=ymin;
		dy=0.
	}
	else {
		dy=(ymax-ymin)/(ny-1)
	};

	n=1;
	x=xmin;
	for (ix=0; ix<nx; ++ix) {
		y=ymin;
		for (iy=0; iy<ny; ++iy) {
			printf("%-4s%12.3f%12.3f%11.3f%11.3f%11.3f%6d\n", n++,x,y,g0,s0,z0,c0);
			y+=dy;
		}
		x+=dx;
	}
}' > "$FILE"
