function mod09_04
  % Use of Autocorrelation to Estimate Period
  %
  % This Octave/MATLAB script was written to mimic a corresponding
  % Labview module (Module 9.4) 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.4.0 and
  % MATLAB R2018a.  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/>.
  %
  
  % Period
  T0 = 0.005;
  
  % Noise level
  Ns = 1;
  
  % Save initial simulation state
  mod09_04_state('T0', T0);
  mod09_04_state('Ns', Ns);
  
  clf;
  mod09_04_gui();
  mod09_04_sim();
end

function mod09_04_gui
  pos = [0 0.85 1 .15 ];
  cpanel = uipanel ('position', pos);
  mod09_04_state('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, 'Period', [0.002, 0.008], ...
                      mod09_04_state('T0'), [0.001 0.002], ...
                      [0.05 0.05  .4 .9], @mod09_04_cb );
  mod09_04_state('T0h', h);
  h = sliderControl(cpanel, 'Noise Level', [0, 2], ...
                      mod09_04_state('Ns'), [0.01 0.05], ...
                      [0.55 0.05  .4 .9], @mod09_04_cb );
  mod09_04_state('Nsh', h);
end

function mod09_04_cb(s, ~)
  g = mod09_04_state();
  if (s == g.T0h)
    % T0 slider  
    v = round(get(s, 'value')/0.001)*0.001;
    set(s, 'value', v);
    set(get(s, 'userdata'), 'string', num2str(v));
    mod09_04_state('T0', v);
  elseif (s == g.Nsh)
    % Ns slider  
    v = round(get(s, 'value')/0.001)*0.001;
    set(s, 'value', v);
    set(get(s, 'userdata'), 'string', num2str(v));
    mod09_04_state('Ns', v);
  end
  
  mod09_04_sim();
end

function mod09_04_sim()

  T0 = mod09_04_state('T0');  % Period
  Ns = mod09_04_state('Ns');  % Noise level

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Calculate all of the data
  
  fs = 1000;            % Sampling frequency
  TCMAX = 0.01;         % max corr plot time value
  TSMAX = 0.05;         % max signal plot time value
  L = 500;              % total signal length
  x = sign(10*cos(2*pi*1/T0*[0:(L-1)]/fs)) + Ns*randn(1, L);
  
  fx2 = abs(fft(x, 1024)).^2;
  A = real(ifft2(fx2));
  ICMAX = TCMAX*fs+1;
  ISMAX = TSMAX*fs+1;
  A = A(1:ICMAX);
  TA = (0:ICMAX-1)/fs;
  TS = (0:ISMAX-1)/fs;
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Now create the plots
  dw = 0.05; plotw = 0.85;  
  dh = 0.05; ploth = 0.30; 
  plotrowy = [ploth+3.2*dh  dh] + 0.5*dh;
  plotcolx = dw + 0.65*dw;
  
  % Plot the signal autocorrelation
  subplot('position', [plotcolx(1) plotrowy(1) plotw ploth]);
  plot(TA, A(1:ICMAX));
  yl = [-500 1000];
  ylim(yl);
  line([T0 T0], yl, 'color', 'r')
  grid on;
  xlabel('Time (s)');
  ylabel('Amplitude');
  h = title('Autocorrelation');
  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]);
  plot(TS, x(1:ISMAX));
  grid on;
  xlim([0 0.05001]);
  xlabel('Amplitude');
  ylabel('Value');
  h = title('Signal');
  p = get(h, 'position');
  xl = xlim();
  set(h, 'position', [0 p(2:3)], 'horizontalalignment', 'left');
  %}
  
  drawnow();
end

function v = mod09_04_state(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

% 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 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
