#! /bin/sh
# Velocity analyses for binbig cdps (as output by BinBig script).
# This script is based on demos/Velocity_Analysis/Traditional/Velan
# authored by: Dave Hale, Jack K. Cohen, John Stockwell
#
# Modified: Andre Latour, May 1 2022.
#           Only the par file for sunmocsv is created. The original
#           demos/Velocity_Analysis/Traditional/Velan also creates
#           velocity files related to migration but I deleted all that
#           since it was designed for 2D velocity fields, and the migration 
#           programs do not appear to be able to handle 3D (yet?).
#           Note that BinBig can also be used for 2D and this script    
#           will also function for that case.                           
# NOTE: Comment lines preceeding user input start with  ##
#set -x

## Usually no need to change these things        
#velpanel=bbsorted.su    # input traces from BinBig (subinbigcsv and susort)                  
velpanel=bbsortedno544.su  # input traces after Reject544                 
qlocations=qlocations.csv # cdp locations from BinBig (subinbigcsv)
seqbeg=5                 # skip this many header records in qlocations
fold=9999        	# maximum traces that will be accepted per cdp     
vpicks=stkvel.p1	# output file of cdp=, vnmo= and tnmo= values
vpickstail=stkveltail.p1	# convenient file with some values
normpow=0		# see selfdoc for suvelan
slowness=0		# see selfdoc for suvelan

## Set velocity sampling and band pass filters
nv=100			# number of velocities in scan
dv=50.0			# velocity sampling interval in scan	
fv=1000.0		# first velocity in scan

## Set interpolation type 
interpolation=akima	# choices are linear, spline, akima, mono

## set filter values
f=1,10,80,100		# bandwidth of data to pass
amps=0,1,1,0		# don't change

## number of contours in contour plot
nc=35		# this number should be at least 25
fc=.05		# This number should be between .05 to .15 for real data 
ccolor=black,grey,green,black,grey,cyan,black,grey,blue,black,grey,blue,red,red,red
perc=97		# clip above perc percential in amplitude
xcur=3		# allow xcur trace xcursion

### Get header info

nout=`sugethw ns <$velpanel | sed 1q | sed 's/.*ns=//'`
dt=`sugethw dt <$velpanel | sed 1q | sed 's/.*dt=//'`
dxout=`bc -l <<END
	$dt / 1000000
END`

## Create a null trace to use if there are no traces in the desired cdp.
sunull nt=$nout ntr=1 dt=$dxout >panel.missing


echo  "Skip Introduction? (y/n) " | tr -d "\012" >/dev/tty
read response
case $response in
n*) # continue velocity analysis


### give instructions
echo
echo
echo
echo
echo "            Instructions for Velocity Analysis."
echo
echo "  A contour semblance map will appear on the left of your screen."
echo "  A wiggle trace plot of the cdp panel being analysed will appear"
echo "  on the right as a aid in picking. Click on the semblance contour"
echo "  map to make that window active."
echo
echo "  Pick velocities by placing cursor on each peak in the"
echo "  semblance plot and typing 's'. Type 'q' when last peak is picked."
echo "  Note, this is 'blind' picking. You will not see any indication"
echo "  on the contour plot that a point has been picked."
echo
echo "  Note also, that it is best if a value of the velocity is picked "
echo "  at the beginning of the data (t=0.0 usually). The picks must "
echo "  be increasing in time. If you feel you have made an incorrect pick"
echo "  you will be given an opportunity to pick the velocities again. "
echo
echo "  Finally, a reasonable value at the latest time of the section "
echo "  should be picked. (Picking reasonable values for the top and bottom"
echo "  of the section ensures that interpolations of the velocities are"
echo "  reasonable. You don't want the wavespeed profile to start at zero "
echo "  velocity."
pause
echo
echo "  You may get some BLANK CONTOUR semblance maps. PICK THEM ANYWAY."
echo "  This is deliberate when there are no traces for a cdp location."
echo "  The bilinear interpolation of sunmocsv requires velocity functions"
echo "  that form enclosing rectangles. If you make just one pick you can"
echo "  recognize these locations later and replace them with reasonable"
echo "  velocity functions made from nearby locations."
echo
echo "  A graph of the velocity function will appear, and a prompt to" 
echo "  hit the return key will be seen in this terminal window.  You"
echo "  will then see an nmo corrected version of the cdp gather you that"
echo "  you are performing velocity analysis on." 
echo
echo "  You will be prompted in the terminal window to hit return. "
echo "  Then you will be asked if your picks are ok. This gives you "
echo "  a chance to re-pick the velocities if you do not like the velocity"
echo "  function you have obtained."

pause

;;
*y) #continue

echo
echo
echo "Beginning the velocity analysis"
echo
echo
echo

;;
esac

########################### start velocity analysis #####################


>$vpicks
>$vpickstail
seqnow=$seqbeg
seqend=`wc -l < $qlocations`

