clear all;

%%
fs = 100;
nsecs = 20;
t = [0:1/fs:nsecs-1/fs];

a = ao(plist('built-in', 'padded_sine', ...
  'f0', .1, ...
  'Timebase', t, ...
  'Tstart', 1.1, ...
  'Ncycles', 2.1, ...
  'phi', 90))

n = ao(plist('tsfcn', '0.1*randn(size(t))', 'fs', fs, 'nsecs', nsecs));

sw = a+n;

sw.iplot

%% Now try to fit this

% [dc,A,f0,phi,Tstart,N]
af = ao(plist('built-in', 'padded_sine', ...
  'Timebase', sw, ...
  'f0', .1, ...
  'P', [0 1 .11 90 1 2]));

iplot(sw, af)

%% Now fit with simplex

opts = optimset('Display', 'iter', ...
  'MaxFunEvals', 10000, ...
  'MaxIter', 10000, ...
  'TolX', 1e-15, ...
  'TolFun', 1e-15, ...
  'LargeScale', 'on');

r0 = [0 1 .11 90 1 2];

mksine = @(r)(ao(plist('built-in', 'padded_sine', ...
  'Timebase', sw, ...
  'P', r)).y);

f = @(r)(sum((mksine(r)-sw.y).^2));

% Do a few iterative fits
% for kk=1:5
  x0 = fminsearch(f, r0, opts);
% end


%%

afit = ao(plist('built-in', 'padded_sine', 'Timebase', sw, 'P', x0));

iplot(sw, afit)



