% Sinc curve: Calculate the sinc pulse, window and windowed sinc pulse
% given a sample rate, cutoff frequency, and transition width.

clear all;
close all;

% Basic variables

fs=2.4e6; % Sample rate in Hz
fw=10e3; % Transition width in Hz
fc=100e3; % Cutoff frequency in Hz.
a=74; % Attenuation of Blackman window
N=ceil((a*fs/(22*fw))); % harris approximation for number of points in sinc pulse.

% Check to see if N is odd or even. If it is odd, make it even.

if(mod(N,2)==1)
    N=N+1;
endif

Nhalf=N/2+1;
n=(-N/2):(N/2); % Counter for calculating the sinc pulse.
hsinc=sin(2*pi*n*fc/fs)./(pi*n); % Calculate the sinc pulse.
hsinc(Nhalf)=2*fc/fs; % Calculate the value of the center of the sinc pulse.

% Plot the sinc curve

figure(1,'position',[0 0 1100 500]);

plot((0:N),hsinc,'linewidth',2,'color','black');
grid on;
title('Sinc Pulse','fontsize',24);
xlabel('Delay Value','fontsize',18);
ylabel('Amplitude','fontsize',18);
set(gca,'fontsize',14);
ylim([-0.02,0.1]);
xlim([0,N]);

% Calculate the window

k=0:N;
w=0.42-0.5*cos(2*pi*k/N)+0.08*cos(4*pi*k/N);

figure(2,'position',[0 0 1100 500]);

plot(k,w,'linewidth',2,'color','black');
grid on;
title('Blackman Window','fontsize',24);
xlabel('Delay Value','fontsize',18);
ylabel('Amplitude','fontsize',18);
set(gca,'fontsize',14);
ylim([0,1]);
xlim([0,N]);

% Calculate the windowed sinc pulse by multiplying the sinc pulse with the window.

hw=hsinc.*w;

figure(3,'position',[0 0 1100 500]);

plot((0:N),hw,'linewidth',2,'color','black');
grid on;
title('Windowed Sinc','fontsize',24);
xlabel('Delay Value','fontsize',18);
ylabel('Amplitude','fontsize',18);
set(gca,'fontsize',14);
ylim([-0.02,0.1]);
xlim([0,N]);

% Calculate the spectrum of the windowed sinc filter.

Nh=2^15; % Length of zero-padded windowed sinc pulse
hwf=[hw zeros(1,Nh-N-1)]; % Zero-padding of windowed sinc pulse
frq=20*log10(abs(fft(hwf))); % Calculate the FFT of the zero-padded windowed sinc pulse
f=(0:(Nh-1))*fs/Nh; % Frequency scale counter

figure(4,'position',[0 0 1100 500]);

plot(f/1000,frq,'linewidth',2,'color','black');
grid on;
title('Gnu Octave Low Pass Filter Spectrum - Blackman Window','fontsize',24);
xlabel('Frequency (kHz)','fontsize',18);
ylabel('Relative Gain (dB)','fontsize',18);
set(gca,'fontsize',14);
ylim([-150,10]);
xlim([0,300]);
set(gca,'ytick',[-150:10:10]);
