#! /bin/csh -f

# swin.csh -s YYYY DDD HH MM LL PL or MBN LL PL -o opt_file
#	-id XXXX [-n net] [-p setup_path] [-ico IC offset]

#	global or regional processing of a given network
#	using preset setting in an option file

#	-s session end time (YYYY DDD HH MM) and session
#	   length (LL in min), and predicted orbit length
#	   (PL in min) from session end time,  or
#	   min before now (MBN) in UT time as session end time
#	   if only 3 session parameters are given

#	-o option file, which located under the setup path (-s)
#	-id 4 character network ID
#	-n Nth network in option file, default = 1
#	-p setup path, default = /usr/local/processing/gamit_setup
#	-ico IC offset in min, default = 0

# by pfang@ucsd.edu Feb. 99

# set defaults
set i10 = 10; set i30 = 30; set i60 = 60; set i100 = 100; set i1440 = 1440
set gs = /usr/local/processing/gamit_setup
set netn = 1
set ico = 0

if ($#argv < 1) then
	sed -e "1 d" -e "s/#//" -e "/pfang/q" $0
	exit
endif

set runarg = ($argv)
# -------------------------------------------
echo "swin.csh: Sort user options"
# -------------------------------------------
foreach a ($argv)
switch($a)
	case -s:
		set sess = (`echo $argv | cut -d- -f2`); shift sess
		if ($#sess < 4) then
			set ydoyhm = (`date -u +"%Y %j %H %M"`)
			set mjd = `mjd2ydoy $ydoyhm[1] $ydoyhm[2]`
			@ min = $ydoyhm[3]*60 + $ydoyhm[4] - $sess[1]
			while ($min < 0)
				@ min += $i1440
				@ mjd--
			end
			set ydoy = (`mjd2ydoy $mjd`)
			@ hh = $min / $i60
			@ mm = $min % $i60
			set sess = ($ydoy $hh $mm $sess[2] $sess[3])
		endif
		breaksw
	case -o:
		set optf = ($argv[2])
		breaksw
	case -id:
		set nid = ($argv[2])
		breaksw
	case -n:
		set netn = ($argv[2])
		breaksw
	case -p:
		set gs = ($argv[2])
		breaksw
	case -ico:
		set ico = ($argv[2])
		breaksw
endsw
shift
end

set sol_type = (`grep "#SOL_TYPE" $gs/$optf`); shift sol_type
# -------------------------------------------
echo "swin.csh: set session IC time, end time, and predicted orbit end time"
# -------------------------------------------
# st:=start, ic:=IC,    nd:=end,  pe:=predicted orbit end
#  |----------|----------|---...---|
set ydoynd = ($sess[1] $sess[2])
set mjdnd = (`mjd2ydoy $ydoynd`)
# round it to 0 or 30 min
@ minnd = ((($sess[3] * $i60) + $sess[4]) / $i30) * $i30
@ hhnd = $minnd / $i60; if ($hhnd < 10) set hhnd = "0$hhnd"
@ mmnd = $minnd % $i60; if ($mmnd < 10) set mmnd = "0$mmnd"

set mjdst = $mjdnd
@ minst = $minnd - $sess[5]
while($minst < 0)
	@ minst += $i1440
	@ mjdst--
end
set ydoyst = (`mjd2ydoy $mjdst`)
@ yyst = $ydoyst[1] % 100; if ($yyst < 10) set yyst = "0"$yyst
@ yr1st = $ydoyst[1] % 10
set gwkst = (`gwk2ydoy $ydoyst`)
@ hhst = $minst / $i60; if ($hhst < 10) set hhst = "0$hhst"
@ mmst = $minst % $i60; if ($mmst < 10) set mmst = "0$mmst"

@ mjdic = $mjdnd + ($ico / $i1440)
if ($sol_type == 'ultra') then
	@ minic = $minnd - ( ($sess[5] * 1) / 3)
else
	@ minic = $minnd - ($sess[5] / 2)
endif

while($minic < 0)
	@ minic += $i1440
	@ mjdic--
end
set ydoyic = (`mjd2ydoy $mjdic`)
@ hhic = $minic / $i60; if ($hhic < 10) set hhic = "0$hhic"
@ mmic = $minic % $i60; if ($mmic < 10) set mmic = "0$mmic"

set mjdpe = $mjdnd
@ minpe = $minnd + $sess[6]
while($minpe > $i1440)
	@ minpe -= $i1440
	@ mjdpe++
end
set ydoype = (`mjd2ydoy $mjdpe`)
@ yype = $ydoype[1] % 100; if ($yype < 10) set yype = "0"$yype
@ hhpe = $minpe / $i60; if ($hhpe < 10) set hhpe = "0$hhpe"
@ mmpe = $minpe % $i60; if ($mmpe < 10) set mmpe = "0$mmpe"

# directory naming convention
# orbneop hrlyg.DDDHHMM where DDDHHMM are session start date/time
# working nnnn.DDDHHMM where nnnn stands for networkID

pp_orbneop.csh -s $ydoyst $hhst $mmst $sess[5] -o $optf -gs $gs -ic $ydoyic $hhic $mmic > /dev/null &

# -------------------------------------------
echo "swin.csh: prepare working space and rinex files"
# -------------------------------------------
set hostn = (`hostname | tr '.' ' '`)
set work = (`grep "#WORK_PATH" $gs/$optf`); shift work
set work = "$work/$nid[1].$ydoyst[2]$hhst$mmst"
set work = `echo $work[1] | sed -e "s/HOSTN/$hostn[1]/g"`
set work = `echo $work[1] | sed -e "s/YYYY/$ydoyst[1]/g"`
set work = `echo $work[1] | sed -e "s/DDD/$ydoyst[2]/g"`
if (! -e $work) mkdir $work
cd $work
if ($status) then
	echo "$0 : cd $work[1] failed"
	goto deregister
endif
chmod +w * >& /dev/null
/bin/rm * >& /dev/null

echo "$0 $runarg" > footprint.bat
echo "pp_orbneop.csh -s $ydoyst $hhst $mmst $sess[5] -o $optf -ic $ydoyic $hhic $mmic" >> footprint.bat

switch($sol_type)
case hrtr:
case hr2g:
case ptst:
	load_rnx.pl -s $sess -o $optf -n $netn &
	echo "load_rnx.pl -s $sess -o $optf -n $netn" >> footprint.bat
	breaksw
case hrlyr:
	load_rnx.pl -s $sess -o $optf -n $netn &
	echo "load_rnx.pl -s $sess -o $optf -n $netn" >> footprint.bat
	breaksw
case pre_rap:
case rapd2:
case rapid:
	load_rnx.pl -s $sess -o $optf -p 75 -n $netn &
	echo "load_rnx.pl -s $sess -o $optf -p 75 -n $netn" >> footprint.bat
	breaksw
case reg:
	load_rnx.pl -s $sess -o $optf -n $netn &
	echo "load_rnx.pl -s $sess -o $optf -p 1 -n $netn" >> footprint.bat
	breaksw
default:
	load_rnx.pl -s $sess -gs $gs -o $optf -n $netn &
	echo "load_rnx.pl -s $sess -gs $gs -o $optf -n $netn" >> footprint.bat
	#pp_obs.csh -s $ydoyst $hhst $mmst $sess[5] -o $optf -n $netn &
	#echo "pp_obs.csh -s $ydoyst $hhst $mmst $sess[5] -o $optf -n $netn" >> footprint.bat
	breaksw
endsw


# -------------------------------------------
echo "swin.csh: link excutables and session files"
# -------------------------------------------
set elink = (`grep "#EXEC_LINK" $gs/$optf`); shift elink
$elink

set link_tab = (`grep "#LINK_TAB" $gs/$optf`); shift link_tab
$link_tab -s $ydoyst $hhst $mmst $sess[5] -o $optf -gs $gs

set stn_info = (`grep "#STN_INFO" $gs/$optf`); shift stn_info
echo "$nid[1] pgga" > station.info
sed -e "1,1 d" $gs/$stn_info >> station.info

set backup = (`grep "#BACK_UP" $gs/$optf`); shift backup

# -------------------------------------------
echo "swin.csh: set up sestbl, sittbl, and station.info"
# -------------------------------------------
set strategy = (`grep "#STRATEGY" $gs/$optf`); shift strategy
set decim_pre = (`grep "#DECIM_PRE" $gs/$optf`); shift decim_pre
set decim_post = (`grep "#DECIM_POST" $gs/$optf`); shift decim_post
set tidal = (`grep "#TIDAL" $gs/$optf`); shift tidal
set nzen = (`grep "#NZEN" $gs/$optf`); shift nzen
set ngrad = (`grep "#NGRAD" $gs/$optf`); shift ngrad
set elev_cut = (`grep "#ELEV_CUT" $gs/$optf`); shift elev_cut
set aphs_mod = (`grep "#APHS_MOD" $gs/$optf`); shift aphs_mod
set tropo_mfn = (`grep "#TROPO_MFN" $gs/$optf`); shift tropo_mfn
set removec = (`grep "#REMOVEC" $gs/$optf`); if($status != 1) shift removec

set sestbl = (`grep "#SESTBL" $gs/$optf`); shift sestbl
set zen_yn = (`grep "Zenith Delay Estimation" $gs/$sestbl`)
if ($zen_yn[5] == 'NO') then
	@ nzen = 0
else
	@ nzen = $sess[5] / $nzen[1] + 1
endif
echo -n "" > sed.inp
if ($strategy == 'postfit') then
	echo "s/AUTCLN Postfit =..../AUTCLN Postfit = YES/" >> sed.inp
else
	echo "s/AUTCLN Postfit =..../AUTCLN Postfit = NO/" >> sed.inp
endif
echo "s/pre decimation factor =.../pre decimation factor = $decim_pre/" >> sed.inp
echo "s/Decimation Factor =.../Decimation factor = $decim_post/" >> sed.inp
echo "s/Antenna Model =...../Antenna Model = $aphs_mod/" >> sed.inp
echo "s/Number Zen =.../Number Zen = $nzen/" >> sed.inp
if ($ngrad > 0) then
	echo "s/Atmospheric gradients =../Atmospheric gradients = Y/" >> sed.inp
	echo "s/Number grad =.../Number grad = $ngrad /" >> sed.inp
else
	echo "s/Atmospheric gradients =../Atmospheric gradients = N/" >> sed.inp
	echo "s/Number grad =.../Number grad = $ngrad /" >> sed.inp
endif
echo "s/Tide .odel =.../Tide Model = $tidal/" >> sed.inp
switch($nid[1])
	case grad:
		echo "s/Gradient Constraints = ..../Gradient Constraints = 0.001/" >> sed.inp
		echo "s/Gradient Variation = ........./Gradient Variation = 0.001 100./" >> sed.inp
	breaksw
endsw
if ($sol_type[1] == 'ultra') then
	echo "s/Wobble Con = ......../Wobble Con = 0.01 0.001/" >> sed.inp
	echo "s/UT1 Con = ............/UT1 Con = 0.00001 0.01/" >> sed.inp
endif

sed -f sed.inp $gs/$sestbl > sestbl.

set sittbl = (`grep "#SITTBL" $gs/$optf`); shift sittbl
(echo $elev_cut[1] $aphs_mod[1] $tropo_mfn $nzen; cat $gs/$sittbl) | \
awk 'NR == 1 {cut = $1; phs = $2; map = $3 "  " $4; zen = $5} \
NR > 1 && NR < 4 {print} \
NR > 3 {printf "%s %4.1f   %s",substr($0,1,59),cut,phs; \
printf "%s %s",substr($0,72,31),map; \
printf "%s %2.2d%s\n",substr($0,114,21),zen,substr($0,138,25)}' > sittbl.

set one_path = (`grep "#ONE_PATH" $gs/$optf`); shift one_path
set one_path = "$one_path[1]/$sol_type[1].$ydoyst[2]$hhst$mmst"
set one_path = `echo $one_path[1] | sed -e "s/HOSTN/$hostn[1]/g"`
set one_path = `echo $one_path[1] | sed -e "s/YYYY/$ydoyst[1]/g"`

set sfx = "$yr1st.$ydoyst[2]"
is_ready -f $one_path[1]/sess.done
cp $one_path[1]/lcomm$sfx l$nid[1]$sfx
cp $one_path[1]/session.info .
foreach c (e j g)
	/bin/cp $one_path[1]/$c[1]comm$sfx $c[1]pgga$sfx
end

is_ready -f pp_obs.csh.done

# -------------------------------------------
echo "swin.csh: pre-processing"
# -------------------------------------------
echo "setting nav to e????.$ydoyst[2]"
echo "if getting a set: No match error here from swin, "
echo "it may be getting last years e file from orbneop dir"
echo "check /net/host/working/orbneop/reg.ddd0000"
echo "also check if auto file at /archive/garner/rinex"
set nav = (e?????.$ydoyst[2])
set pno = (`head -1 station.info`)

echo "makexp $pno[1] $pno[2] $nav[1] $ydoyst[1] $ydoyst[2] $yr1st[1]" >> footprint.bat

makexp $pno[1] $pno[2] $nav[1] $ydoyst[1] $ydoyst[2] $yr1st[1] << eof_makexp
$yyst[1]
$ydoyst[2]
99
$nav[1]
eof_makexp
if ($status) goto deregister

makex $nid[1].makex.batch            
if ($status) goto deregister

# register this solution
echo "swin.csh: registering solution"
set stations = `ls x* | wc -l`
#updateGamitRegistry.pl -s -h $hostn -y $ydoynd[1] -d $ydoynd[2] -n $nid[1] -u `whoami` -t $stations
cpuJobTrack.pl -j $nid[1]_$ydoyst[2] -m add


#chmod +w *.$yyst[1][od]*; /bin/rm *.$yyst[1][od]*

fixdrv d$nid[1]?.$ydoyst[2]
if ($status) goto deregister

expandt.pl -i b*.001
/bin/mv b*.001.new b*.001

# -------------------------------------------
echo "swin.csh: modify batch and launch the job"
# -------------------------------------------
cp $gs/$backup[1] .
switch($sol_type)
case pre_rap:
	echo "prnexcl -e q*.??? -g gpggaa.$ydoyst[2]" >> b$nid[1]$yr1st.bat
	echo "/bin/mv gpggaa.$ydoyst[2].new gpggax.$ydoyst[2]" >> b$nid[1]$yr1st.bat
	echo "uniback YYYY $ydoyst[1] DDD $ydoyst[2]" >> b$nid[1]$yr1st.bat
	breaksw
case hrtr:
	echo "submit_trop.csh -i qi* -c vg_in -s sittbl. -k GCR -ftp y -ftpdir /pub/transfer/kg_igs/incoming/igstropnrt" >> b$nid[1]$yr1st.bat
	echo "uniback PCODE $nid[1] YYYY $ydoyst[1] DDD $ydoyst[2] SESS $hhst[1]" >> b$nid[1]$yr1st.bat
case hr2g:
case ptst:
	echo "/bin/rm [cp]*.$ydoyst[2] *.out" >> b$nid[1]$yr1st.bat
	breaksw
case rap_reg:
	set sufx = (`echo $nid[1] | cut -c4`)
	echo "bias_sum > biassum.$ydoyst[2]" >> b$nid[1]$yr1st.bat
	if ($nid[1] == cors) set sufx = f
	if ($nid[1] == cmet) set sufx = s
	echo "uniback PCODE $nid YYYY $ydoyst[1] DDD $ydoyst[2] SUFX $sufx &" >> b$nid[1]$yr1st.bat
	echo "chmod -R +w $one_path[1]" >> b$nid[1]$yr1st.bat
	echo "/bin/rm -r $one_path[1]" >> b$nid[1]$yr1st.bat
	breaksw
case hrlyr:
	echo "ln -s q$nid[1]a.$ydoyst[2] q$nid[1]a.$ydoyst[2]$hhst" >> b$nid[1]$yr1st.bat
#	echo "submit_any.csh -r FSL_HOURLY -l q$nid[1]a.$ydoyst[2]$hhst" >> b$nid[1]$yr1st.bat
	echo "uniback PCODE $nid YYYY $ydoyst[1] DDD $ydoyst[2] SESS $hhst$mmst &" >> b$nid[1]$yr1st.bat
	echo "chmod -R +w $one_path[1]" >> b$nid[1]$yr1st.bat
	echo "/bin/rm -r $one_path[1]" >> b$nid[1]$yr1st.bat
#	echo 'latedb.pl -r n -a /net/fiona1/working/nrtsoln/fsl1.$ydoyst[2]$hhst$mmst fsl1 > /dev/null &' >> b$nid[1]$yr1st.bat
#	echo 'osumdb.pl -r n -a /net/fiona1/working/nrtsoln/fsl1.$ydoyst[2]$hhst$mmst fsl1 -d /net/anya/working/rawpool/igs/history osum_fsl1 > /dev/null &' >> b$nid[1]$yr1st.bat
	breaksw
case rerun:
	echo "uniback YYYY $ydoyst[1] DDD $ydoyst[2] &" >> b$nid[1]$yr1st.bat
	echo "/cfmrg/a\" > sed.inp
#	echo "toobusy.csh 0.80 120 1600 2359" >> sed.inp
	sed -f sed.inp b$nid[1]$yr1st.bat >> b$nid[1]$yr1st.bat.new
	/bin/mv b$nid[1]$yr1st.bat.new b$nid[1]$yr1st.bat
	chmod +x b$nid[1]$yr1st.bat
	breaksw
case reg:
        set SFX = ""
        echo "bias_sum" >> b$nid[1]$yr1st.bat
        set nid3 = `echo $nid | cut -c1-3`
        switch($nid3)
                case akd:
                        set SFX = a
                        breaksw
                case pan:
                        set SFX = p
                        breaksw
                case ebr:
                        set SFX = r
                        breaksw
                case wcd:
                        set SFX = w
                        breaksw
                case cor:
                        set SFX = f
                        breaksw
                case net:
                        set SFX = s
                        breaksw
                case eur:
                        set SFX = e
                        breaksw
                case eme:
                        set SFX = i
                        breaksw
                case bar:
                        set SFX = b
                        breaksw
                case ban:
                        set SFX = g
                        breaksw
                endsw
                case sum:
                        set SFX = u
                        breaksw
                endsw
                if($SFX != "") then
                        echo "mv -f autcln.pref.sum autcln.pref.sum.$nid" >> b$nid[1]$yr1st.bat
                        echo "mv -f autcln.post.sum autcln.post.sum.$nid"  >> b$nid[1]$yr1st.bat
                        echo "uniback PCODE $nid[1] SUFX $SFX YYYY $ydoyst[1] DDD $ydoyst[2]" >> b$nid[1]$yr1st.bat
                        echo "cd .. ; rmdir $work" >> b$nid[1]$yr1st.bat
                        echo "QCGamit_suma $ydoyst[1] $ydoyst[2] $nid" >> b$nid[1]$yr1st.bat
                endif
                if($removec == "TRUE") then
                      echo 'rm -f c?????.???' >> b$nid[1]$yr1st.bat
                      echo 'compress *' >> b$nid[1]$yr1st.bat
                endif
        breaksw
case daily:
	echo "mv -f autcln.pref.sum autcln.pref.sum.$nid" >> b$nid[1]$yr1st.bat
        echo "mv -f autcln.post.sum autcln.post.sum.$nid"  >> b$nid[1]$yr1st.bat
        echo "touch swin.done" >> b$nid[1]$yr1st.bat
	chmod +x b$nid[1]$yr1st.bat
	breaksw
default:
	echo "/bin/mv autcln.cmd.prefit autcln.cmd.prefit.$nid[1]" >> b$nid[1]$yr1st.bat
	echo "/bin/mv autcln.pref.sum autcln.pref.sum.$nid[1]" >> b$nid[1]$yr1st.bat
	echo "/bin/mv autcln.cmd.postfit autcln.cmd.postfit.$nid[1]" >> b$nid[1]$yr1st.bat
	echo "/bin/mv autcln.post.sum autcln.post.sum.$nid[1]" >> b$nid[1]$yr1st.bat
	echo "uniback YYYY $ydoyst[1] DDD $ydoyst[2] SESS $hhst$mmst &" >> b$nid[1]$yr1st.bat
	chmod +x b$nid[1]$yr1st.bat
	breaksw
endsw

if (-e FIXDRV.fatal) goto deregister
csh b$nid[1]$yr1st.bat > /dev/null
if ($status) goto deregister  

# -------------------------------------------
echo "swin.csh: done out"
# -------------------------------------------
touch swin.done

deregister:
# de-register this solution
echo "swin.csh: deregistering solution"
#echo "updateGamitRegistry.pl -e -h $hostn -y $ydoynd[1] -d $ydoynd[2] -n $nid[1] -u `whoami` -t $stations"
#updateGamitRegistry.pl -e -h $hostn -y $ydoynd[1] -d $ydoynd[2] -n $nid[1] -u `whoami` -t $stations
echo "cpuJobTrack.pl -j $nid[1]_$ydoyst[2] -m del"
cpuJobTrack.pl -j $nid[1]_$ydoyst[2] -m del
