%--------------------------------------------------
% Tony Hyun Kim
% 6.003: PS#8, Matlab exercise
%--------------------------------------------------

%--------------------------------------------------
% Part (a)
%--------------------------------------------------
load origbl; % Load the sound file in the vector 'x'
fs = 8192;

X = fftshift(fft(x,8192));
N = length(x);
f = linspace(-1/2*fs, 1/2*fs, 8192);
subplot(221);
plot(f,abs(X));
xlabel('Signal frequency');
ylabel('|X(jw)|');
title('Part (a): Original sound file');


%--------------------------------------------------
% Part (b)
%--------------------------------------------------
t = [0:1/fs:(N-1)/fs]';
y = x.*cos(2*pi*1500*t);
subplot(222);
Y = fftshift(fft(y,8192));
plot(f,abs(Y));
xlabel('Signal frequency');
ylabel('|Y(jw)|');
title('Part (b): The modulated carrier');

%--------------------------------------------------
% Part (c)
%--------------------------------------------------
w = y.*cos(2*pi*1500*t);
subplot(223);
W = fftshift(fft(w,8192));
plot(f,abs(W));
xlabel('Signal frequency');
ylabel('|W(jw)|');
title('Part (c): The demodulated carrier');

%--------------------------------------------------
% Part (d): See my handwritten work for the 
%           analytic expression of h.
%--------------------------------------------------
T = 40/fs/2;
ts = [0:1/fs:(41-1)/fs]';
h = sinc(2*1500*(ts-T));
h = h.*hamming(41);
subplot(224);
H = fftshift(fft(h,8192));
df = fs/8192;
plot([-fs/2:df:fs/2-df],abs(H));

xlabel('Signal frequency');
ylabel('|H(jw)|');
title('Part (d): Transform of ideal filter response');

figure;
plot(ts,h);
xlabel('t');
ylabel('Impulse response, h(t-T)');
title('Part (d): Impulse response of ideal filter');

%--------------------------------------------------
% Part (e): 
%--------------------------------------------------
z = conv(w,h);
Z = fftshift(fft(z,8192));
figure;
plot(f,abs(Z));
xlabel('Signal frequency');
ylabel('|Z(jw)|');
title('Part (e): The filtered output');

%--------------------------------------------------
% Part (f): 
%--------------------------------------------------
figure;
subplot(311);
w = y.*cos(2*pi*1500*t+0);
W = fftshift(fft(w,8192));
plot(f,abs(W));
xlabel('Signal frequency');
ylabel('Demodulation with phase, phi = 0');
title('Part (f): Effect of phase in the demodulation scheme');

subplot(312);
w = y.*cos(2*pi*1500*t+pi/4);
W = fftshift(fft(w,8192));
plot(f,abs(W));
xlabel('Signal frequency');
ylabel('Demodulation with phase, pi/4');
title('Part (f): Effect of phase in the demodulation scheme');


subplot(313);
w = y.*cos(2*pi*1500*t+pi/2);
W = fftshift(fft(w,8192));
plot(f,abs(W));
xlabel('Signal frequency');
ylabel('Demodulation with phase, pi/2');
title('Part (f): Effect of phase in the demodulation scheme');