#!/bin/bash


rayp=5.E-5

awk 'BEGIN{
	for(baz=0; baz<360; baz+=5)
		print baz, '$rayp', 0., 0.
}' > tmp.geom

cat <<eof >raysum-params
# Multiples: 0 for none, 1 for Moho, 2 for all first-order
0
# Number of samples per trace
3000
# Sample rate (seconds)
0.01
# Gaussian pulse width (seconds)
1
# Alignment: 0 is none, 1 aligns on primary phase (P or S)
1
# Shift of traces -- t=0 at this time (sec)
5
# Rotation to output: 0 is NS/EW/Z, 1 is R/T/Z, 2 is P/SV/SH
1
eof

cat <<eof >tmp.mod
40000 2600 6400 3700  1  0   0   0  0   0   0
0000  3500 8100 4500  1  0   0   0  0   -90   0
eof
read tPs tA tF <<< `awk '($1 !~ /^#/)' tmp.mod | awk '($1!=0)' | awk '(NR==1){h=$1;vp=$3; vs=$4; x=h/sqrt(1-(vs*'$rayp')^2); dt=x/vs-x/vp; printf("%3.1f\t%3.1f\t%3.1f",dt, dt-2, dt+1.5)}'`

awk 'BEGIN{
	for(gama=0; gama<=35; gama+=1)
		print gama
}' |\
while read gam; do
	awk -v gam=$gam '{if(NR==2) $NF=gam; print $0}' tmp.mod > tmp1.mod
	seis-spread tmp1.mod tmp.geom sample.ph sample.arr sample.tr P >/dev/null
	awk '($1 !~ /^#/ && NF>=3){
		if(FNR == NR)
		{
			if(NF == 4) baz[++n] = $1	
		}else
		{
			if(ntr == 0)
			{
				ntr=$1; npts=$2; dt=$3; align=$4; t0=-$5+dt; 
				ipt = 0 
			}else
			{
				ipt = (ipt==npts)?1:(ipt +1)

				if(ipt == 1)
				{
					t =  t0
					tracei ++
					fname = tracei ".tr"
				}
				else 
				
					t += dt

				print baz[tracei], t, $1, $2, $3 >fname
			}
		}
	}' tmp.geom sample.tr

	for file in [1-9]*.tr
	do
		[[ ! -f $file ]] && continue
		n=${file%.tr}
		baz=`awk '(NR==1){printf("%d", $1)}' $file`
		epsilon=`awk -v maxt=-10000000 '($2>='$tA' && $2<='$tF'){if($4>maxt){maxt=$4; maxr=$3}}END{x=atan2(-maxt, maxr)*180/3.141592653; printf("%d\n", (x>0)?int(x+0.5):int(x-0.5))}' $file`
		echo $gam $baz $epsilon
	done
	rm -f sample.ph sample.arr sample.tr
done | sort -n -k1 -k2 > epsilon_by_raysum.lst
rm -f [1-9]*.tr tmp.mod tmp1.mod tmp.geom raysum-params