%--------------------------------------------------------
% Example of the design of a linear-phase lowpass filter 
%   with a cutoff frequency of pi/2 using 
%   frequency-sampling method.
%
%   Created by Aly El-Osery
%   Date: Nov. 14th, 2002
%   Last Modified: Nov. 8th, 2006
%--------------------------------------------------------

clear all
close all
M=65

kw=0:(M-1)/2;
k=0:M-1;
w=0:0.001:pi;

r=0.5;

Hk(kw+1)=1*exp(-j*2*pi/M*kw*(M-1)/2);
Hk((M-1)/4+2:(M-1)/2+1)=0;

Hk(M:-1:(M-1)/2+2)=conj(Hk(2:(M-1)/2+1));

figure(3)
stem(k,abs(Hk))
xlabel('k')
ylabel('H_1(k)')
grid on

%Using the interpolation function
Hw=1/M*(1-r^M*exp(-j*M*w)).*(Hk*(1-r*exp(j*2*pi/M*k')*exp(-j*w)).^-1);
figure(1)
subplot(2,1,1)
plot(w,20*log10(abs(Hw)),'r')
xlabel('\omega')
ylabel('Magnitude in dB')
grid on
subplot(2,1,2)
plot(w,unwrap(angle(Hw)),'r')
xlabel('\omega')
ylabel('phase')
grid on

%Another approach using IFFT
figure(2)
[m,omega]=freqz(ifft(Hk));
subplot(2,1,1)
plot(omega,20*log10(abs(m)),'r')
xlabel('\omega')
ylabel('Magnitude in dB')
grid on
subplot(2,1,2)
plot(omega,unwrap(angle(m)),'r')
xlabel('\omega')
ylabel('phase')
grid on

%The following repeats the above but with points in the 
%transition band

Hk((M-1)/4+2)=0.5886*exp(-j*2*pi/M*((M-1)/4+1)*(M-1)/2);
Hk((M-1)/4+3)=0.1065*exp(-j*2*pi/M*((M-1)/4+2)*(M-1)/2);

Hk(M:-1:(M-1)/2+2)=conj(Hk(2:(M-1)/2+1));
Hw=1/M*(1-r^M*exp(-j*M*w)).*(Hk*(1-r*exp(j*2*pi/M*k')*exp(-j*w)).^-1);

figure(4)
hold on
subplot(2,1,1)
plot(w,20*log10(abs(Hw)),'b')
grid on
xlabel('\omega')
ylabel('Magnitude in dB')
subplot(2,1,2)
plot(w,unwrap(angle(Hw)),'r')
xlabel('\omega')
ylabel('phase')
grid on

%legend('no transition points','with transition points')

figure(5)
hold
[m,omega]=freqz(ifft(Hk));
subplot(2,1,1)
plot(omega,20*log10(abs(m)),'b')
%legend('no transition points','with transition points')
grid on
xlabel('\omega')
ylabel('Magnitude in dB')
subplot(2,1,2)
plot(omega,unwrap(angle(m)),'r')
xlabel('\omega')
ylabel('phase')
grid on


figure(6)
hold on
stem(k,abs(Hk))
xlabel('k')
ylabel('H_2(k)')

hold off
