function editlist = editlist_find(times, bestlags, MEDFILTLEN, MINRUN, BINWIDTH)
% editlist = findeditlist(times, bestlags, MEDFILTEN, MINRUN, BINWIDTH)
%   <times>, <bestlags> are a set of best-lag estimates at
%   different times.  Search for a sequence of piecewise-constant
%   lag times, and return an editlist of edit times that will make
%   all the lags zero.  <editlist> is a series of rows like
%    <srcstart> <dststart> <dur>
%   meaning that the regions <srcstart>..<srcstart+dur> should be
%   placed at <dststart>..<dststart+dur> in the aligned output.
% 2013-12-30 Dan Ellis dpwe@ee.columbia.edu

if nargin < 3; MEDFILTLEN = 5; end
if nargin < 4; MINRUN = 6; end
if nargin < 5; BINWIDTH = 0.1; end

dtimes = median(diff(times));

% Strip any NaNs in bestlags
ii = find(~isnan(bestlags));
times = times(ii);
bestlags = bestlags(ii);

% Median filter the bestlag sequence
%MEDFILTLEN = 5;
filtLags = medfilt1(bestlags, MEDFILTLEN);

% Make a histogram of the bestlags
%BINWIDTH = 0.100;
hbins = min(filtLags):BINWIDTH:max(filtLags);
N = hist(filtLags, hbins);

% The shortest run we'll keep
%MINRUN = 6;

goodlags = hbins(find(N>=MINRUN));

nedits = 0;
editlist = zeros(nedits,3);

times = [times times(end)+5*dtimes];

for lag = goodlags
  timemsk = ( (filtLags >= lag - BINWIDTH) ...
              & (filtLags < lag + BINWIDTH) );
  starts = find(([0 timemsk] == 0) & ([timemsk 0] == 1));
  stops  = find(([0 timemsk] == 1) & ([timemsk 0] == 0));
  for i = 1:length(starts)
    start = starts(i);
    len = stops(i) - start;
    if len >= MINRUN
      nedits = nedits + 1;
      meanlag = mean(filtLags(start:start+len-1));
      editlist(nedits,:) = [times(start)+meanlag, times(start), ...
                            times(stops(i)-1)-times(start)];
    end
  end
end

  
% sort return by start time
[vv,xx] = sort(editlist(:,1));
editlist = editlist(xx,:);

% fill in gaps in dest by extending forward
% first time fills back
firsttime = min(editlist(1,[1 2]));
editlist(1,:) = editlist(1,:) + [-firsttime -firsttime firsttime];

% rest fill forward
for i = 2:size(editlist, 1)
  editlist(i-1, 3) = min(diff(editlist([i-1,i],[1 2]),1));
end

% final fills to end
