function [peakmid, peakwidth] = findPeaks(X, minheight, minwidth, minsep)
% findPeaks is a function to find peaks in a dataset (vector) X.
% minheight is the cutoff height for peaks
% minwidth is the minimum width of a peak
% minsep is the minimum separation between peaks (peaks closer than this
% will be merged together.
% peakmid is a vector of peak midpoints;
% peakwidth is a vector of peak widths.
i = 1; % X index
n = 1; % peak number
peakL = 0;
peakR = 0;
N = length(X); 
X = [X repmat(minheight-1, 1, minsep)]; % pad with small values
while (i < N)
    % find left-hand edge of a peak
    while (i < (N-minwidth) && any(X(i:(i+minwidth)) < minheight) )
        i = i + 1;
    end;
    if (i >= N-minwidth)
        break;
    end;
    peakL(n) = i;
    % find right-hand edge of the peak
    while (i < (N-minsep) && any(X(i:(i+minsep)) > minheight))
        i = i + 1;
    end;
    peakR(n) = i;
    n = n + 1;
end;
peakmid = (peakL + peakR) / 2;
peakwidth = peakR - peakL;

    
