function mod08_10b
  % Compute CT Fourier Time Using the DFT
  %
  % This Octave/MATLAB script was written to mimic a corresponding
  % Labview module (Module 8.10b) that accompanies the free text 
  % "Signals and Systems: Theory and Applications" by Ulaby and Yagle
  % (ss2.eecs.umich.edu).
  %
  % In almost all cases the compuation code used in these scripts
  % is the same as that used in the Labview module.  Credit for the
  % computation code should go to the textbook authors.
  
  % These scripts have been tested under Octave 4.2.2, Octave 4.4.0
  % and MATLAB R2015a.  The Octave GUI implementation is still a
  % little buggy.  Some of strange plotting code used here attempts
  % to work around a few Octave bugs.

  % Copyright (C) 2018 Anthony Richardson <richardson.tony@gmail.com>
  %
  % This program is free software; you can redistribute it and/or modify it under
  % the terms of the GNU General Public License as published by the Free Software
  % Foundation; either version 3 of the License, or (at your option) any later
  % version.
  %
  % This program is distributed in the hope that it will be useful, but WITHOUT
  % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  % FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  % details.
  %
  % You should have received a copy of the GNU General Public License along with
  % this program; if not, see <http://www.gnu.org/licenses/>.
  %
  
  % Amplitude of 5 Hz Component
  Tmax = 4;
  
  % Amplitude of 10 Hz Component
  Bmax = 0.6;
  
  % Save initial simulation state
  simState('Tmax', Tmax);
  simState('Bmax', Bmax);
  
  clf;
  createPanel();
  createPlot();
end

function createPanel
  pos = [0.71 0.02 .28 .96 ];
  cpanel = uipanel ('position', pos);
  simState('cpanel', cpanel);
  
  %%{
  %% BUG workaround - may be able to remove this in a
  %% future version of octave
  if (exist('OCTAVE_VERSION', 'builtin'))
    % The panel position seems to get messed up when the
    % window is resized in Octave. This was an attempt to fix it.
    %set(gcf, 'sizechangedfcn', @resetControlPanel);
    % That didn't work but this seems too.
    dellistener(gcf, 'position');
    addlistener (gcf, 'position', {@resetControlPanel, cpanel, pos});
  end
  %}
  h = uicontrol(cpanel, 'style', 'text', ...
                'units', 'normalized', ...
                'string', 'N = 0', ...
                'horizontalalignment', 'left', ...                
                'position', [0.05  0.88 .9 .10]);
  simState('Nh', h);
  h = sliderControl(cpanel, 'Tmax (s)', [4, 10], ...
                      simState('Tmax'), [0.1 0.5], ...
                      [0.05 0  .9 .20], @guiCallback );
  simState('Tmaxh', h);
  h = sliderControl(cpanel, 'Bmax (rad/s)', [0.5, 1], ...
                      simState('Bmax'), [0.1 0.2], ...
                      [0.05 .5  .9 .20], @guiCallback );
  simState('Bmaxh', h);
end

% Reset GUI panel after window size change
function resetControlPanel(~, ~, p, pos)
  % Just setting the panel position does not seem to work but
  % maximizing it and then resetting the position does.
  set(p, 'visible', 'off');
  set(p, 'position', [0 0 1 1]);
  set(p, 'position', pos);
  set(p, 'visible', 'on');
  drawnow();
end

function guiCallback(s, ~)
  g = simState();
  if (s == g.Tmaxh)
    % Tmax slider  
    v = round(get(s, 'value')/0.1)*0.1;
    set(s, 'value', v);
    set(get(s, 'userdata'), 'string', num2str(v));
    simState('Tmax', v);
  elseif (s == g.Bmaxh)
    % Bmax slider  
    v = round(get(s, 'value')/0.1)*0.1;
    set(s, 'value', v);
    set(get(s, 'userdata'), 'string', num2str(v));
    simState('Bmax', v);
  end
  
  createPlot();
end

