#!/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=FT_${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 HK${fgrid#FT} ]; then
	read vpc vsc Hsol Ksol <<< `awk '(NR==1){print $(NF-2), $(NF-2)/$NF, $(NF-1), $NF}' HK${fgrid#FT}`
	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 Fin Tin <<< `awk '($1!~/^#/){if($5!=0) {fin=0; tin=0} else {h=$1*0.001; vs=$4*0.001; cosi=sqrt(1-('$rayp'*vs)^2); fin=$8; tin=(h/cosi)/vs-h/cosi/vs/(1+$7*0.01); exit}}END{print fin, tin}' ${stn#n$noise}.mod `
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

##### F/T grid
read xmin xmax dx ymin ymax dy fai tau dxi dyi <<< `awk '(NR==1){print 0, 360, $3*2, 0, 1, $4*2, $(NF-1), $NF, $3*0.1, $4*0.1}' FT_${str}.grd`
read mi mx <<< `awk '(NR>1){print $NF}' FT_${str}.grd | gmt info -C`
awk '(NR>1){print $1, $2, ($NF-('$mi'))/('$mx'-('$mi')); if($1==0) print 180, $2, ($NF-('$mi'))/('$mx'-('$mi'))}' FT_${str}.grd >FTgrid.tmp
awk '{print $1, $2, $NF; print $1+180, $2, $NF}' FTgrid.tmp | gmt xyz2grd -R$xmin/$xmax/$ymin/$ymax -I$dx/$dy -rg -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 -JPa3.2c -BwsNe+t"@~\152@~=$fai  @~\164@~=$tau" -Bxa45g45+l"@~\152@~ (@~\260@~)" -Bya0.5f0.5g0.5+l"@~\164@~ (s)" -Cplot.cpt plot.grd -X3 -Y8 -P -K >${output}
echo 0 0.5 | awk '{print $1, $2, "9,1,black TC", $2"s"}' | gmt pstext -F+f+j -D0c/-0.02 -N -R -J -O -K  >> $output
echo 0 1.0 | awk '{print $1, $2, "9,1,black TC", $2"s"}' | gmt pstext -F+f+j -D0c/-0.02 -N -R -J -O -K  >> $output

echo $fai $tau | gmt psxy -R -J -S+0.1 -W1.0p,white -O -K >> ${output}
if [ -f ${stn#n$noise}.mod ]; then
	echo $Fin $Tin | gmt psxy -Sc0.03 -W1p,red -Gred -R -J -O -K >> $output
fi
# echo 165 $ymax | awk '{print $1, $2-0.05, "10,1,black RB", "(i)" }' | gmt pstext -F+f+j -D0c/0c -N -R -J -O -K  >> $output

gmt psscale -Cplot.cpt -Bxa0.5f0.25 -O -K -Dx0.6/-0.3/1.5/.15h >> ${output}

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

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

