#!/bin/bash
if [ $# -lt 2 ]; then
	echo "argv1: stn"
	echo "argv2: alpha"
	exit
fi
stn=$1
alpha=$2
noise=$3

str=${stn}.g${alpha}
rayp=0.0576
vpm=8.1

fgrid=HK_${str}.grd
output=${fgrid%.grd}.ps

font="12p,31,black"
font_title="12p,29,black"
gmt set PS_MEDIA A4 PROJ_LENGTH_UNIT cm \
	FORMAT_GEO_MAP ddd \
        MEASURE_UNIT inch \
	MAP_FRAME_TYPE plain MAP_FRAME_PEN 0.8p,0 \
	MAP_TICK_LENGTH 0.1c MAP_TICK_PEN 0.8p \
	FONT_ANNOT $font MAP_ANNOT_OFFSET 0.06c \
	FONT_LABEL $font MAP_LABEL_OFFSET 0.12c \
	FONT_TITLE $font_title MAP_TITLE_OFFSET 0.1c \
	PS_CHAR_ENCODING Standard+

########################### get tPs
if [ -f ${fgrid} ]; then
	read vpc vsc Hsol Ksol <<< `awk '(NR==1){print $(NF-2), $(NF-2)/$NF, $(NF-1), $NF}' ${fgrid}`
	read tPs tPpPs tPpSs <<< `echo $rayp $Hsol $vsc $Ksol | awk '{p1=sqrt(1/($3*$3)-($1*$1)); p2=sqrt(1/(($4*$3)*($4*$3))-($1*$1)); printf("%.2f\t%.2f\t%.2f\n", $2*(p1-p2), $2*(p1+p2), 2*$2*p1)}'`
else
	echo "no HK grid available"
	exit
fi
if [ -f ${stn#n$noise}.mod ]; then
	read Hin Kin <<< `awk '($1!~/^#/ && $1!=0)' ${stn#n$noise}.mod | awk '(NR==1){printf("%d\t%.3f\n", $1*0.001, $3/$4)}'`
fi

########################### 
read stn stlo stla stel <<< `saclst kstnm stlo stla stel f decon.r.*.${str} | awk '(NR==1){print $2, $3, $4, $5}'`
gmt makecpt -C255,230,220,200,180,160,140,120,100 -T0,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1 -D  > plot.cpt

##### H-K grid
read xmin xmax dx ymin ymax dy moho kappa dxi dyi <<< `awk '(NR==1){print $3, $4, $5, $6, $7, $8, $10, $11, $5*0.1, $8*0.1}' HK_${str}.grd`
read sigmaH sigmaK <<< `HK-sigma.sh -grid=HK_${str}.grd`
awk '(NR>1){print $1, $2, $NF}' HK_${str}.grd | gmt xyz2grd -R$xmin/$xmax/$ymin/$ymax -I$dx/$dy -Gplot.grd
gmt grdsample plot.grd -I$dxi/$dyi -Gplot_new.grd; mv -f plot_new.grd plot.grd
gmt grdimage  -R$xmin/$xmax/$ymin/$ymax -JX1.6/1.6 -X3 -Y8 -BWSne+t"H=$moho@~\261@~$sigmaH  @~\153@~=$kappa@~\261@~$sigmaK" -Bx10+l"H (km)" -Bya0.1+l"@~\153@~" -Cplot.cpt plot.grd -P -K > ${output}
echo $moho $kappa $sigmaH $sigmaK | gmt psxy -Exy+p1p,white -W1p,white -R -J -O -K >> $output
if [ -f ${stn#n$noise}.mod ]; then
	echo $Hin $Kin | gmt psxy -Sc0.04 -W1p,red -Gred -R -J -O -K >> $output
fi

gmt psscale -Cplot.cpt -Bxa0.5f0.25 -O -K -Dx0.8/-0.5/1.6/.15h >> ${output}

ps2pdf $output
rm -f tmp.xyz $output gmt.* plot.cpt plot.grd

spdf.sh ${output%.ps}.pdf

