%The following code demonstrates how the Discrete Fourier Series (and the
%Discrete Fourier Transform) result from sampling of the Fourier Transform
%of the repeated sub-sequence.

N = 11;
interp_factor = 1000;
omega = linspace(0, 2, interp_factor * N);

h = [1 2 3 4 -1];
spacing = zeros(1, N - length(h));

figure(1);
sequence_unit = [h spacing];
sequence = [sequence_unit sequence_unit sequence_unit];
stem(0:length(sequence)-1, sequence)

X_e_jw = omega .* 0;
for count = 1:length(h)
    X_e_jw_n = exp(j .* pi .* omega .* (count-1)) .* h(count);
    X_e_jw = X_e_jw_n + X_e_jw;
end

figure(2);
plot(omega, abs(X_e_jw))
hold on;
X_e_jw_sampled = X_e_jw(1:interp_factor:end);
omega_sampled = omega(1:interp_factor:end);
stem(omega_sampled, abs(X_e_jw_sampled),'g');
hold off;
xlabel('\omega/\pi');
ylabel('Magnitude');
title('Fourier Transform of Finite Sequence');
legend('Fourier Transform', 'Discrete Fourier Series');


figure(3);
stem(abs(X_e_jw_sampled))
hold on;
stem(abs(fft(sequence_unit)), 'g')
hold off;
title('Fourier Series Coefficients')
ylabel('|X[k]|');
xlabel('k');