%% 1.5 Frequency Response of the Four-Point Averager
% b
w = linspace(-pi, pi, 400);
C_w = (2*cos(0.5*w)+2*cos(1.5*w))/4;
phi_w = exp(-j*1.5*w);
H = C_w .* phi_w;
plot(w, abs(H));
xlabel('w');
ylabel('C(w)');
title('Magnitude');
xlim( [-pi pi] );
figure;
plot(w, angle(H));
xlabel('w');
ylabel('e^jphi(w)');
title('Phase');
xlim( [-pi pi] );

% c
bb = 1/4*ones(1,4);
%-- Filter Coefficients
ww =-pi:(pi/100):pi; %-- omega hat frequency vector
H = freqz(bb, 1, ww); %<--freekz(bb,1,ww) is an alternative
subplot(2,1,1);
plot(ww, abs(H)), grid on
subplot(2,1,2);
plot(ww, angle(H)), grid on
xlabel('Normalized Radian Frequency')

%% 1.6 FIR Nulling Filters
b = [1, 1.414213562, 1]
a = [1]
poles = roots(a)
zeroes = roots(b)
zplane(b,a)

%% 2.3 Removing Interference From A Speech Signal
% a
load speechbad.mat

fs = 8000
sound(xxbad, fs)

figure;
spectrogram(xxbad, 1024, 512, 1024, fs, 'yaxis');
title('Spectrogram of Distorted Speech Signal');
xlabel('Time (s)');
ylabel('Frequency (Hz)');
colorbar;

% b
w1 = 2*pi*f_interference(1)/fs
w2 = 2*pi*f_interference(2)/fs

b1 = [1 -2*cos(w1) 1]
b2 = [1 -2*cos(w2) 1]
equivalentFilterCoeff = conv(b1,b2)

% c
ww =-pi:(pi/100):pi; %-- omega hat frequency vector
H = freqz(equivalentFilterCoeff, 1, ww); %<--freekz(bb,1,ww) is an alternative
subplot(2,1,1);
plot(ww, abs(H)), grid on
subplot(2,1,2);
plot(ww, angle(H)), grid on
xlabel('Normalized Radian Frequency')

% d
figure;
spectrogram(xxbad, 1024, 512, 1024, fs, 'yaxis');
title('Spectrogram of Input Distorted Speech Signal');
xlabel('Time (s)');
ylabel('Frequency (Hz)');
colorbar;

xx_null_filtered = filter(equivalentFilterCoeff, 1, xxbad)
figure;
spectrogram(xx_null_filtered, 1024, 512, 1024, fs, 'yaxis');
title('Spectrogram of Output Corrected Speech Signal');
xlabel('Time (s)');
ylabel('Frequency (Hz)');
colorbar;
