% SOL_AMDEMOD_WITHFILTER Demodulate AM signal
%    MD = SOL_AMDEMOD_WITHFILTER(S, FC, FS) is the demodulation of an AM
%    (amplitude modulation) signal at carrier frequency FC, sampled at FS.
%    The returned signal is normalized to have values between -1 and 1.

function md = sol_amdemod_withFilter(s, fc, fs)
    N_ORDER = 2; % 8 for a better filtering, the demodulated signal will look better
    CUTOFF = fc/2; % a good choice for AM will be around 5 KHz (AM radio is generally limited to that)
    
    % Take absolute value
    s_abs = abs(s);
    
    % Filter with butterworth filter at half the center frequency
    [b, a] = butter(N_ORDER, 2*CUTOFF/fs);   % cf help butter
    s_filt = filter(b, a, s_abs);
    
    % Uncomment below to visualize the impulse response
%     impulseResponseFilter = filter(b,a,[1,zeros(1,100)]);
%     tfplot(impulseResponseFilter, fs, 'h', 'Butterworth Filter');
%     % another way of visualizing
%     fvtool(b,a);
%     % yet another way of visualizing
%     freqz(b,a);
    
    % Remove the mean %(eventually ignore the 25 first elements to remove the transients from the filter)
    s_filt = s_filt(25:length(s_filt)); % remove the elements for good
    s_zm = s_filt - mean(s_filt(1:length(s_filt))); % one can also remove the elements only for subtracting the mean
    
    % Convert to be between -1 and 1 %( eventually ignore the 25 first elements)
    md = s_zm / max(abs(s_zm(1:length(s_zm))));
    
end