while [ $seqnow -lt $seqend ]
do
        cdp=`sed <"$qlocations" 1,"$seqnow"d | sed 1q | cut -d, -f2`
        igi=`sed <"$qlocations" 1,"$seqnow"d | sed 1q | cut -d, -f4`
        igc=`sed <"$qlocations" 1,"$seqnow"d | sed 1q | cut -d, -f5`

	ok=false
	reusepanel=false
	
	# see if panel.$cdp exists
	if [ -f panel.$cdp ]
	then
		echo  "panel.$cdp exists. Reuse? (y/n) " | tr -d "\012" >/dev/tty
		read response
		case $response in
		n*) # continue velocity analysis
			reusepanel=false
		;;
		y*) # no need to get velocity panel
			reusepanel=true
		;;
		esac
	fi

	# see if par.$cdp exists
	if [ -f par.$cdp ]
	then
		echo
		echo " file par.$cdp already exists"
		echo " indicating that cdp $cdp has been picked"
		echo

		echo  "Redo velocity analysis on cdp $cdp? (y/n) " | tr -d "\012" >/dev/tty
		read response
		case $response in
		n*) # continue velocity analysis with next cdp
			ok=true
		;;
		y*) # continue with same value of cdp
			ok=false
		;;
		esac
	fi


	# begin velocity analysis
	while [ $ok = false ]
	do
		echo "Velocity analysis for cdp $cdp. Hints: click contour plot, move mouse and type s for picks, q to quit."

		if [ $reusepanel = false ]
		then
 			suwind < $velpanel key=cdp min=$cdp max=$cdp count=$fold > panel.$cdp 
			reusepanel=true
		fi

		if [ ! -s panel.$cdp ]
		then
                   cp panel.missing panel.$cdp
		   echo "No traces for cdp $cdp.  Make at least 1 pick anyway (and then reset function in $vpicks)."
		fi

		suxwigb < panel.$cdp title="gather for cdp=$cdp  igi=$igi igc=$igc" \
				xbox=50 mpicks=mpicks.$cdp \
				perc=$perc xcur=$xcur wbox=300 &
		sugain tpow=2 < panel.$cdp |
		sufilter f=$f amps=$amps |
		suvelan nv=$nv dv=$dv fv=$fv |
		suxcontour nc=$nc f2=$fv d2=$dv xbox=450 wbox=600 \
		units="semblance" fc=$fc ccolor=$ccolor \
		label1="Time (sec)" label2="Velocity (m/sec)" \
		title="Velocity Scan (semblance) for CMP=$cdp   igi=$igi igc=$igc" \
		mpicks=mpicks.$cdp

		sort <mpicks.$cdp  -n |
		mkparfile string1=tnmo string2=vnmo >par.$cdp

		# view the picked velocity function 
		echo "Putting up velocity function for cdp $cdp"
		sed <par.$cdp '
			s/tnmo/xin/
			s/vnmo/yin/
		' >unisam.p
		unisam nout=$nout fxout=0.0 dxout=$dxout \
			par=unisam.p method=$interpolation |
		xgraph n=$nout nplot=1 d1=$dxout f1=0.0 width=400 height=700 \
			label1="Time (sec)" label2="Velocity (m/sec)" \
			title="Stacking Velocity Function: CMP=$cdp  igi=$igi igc=$igc" \
			grid1=solid grid2=solid \
			linecolor=2 style=seismic &

		pause

		# view an NMO of the panel
		echo "Hit return after nmo panel comes up"
                sunmocsv < panel.$cdp cdp=1 par=par.$cdp |
                suxwigb title="NMO of cdp=$cdp  igi=$igi igc=$igc" wbox=300 xcur=$xcur \
			perc=$perc xcur=$xcur  &

		pause  


		# check to see if the picks are ok
		echo  "Picks OK? (y/n) "  | tr -d "\012" >/dev/tty
		read response
		case $response in
		n*) ok=false ;;
		*) ok=true 
			# clean up the screen
			zap ximage
			zap xgraph
			zap xwigb
			zap xcontour
		;;
		esac

	done </dev/tty

# Combine the individual picks into a composite sunmocsv par file

	if [ $seqnow = $seqbeg ]
        then
                echo  "cdp=$cdp" | tr -d "\012" >>$vpicks
        else
	        echo  ",$cdp"  | tr -d "\012" >>$vpicks
        fi

        seqnow=`bc -l <<END
                $seqnow + 1
END`

	cat par.$cdp >>$vpickstail

	echo
	echo
	echo  "Continue with velocity analysis? (y/n) "  | tr -d "\012" >/dev/tty
	read response
	case $response in
	n*)	# if quitting set cdp to a value large enough to
		# break out of loop 
		seqnow=`expr $seqend + 1`
	;;
	y*)

	;;
	esac

done

echo >>$vpicks
cat $vpickstail >>$vpicks 

set +x

# final echo
echo "sunmocsv par file: $vpicks is ready"

exit 0
