# From the docstring
#x = sdr.capture(Tc, fo=88700000.0, fs=2400000.0, gain=40, device_index=0)
x = sdr.capture(Tc=5,fo=162.4e6,fs=2.4e6,gain=40,device_index=0)

sdr.complex2wav('capture_162475.wav',2400000,x)

fs, x = sdr.wav2complex('capture_162475.wav')

psd(x,2**10,2400);

"""
Explanation: Capture NOAA Weather Radio
Using rtlsdr_helper record a short complex baseband array using capture().
End of explanation
"""


def NBFM_demod(x,fs=2.4e6,file_name='test.wav',B1=50e3,N1=10,B2=5e3,N2=5):
    """
    Narrowband FM Demodulator
    """
    b = signal.firwin(64,2*B1/float(fs))
    # Filter and decimate (should be polyphase)
    y = signal.lfilter(b,1,x)
    z = ss.downsample(y,N1)
    # Apply complex baseband discriminator
    z_bb = sdr.discrim(z)
    z_bb -= mean(z_bb)
    # Design 2nd decimation lowpass filter
    bb = signal.firwin(64,2*B2/(float(fs)/N1))
    # Filter and decimate
    zz_bb = signal.lfilter(bb,1,z_bb)
    # Decimate by N2
    z_out = ss.downsample(zz_bb,N2)
    # Save to wave file
    ss.to_wav(file_name, 48000, z_out)
    print('Done!')
    return z_bb, z_out

z_bb, z_demod = NBFM_demod(x,file_name='NOAA_cos_demod.wav')

psd(z_demod,2**10,2400/50);
xlabel(r'Frequency (kHz)');
ylim([-80,-20])

Audio('NOAA_cos_demod.wav')

"""
Explanation: Narrowband FM Demodulator
End of explanation
"""


