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

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

function usage()
{
		echo "Usage: `basename $0` [-x x-center] [-X x-stddev] [-y y-center] [-Y y-stddev]"
		echo "       [-n number of points] [-g grav] [-s grav-stdev]"
		echo "       [-z height] [-c datacode] [-d seed] [-h] outputfile"
}

function showhelp()
{
		usage
		echo
		echo " This script creates an template observation file named <outputfile> for"
		echo " invert, with data points placed at 2D normally distributed locations."
		echo
		echo " - Options -x and -X define the expectation (\"mean\") and standard deviation"
		echo "     of the locations in x-direction"
		echo " - Options -y and -Y are similar to -x and -X for y-direction."
		echo " - Options -n number of points to be created."
		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."
		echo " - Option -d initializes the random number generator with a (repeatable)"
		echo "     seed (positive integer)."
}

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

X0=0
SX=1
Y0=0
SY=1
NP=1
G0=0
S0=1
Z0=0
C0=0
SEED=-1

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

while getopts "x:X:y:Y:n:g:s:z:c:d:h" OPTIONS ; do
		case $OPTIONS in
				x ) X0=$OPTARG;;
				X ) SX=$OPTARG;;
				y ) Y0=$OPTARG;;
				Y ) SY=$OPTARG;;
				n ) NP=$OPTARG;;
				g ) G0=$OPTARG;;
				s ) S0=$OPTARG;;
				z ) Z0=$OPTARG;;
				c ) C0=$OPTARG;;
				d ) SEED=$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 x0=$X0 -v sx=$SX -v y0=$Y0 -v sy=$SY -v np=$NP -v g0=$G0 -v s0=$S0 -v z0=$Z0 -v c0=$C0 -v seed=$SEED '
function normdist (e,s,  __v1,__v2,__rr,__f) {
	if (have_spare==0) {
		do {
			__v1=2.*rand()-1.;
			__v2=2.*rand()-1.;
			__rr=__v1*__v1+__v2*__v2;
		}
		while (__rr>1. ||  __rr==0.);

		__f=sqrt(-2.*log(__rr)/__rr);
		spare=__v1*__f;
		have_spare=1;
		return e + s*__v2*__f;
	}
	else {
		have_spare=0;
		return e + s*spare;
	} 
}

BEGIN {
	if (np<1) np=1;

  if (seed<0) {
    srand();
  }
  else {
    srand(seed)
  }

	for (n=1; n<=np; ++n) {
		printf("%-4s%12.3f%12.3f%11.3f%11.3f%11.3f%6d\n", n,normdist(x0,sx),normdist(y0,sy),g0,s0,z0,c0);
	}
}' > "$FILE"
