function mod09_02
  % DT Lowpass Filter Design Using Windowing
  %
  % This Octave/MATLAB script was written to mimic a corresponding
  % Labview module (Module 9.1) 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/>.
  %
  
  % L
  M = 26;
  
  % Save initial simulation state
  simState('M', M);
  
  clf;
  createPanel();
  createPlot();
end

function createPanel
  pos = [0.1 0.885 .8 .115 ];
  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 = sliderControl(cpanel, 'Number of segments', [10, 500], ...
                      simState('M'), [1 2], ...
                      [0.05 0.05  .45 .9], @guiCallback );
  simState('Mh', h);
  h = uicontrol(cpanel, 'style', 'text', 'string', ['Nfft = ' num2str(0)], ...
                    'units', 'normalized',...
                    'horizontalalignment', 'left', ...
                    'position', [0.55 0.05 0.4 0.9]);
  simState('Lh', 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.Mh)
    % L slider  
    v = round(get(s, 'value'));
    set(s, 'value', v);
    set(get(s, 'userdata'), 'string', num2str(v));
    simState('M', v);
  end
  
  createPlot();
end

function createPlot()

  M = simState('M');
  Lh = simState('Lh');

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Calculate all of the data
  fs = 8192;
  persistent X;
  persistent N;
  if(isempty(X))
    X = csvread('victorstone.csv');
    N = length(X);
  end

  L = floor(N/M);
  set(Lh, 'string', ['Nfft = ' num2str(L)]);
  FX = abs(fft(reshape(X(1:L*M), L, M)));

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Now create the plots
  FMAX = 1365;
  KMAX = floor(FMAX*L/fs);
  subplot('position', [0.1 0.1 0.8 0.78]);
  imagesc([0 (N-1)/fs], [0 (KMAX-1)*fs/L], FX(1:KMAX-1,:));
  set(gca, 'ydir', 'normal');
  colormap(jet);
  ylabel('freq (Hz)');
  xlabel('time (s)');

  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
