function peaks = localpeaks_cheriton(x,mode,endFlag)

% LOCALPEAKS Find local peaks and troughs in a vector
% 
% SYNTAX
% 
%     peaks = localpeaks(X)
%     peaks = localpeaks(X,MODE)
% 
% 
% DESCRIPTION
% 
% peaks = localpeaks(X) locates the local peaks in vector X.
% 
% peaks = localpeaks(X,MODE) locates local features specified by MODE. MODE
% can be set to 'peaks' (default), 'troughs' in order to identify local
% troughs or 'both' in order to identify both local peaks and troughs.
% 
% Copyright Chris Hummersone 2010
% Modified by James Bramante, September 4, 2015, adding an option to
% include endpoints of vector in the search.

if ~isvector(x)
    error('Input must be a vector')
end

if (nargin < 2) || isempty(mode)
    mode = 'peaks';
end

if nargin < 3
    endFlag = 0;
end

switch lower(mode)
    case 'peaks'
        % do nothing
        peaks = find_peaks(x,endFlag);
    case 'troughs'
        peaks = find_peaks(-x,endFlag);
    case 'both'
        peaks = find_peaks(x,endFlag) | find_peaks(-x,endFlag);
    otherwise
        error('Unknown localpeak mode. Please specify ''peaks'', ''troughs'' or ''both''');
end

end


function peaks = find_peaks(x,endFlag)

if endFlag
    x = vect_cat(2,[min(x)],x,[min(x)]);
end
peaks = false(size(x));
peaks(2:end-1) = sign(x(2:end-1)-x(1:end-2)) + sign(x(2:end-1)-x(3:end)) > 1;
if endFlag
    peaks = peaks(2:end-1);
end

end