function demod = synchdemod(r)
%Takes a signal r and demodulates using synchronous modulation. 
%Assumptions:
% The input signal is sampled at 88.2kHz.
% The input signal is 10 seconds long.
% The carrier frequency is 15kHz. 
%Returns:
% The demodulated signal downsampled to 44.1kHz.

%Overall sampling rate, 88.2kHz.
rate = 44100*2;

%Filter order
order = 50;

%A lowpass filter, operates at a sampling rate of 88.2kHz, with cutoff 8kHz.
b = fir1(order, 8e3/(rate/2)); a=1;

%Time axis, our signals are exactly 10 seconds long
t = 0:1/rate:10;
t = t(1:length(t)-1)';

%Generate carrier required for sync demod
mod_35k = cos(2*pi*35000*t);

%Plot spectrum of r
%We need a high fft_len to get good resolution
fft_len = 2^16;
R = fft(r,fft_len);
mag_R = abs(R)/fft_len;

%Our frequency scale, in Hz, positive frequencies only
f = rate*(0:fft_len/2)/fft_len;

figure(1);
plot(f,mag_R(1:fft_len/2+1))
title('Spectrum of AM signal');
xlabel('Frequency (Hz)');
ylabel('Magnitude');

%Synchronous demodulation
%LPF
demod = filter(b,a, mod_35k.*r);
%Rescale
demod = 2*demod;
%Downsample to the audio range
demod = decimate(demod,2);

%demod is now sampled at 44.1kHz
%Play sound 
soundsc2(demod,44100);
