#!/usr/bin/env python
import sys

def print_usage():
    print("""**********************************************************************
Usage: ./titan_norm_res.py titan_dir_name
where 'titan_dir_name' is the directory with the HUD files.

Description:

 Plot envelope of Titan normalized code and carrier residuals for each
 satellite where: Normalized resid = resid / estimated std. of resid.
 This is meant to be run in an interactive mode because the legend is
 clickable to enable/disable lines.

 Ideally the normalized Titan residuals should look like white noise.
 If 'x' is white noise, then the envelope of x/std(x) should be around
 3 (see mutils.py signal_envelope).
**********************************************************************""")

if len(sys.argv) != 2:
    print_usage()
    sys.exit(0)

titan_dir = sys.argv[1]

from pylab import *
from mutils import *

close('all')

rdr = TitanHudPKFEE(titan_dir)
sv_list = rdr.get_amb_svs()
N_pts = 300

fig = figure(figsize=(10,8))
for sv in sv_list:
    t, cde_val, cde_std = rdr.get_L1_cde_res( sv )
    plot( t, signal_envelope(cde_val/cde_std, N_pts), label='%d'%sv )
    #plot( t, abs(cde_val/cde_std), label='%d'%sv )
title('Envelope of normalized L1 code residuals')
xlabel('GPS time [s]')
ylabel('Norm resid')
legend(bbox_to_anchor=(1.1,1.05))
make_legend_interactive( fig )

fig = figure(figsize=(10,8))
for sv in sv_list:
    t, phs_val, phs_std = rdr.get_L1_phs_res( sv )
    plot( t, signal_envelope(phs_val/phs_std, N_pts), label='%d'%sv )
    #plot( t, abs(phs_val/phs_std), label='%d'%sv )
title('Envelope of normalized L1 phase residuals')
xlabel('GPS time [s]')
ylabel('Norm resid')
legend(bbox_to_anchor=(1.1,1.05))
make_legend_interactive( fig )

show()
