% DSB_AM - demo script for conventional AM and envelope detection
 
%% initialization and message signal
fc = 5e3;
a_mod = 0.5; % modulation index

% read in message signal
[mm, fs] = audioread('kennedy_moon.wav');

% lowpass filter to limit to 2KHz
hh_mm = firpm(51, [0 1.5e3 2.0e3 fs/2]/(fs/2), [1, 1, 0, 0]);
mm = conv(mm,hh_mm);

% resample to higher sampling rate
mm = mm.';
mm = resample(mm, 4, 1);
fs = 4*fs;

% play sound and display spectrogram
spectrogram(mm,1024,0,1024,fs,'yaxis');
soundsc(mm,fs);

pause

%% AM
tt = (0:length(mm)-1)/fs;

% carrier with phase error
% theta = 0;
% theta = pi/2;
theta = 2*pi*10*tt + pi/2;

cc = cos(2*pi*fc*tt + theta);

% AM signal with carrier amplitude set according to modulation index
Ac = abs(min(mm))/a_mod;
ss = (Ac + mm) .* cc;

% play sound and display spectrogram
spectrogram(ss,1024,0,1024,fs,'yaxis');
soundsc(ss,fs);

pause

plot(tt, ss, tt, (Ac + mm),'--',tt, -(Ac + mm),'--');
set(gca, 'XLim', 1 + [0, 30/fc]);
grid on
xlabel('Time (s)')
legend('Modulated Signal', 'Upper Envelope', 'Lower Envelope');

pause

%% Non-Coherent Demod
% take the absolute value of received signal
yy = abs(ss);

disp('Before LPF')
spectrogram(yy,1024,0,1024,fs,'yaxis');
soundsc(yy,fs);

pause

hh_lpf = firpm(150, [0, 2e3, 3e3, fs/2]/(fs/2), [1, 1, 0, 0]);

mm_hat = conv(yy, hh_lpf);

disp('After LPF')
spectrogram(mm_hat,1024,0,1024,fs,'yaxis');
soundsc(mm_hat,fs);



plot(tt, yy, tt, pi/2*mm_hat(75+(1:length(yy))),'--');
set(gca, 'XLim', 1 + [0, 30/fc]);
grid on
xlabel('Time (s)')
legend('|Modulated Signal|', '\pi/2 \cdot Demodulated Signal', 'Location','SouthWest');

pause

