%% SPECIFY FOURIER SERIES HERE  
T = 2;  
kv = 1:23;

% Coefficients:  assume signal real so only positive k required
%c0 = 0.5;
%ckv = sin(kv*pi/2)./(kv*pi);

c0 = 0.5;
ckv = 2*(sin(kv*pi/2)./(kv*pi)).^2;

%% Display parameters
dopause = 1;
xmin = -3;  xmax = 3;
kmind = -10;  kmaxd = 10;

%% Plots
xs = xmin:0.025:xmax;
omega0 = 2*pi/T;
for ki=0:length(kv)
  
  % Axes
  a1m = max(abs(c0),max(2*abs(ckv)));
  ax1 = [xmin xmax -1.2*a1m 1.2*a1m];
  ax2 = [kmind kmaxd 0 1.1*max(c0,max(abs(ckv)))];
  xrec = c0*ones(size(xs));
  for k=1:length(kv)
    ck = ckv(k);
    xrec = xrec + 2*abs(ck)*cos(k*omega0*xs + angle(ck));
  end
  xrecl = [min(xrec) max(xrec)];
  ax3 = [kmind kmaxd -3.5 3.5];
  ax4 = [xmin xmax min(xrec)-0.1*diff(xrecl) max(xrec)+0.1*diff(xrecl)];
    
  % Deal with DC component seperately
  if ki==0
    yc = c0*ones(size(xs));
    ya = yc;

    % Initialise plots and axes
    fh = figure;
    subplot(4,1,1);  hold on;  plot(xs,yc);  hold off;  axis(ax1);
    subplot(4,1,2);  
    ph = stem(0,c0);  axis(ax2);
    set(ph(1),'marker','none');  ylabel('|c_k|');
    subplot(4,1,3);  ph = stem(0,0);  axis(ax3);
    set(ph(1),'marker','none');  ylabel('\angle c_k');
    subplot(4,1,4);  plot(xs,NaN*zeros(size(xs)));  axis(ax4);
    if dopause, pause; end
    subplot(4,1,4);  plot(xs,ya);  axis(ax4);
    if dopause, pause; end

    continue;
  end

  % Skip small components
  if abs(ckv(ki))<1e-6, continue; end
  
  % Update plots with new components
  yc = 2*abs(ckv(ki))*cos(ki*omega0*xs - angle(ckv(ki)));
  ya = ya + yc;
  subplot(4,1,1);  hold on;  ph = plot(xs,yc);  hold off;  
  set(ph,'color','red');
  subplot(4,1,2);  
  hold on;  phs11 = stem(ki,abs(ckv(ki)));  phs12 = stem(-ki,abs(ckv(ki)));  hold off;  
  subplot(4,1,3);  
  hold on;  phs21 = stem(ki,angle(ckv(ki)));  phs22 = stem(-ki,-angle(ckv(ki)));  hold off;  
  phs = [phs11 phs12 phs21 phs22];  set(phs,'color','red','marker','none');
  if dopause, pause; end
  
  % Reset colours
  subplot(4,1,4);  plot(xs,ya);  axis(ax4);
  if dopause, pause; end
  set(ph,'color','blue');  set(phs,'color','blue');
end