function createPlot()

  Tmax = simState('Tmax');
  Bmax = simState('Bmax');

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Calculate all of the data
  
  B=2*Bmax;
  M = round(B*Tmax);
  fs = M/Tmax;
  tdt = (-M:(M-1))/M*Tmax;
  N = length(tdt); % N always be even (N = 2*M)
  set(simState('Nh'), 'string', ['N = ' num2str(N)]);
  tct = linspace(tdt(1), tdt(end), 2000);
  fdt = (-M:(M-1))*fs/M/2;
  fct = linspace(fdt(1), fdt(end), 2000);

  % Ensure sampling at t = 0 and t = -Tmax
  xdt = exp(-tdt.*tdt/2)/sqrt(2*pi);  
  xct = exp(-tct.*tct/2)/sqrt(2*pi);  

  FXdt=fftshift(abs(fft(xdt)))/fs;
  FXct=exp(-2*pi*pi*fct.*fct);

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Now create the plots
  dw = 0.05; plotw = 0.60;  
  dh = 0.05; ploth = 0.35; 
  plotrowy = [ploth+3.7*dh  dh] + 1.1*dh;
  plotcolx = dw + 0.65*dw;
  
  % Plot the signal spectrum
  subplot('position', [plotcolx(1) plotrowy(1) plotw ploth]);
  stem(fdt, FXdt);
  hold on;
  plot(fct, FXct);
  hold off;
  grid on;
  legend('DFT', 'CTFT');
  xlim([fdt(1) -fdt(1)])
  xlabel('\omega (rad/s)');
  ylabel('Value');
  h = title('Frequency Domain');
  p = get(h, 'position');
  xl = xlim();
  set(h, 'position', [xl(1) p(2:3)], 'horizontalalignment', 'left');

  % Plot the signal
  subplot('position', [plotcolx(1) plotrowy(2) plotw ploth]);
  stem(tdt, xdt);
  hold on;
  plot(tct, xct);
  hold off;
  grid on;
  legend('DT', 'CT');
  xlim([tdt(1) -tdt(1)]);
  xlabel('Time (s)');
  ylabel('Value');
  h = title('Time Domain');
  p = get(h, 'position');
  xl = xlim();
  set(h, 'position', [xl(1) p(2:3)], 'horizontalalignment', 'left');
  
  drawnow();
end

function v = simState(key, val)
  persistent state;
  if (nargin == 0)  
    % Return the entire struct
    v = state;
  elseif (nargin == 1)
    % Return a particular field from the struct
    v = state.(key);
  elseif (nargin == 2)
    % Set a key value (key must be a string)
    state.(key) = val;
    v = val;
  end
end

function h = sliderControl(parent, label, limits, val, step, pos, cback)
  % sliderstep = [minstep maxstep]
  % where minstep is fraction of range on arrow click
  % and maxstep is fraction of range on trough click
  h = uicontrol(parent, 'style' ,'slider',...
           'units', 'normalized',...
           'position', [pos(1) pos(2)+0.33*pos(4) pos(3) 0.32*pos(4)],...
           'min', limits(1), 'max', limits(2),...
           'sliderstep', [step(1)/(limits(2)-limits(1)) step(2)/(limits(2)-limits(1))],...
           'value', val, 'callback', cback);
  uicontrol(parent, 'style', 'text',...
           'units', 'normalized',...
           'position', [pos(1) pos(2) 0.2*pos(3) 0.3*pos(4)],...
           'horizontalalignment', 'left', ...
           'String', num2str(limits(1)));
  uicontrol(parent, 'style', 'text',...
           'units', 'normalized',...
           'position', [pos(1)+0.8*pos(3) pos(2) 0.2*pos(3) 0.3*pos(4)],...
           'horizontalalignment', 'right', ...
           'String', num2str(limits(2)));         
  uicontrol(parent, 'style', 'text',...
           'units', 'normalized',...
           'position', [pos(1) pos(2)+0.67*pos(4) pos(3) 0.3*pos(4)],...
           'horizontalalignment','left',...
           'String', label);        
  hc = uicontrol(parent, 'style', 'text',...
           'units', 'normalized',...
           'position', [pos(1)+.3*pos(3) pos(2) 0.4*pos(3) 0.3*pos(4)],...
           'backgroundcolor', [0.8 0.8 0.8], ...
           'String', num2str(val));
  set(h, 'userdata', hc);
end
