function ss = ampDemodulate(sp, fc, BW, isIQ, fs)
% ampDemodulate - demodulate an amplitude modulated signal
%
% Inputs:
%   sp - passband, modulated signal
%   fc - carrier frequency (in Hertz)
%   BW - baseband bandwidth (in Hertz); ss will be fitered to enforce BW
%   isIQ - flag that indicates if this signal is quadrature modulated
%   fs - sampling rate (in Hertz)
%
% Outputs:
%   ss - input samples (maybe complex)
%
% Usage:
%   ss = ampDemodulate(sp, fc, BW, isIQ, fs)

% Note: this script does not (yet) provide phase tracking

%% downconvert signal
% we'll need a LPF to remove the double frequency component
f2 = max(1.2*BW, 2*fc-BW);
hh = firpm(50, [0, BW, f2, fs/2]/(fs/2), [1 1 0 0]);

tt = (0:length(sp)-1)/fs;

% downconvert, then filter
ss = sp .* cos(2*pi*fc*tt)*2;
ss = conv(ss, hh);

% remove the carrier component
ss = ss - mean(ss); % mean(ss) equals the zero frequency component, i.e., the carrier

%% if sp is quadrature modulated, get the Q channel as well
if isIQ
    ssQ = sp .* sin(2*pi*fc*tt)*(-2);
    ssQ = conv(ssQ, hh);
    ssQ = ssQ - mean(ssQ);
    
    % combine I and Q into complex signal
    ss = complex(ss, ssQ);
end

