function y = Read_RTLSDR(cf, sf, fs, nf ,g)
%
% Utility to read data from an rtl-sdr
%
% y = Read_RTLSDR(cf, sf, fs, nf, g)
% 
% Inputs:
%   cf - center frequeny in Hz (88.5e6 for KQED)
%   sf - sampling frequecy in Hz, typically 2.048e6
%   fs - frame size, typically 1e5
%   nf - number of frames
%   g  - reciever gain in dB, typically 10 to 30
%
% Returns:
%   y - complex I and Q samples of the RF waveform
%
% The total acquisition time is (fs*nf)/sf seconds
%
% Choose the gain so that the amplitude is less than 128, where
%    the rtl-sdr clips, but large enough you can't see the quantization
%

% set up the rtl-sdr
hSDR = comm.SDRRTLReceiver('0', ...
              'CenterFrequency',  cf, ...
              'SampleRate',       sf, ...
              'SamplesPerFrame',  fs, ...
              'EnableTunerAGC',false);
% we can't do this in the call above for some reason!
hSDR.TunerGain = g;

% collect the data
buf = [];
for counter = 1:nf
    buf = [buf; step(hSDR)];
end

% free up the device
release(hSDR);

% convert the data into doubles for matlab
y = double(buf);

end
