#!/bin/bash

fout=/dev/stdout
for argv in "$@"; do
	case "$argv" in
	   -grid=*  )   fgrid=${argv#*=} ;;
	        *   )
			[[ $fgrid == "" ]] && fgrid=$argv
	        ;;
	esac
done

if [[ $# -lt 1 || ! -f $fgrid ]]; then
	cat <<EOF
Info:
	Scan 2D grids to obtain sigmaX & sigmaY
Usage:
	grid_file(x y va vr)
		or
	-grid=x
EOF
        exit
fi

###----------------------------
### grid infor
###----------------------------
read X Y <<<`awk '($1==">"){print $(NF-1), $NF; exit}' $fgrid`
read Xmin Xmax Ymin Ymax <<<`awk '($1!=">")' $fgrid | gmt gmtinfo -C | awk '{print $1, $2, $3, $4}'`
dX=`awk '($1!=">"){print $1}' $fgrid | sort -n -k1 | uniq | awk '{if(NR==1) old=$1; if(NR==2) new=$1}END{print new-old}'`
dY=`awk '($1!=">"){print $2}' $fgrid | sort -n -k1 | uniq | awk '{if(NR==1) old=$1; if(NR==2) new=$1}END{print new-old}'`

###----------------------------
### get the solution H & K
###----------------------------
awk '($1!=">"){print $1, $2, $NF}' $fgrid | gmt xyz2grd -R$Xmin/$Xmax/$Ymin/$Ymax -I$dX/$dY -Gtmp.2dgrd

###----------------------------
### estimate sigmaX and sigmaY using Gaussian function approximation
###----------------------------
function get_gaussian_width
{
	awk '{
		n++
		xx[n] = $1
		vv[n] = $2
		dw = (xx[n] > xx[1])?(xx[n] - xx[1]):(xx[1] - xx[n])
		if(dw > dwmax) dwmax = dw
		if("'$debug'" == "true")
		{
			print xx[n], dw, dwmax >"/dev/stderr"
		}
	}END{
		x0 = xx[1]
		v0 = vv[1]
		dw = xx[3] - xx[2]

		if("'$debug'" == "true")
			print dw, dwmax, x0, v0 >"/dev/stderr"

		misfitmin=1e20
		wbest = 0
		for(w=dw; w<=dwmax; w+=dw)
		{
			misfit = 0 
			for(i=1; i<=n; i++)
			{
				### half width (Full Width at Half Maximum) of Gaussian function/1.1774 = sigma
				vdif=(xx[i] - x0)^2 / 2 /(w/1.1774)^2
				if(vdif>100) vdif = 100
					misfit += (vv[i] - v0*exp(-vdif))^2
			}
			if("'$debug'" == "true")
				print w, wbest, misfit, misfitmin >"/dev/stderr"

			if(misfit < misfitmin)
			{
				misfitmin = misfit
				wbest = w
			}
		}
		print wbest
	}'
}

# debug=true
sigmaX=$(awk 'BEGIN{print '$X', '$Y'; for(i='$Xmin'; i<='$Xmax'; i+='$dX') print i, '$Y'}' | gmt grdtrack -Gtmp.2dgrd 2>/dev/null | awk '{print $1, $3}' | get_gaussian_width)
sigmaY=$(awk 'BEGIN{print '$X', '$Y'; for(i='$Ymin'; i<='$Ymax'; i+='$dY') print '$X', i}' | gmt grdtrack -Gtmp.2dgrd 2>/dev/null | awk '{print $2, $3}' | get_gaussian_width)

[[ $sigmaX == "" ]] && sigmaX="NaN"
[[ $sigmaY == "" ]] && sigmaY="NaN"

# printf "%4.1f\t%4.1f\t%4.2f\t%4.2f\n" $X $sigmaX $Y $sigmaY
printf "%4.1f\t%4.2f\n" $sigmaX $sigmaY

rm -f tmp.2dgrd
