#!/bin/sh
set -x



#####
#	script for processing KISR Digital Data
#	THE INSTRUMENT RESPONSE MAY CHANGE IN THE FIGURE
#####

######
#	shell script to make entries for the various command files
######
#2004/05/23 09:22:05 32.53N 104.56W 5.0 4.0M A NEW MEXICO
YEAR="2008"
MO="02"
DY="15"
HR="02"
MN="04"
SEC="04"
MSEC="600"
LAT="28.986"
LON="47.532"
DEP="7.7"
MAG="1.0"
#ADDAFTERHERE


#####
#	No changes below here
#####
DEST=GOOD

if [ -d ${DEST} ]
then
	echo GOOD exists
else
	mkdir ${DEST}
fi


#####
#	for each SAC file
#	From the header get Network, Station, Component, Sample rate
#	Deconvolve to ground velocity with FREQLIMITS 0.002 0.004 FHL FHH
#	where the latter two are 0.25 Fnuquist and 0.5 f nyquist
#####

#####
#	go to the raw trace directory
#####
cd Sac


for TRACE in *.SAC
do
#####
#	convert to local machine format
#####
saccvt -I < ${TRACE} > t.sac ; mv t.sac ${TRACE}
#####
#	now get trace header parameters
#####
KSTNM=`saclhdr -KSTNM $TRACE`
KCMPNM=`saclhdr -KCMPNM $TRACE`
DELTA=`saclhdr -DELTA $TRACE`
DOY=`saclhdr -NZJDAY $TRACE`
FHH=`echo $DELTA | awk '{print 0.50/$1}' `
FHL=`echo $DELTA | awk '{print 0.25/$1}' `
#####
#	we will not rewrite the KNETWK and KHOLE in the headers with new values
#	we will just repeat the following steps in the script
#####
KNETWK=`saclhdr -KNETWK $TRACE`
if [ "${KNETWK}" = "-12345" ]
then
        NET=""
else
        NET=${KNETWK}
fi
KHOLE=`saclhdr -KHOLE $TRACE`
if [ "${KHOLE}" = "-12345" ]
then
        LOC=""
else
        LOC=${KHOLE}
fi
DOY=`saclhdr -NZJDAY $TRACE`
#####
#	get the Pole zero file - it is displacement sensitivity ct/nm
#	use the component to select short period or broadband response
#####

case ${KCMPNM} in
	BHZ|BHN|BHE) pzfile="kisr_bh.pz" ; FLL=0.002 ; FLH=0.004 ;;
	SHZ|SHN|SHE) pzfile="kisr_sh.pz" ; FLL=0.02  ; FLH=0.04  ;;
esac

cp ${pzfile} resp
gsac << EOF
r $TRACE
ch EVLA $LAT EVLO $LON EVDP $DEP
ch OCAL $YEAR $MO $DY  $HR $MN $SEC $MSEC
ch lovrok true
ch lcalda true
wh
rtr
# convert to nm/sec
transfer from polezero subtype  resp TO vel FREQLIMITS ${FLL} ${FLH}  ${FHL} ${FHH}
# convert to m/sec
div 1.0e+9
w ../${DEST}/${KSTNM}${KCMPNM}.${NET}.${LOC}.sac
quit
EOF


#####
#       deconvolve the trace
#####
done