% Example of using FFT for convolution.

N = 64;

% The signal:
x = f_step(N);


% The kernel:
Nk = 11; % Filter width (prefer an odd number so it can be centered).
k = ones(1,Nk)/Nk; % A normalized boxcar filter of width Nk.
k_padded = zeros(1,N);
k_padded(1:Nk) = k;
k_padded = circshift(k_padded, [0,-floor(Nk/2)]);


% Performing the convolution:
K = fftn(k_padded);
X = fftn(x);
X2 = X.*K;
x2 = ifftn(X2);

% Question: how hard would it be to write a general purpose routine to do 
% convolution, e.g.  x2 = convolve(x,k); would this be worthwhile?
%        
% Question: Why is no anti-aliasing filter needed?
%
% Question: Suppose you calculated the Green's function analytically 
% for the lowpass filter, then coded it up and convolved it using fftn
% with E(t). Would this offer any improvement over using D_lowpass
% and solve_inhomogeneous?
%

% PLOTS...
figure(1)
hold off
bar(K_padded,'b')
hold on
title('Properly "centered" boxcar filter')
hold off
print('test5_boxcar.pdf','-dpdf')

figure(2)
hold off
plot(x,'b','linewidth',2)
hold on
plot(real(x2),'g','linewidth',2)
plot(imag(x2),'r','linewidth',2)
title('Boxcar smoothing, done with FFT: x2 = x*k')
legend('x(t)','Re(x2)','Im(x2)')
print('test5_result.pdf','-dpdf')