function [spikesM, spikesm] = detecspike(sig,thrld,winsize,ifplot)

% detect spike of a signal by threshold
% input:
%     sig: signal
%     thrld: threshold to detect spike
%     winsize: the windowsize
%     ifplot: whether to create plot, 1=yes, 0=no
% output:
%     spikesM: index where datapoints were regarded as spikes (max)
%     spikesm: index where datapoints were regarded as spikes (min)

% sig = data(:,4);
% winsize = 20;
% thrld = 1.5;

% Code writer: Hui-Wen Yang 2019 @GICE, NTU and LIBSA, NCU
% Please cite:
% Hui-Wen Yang ; Shyh-Kang Jeng ; Hsu-Wen V. Young ; Chen Lin ; Yung-Hung Wang ; 
% Kun Hu ; Men-Tzung Lo. (2019). A Minimum Arclength Method for Removing Spikes 
% in Empirical Mode Decomposition. IEEE Access PP(99):1-1 ?January 2019

if nargin<4
    ifplot = 1;
end

[spmax, spmin, ~] = extrema(sig);
w = floor(winsize/2);

for m = 1:2
    if m==1, sp = spmax;% maximum
    else sp = spmin; end %minimum
    len = size(sp,1);
    olrmark = zeros(len,1);
    mds = zeros(len,1);
    wss = mds; wes = mds;
	for wi = w:len-w
		% Determine the starting and ending of window
		if len - wi < winsize, ws = len - winsize; we = len; % at the tail of data
        elseif wi < winsize,    ws = 1;	we = winsize; % at the head of data
        else ws = wi-w; we = ws+winsize-1;
		end
		iint = ws:we;
        seg = diff(sp(iint,2));
        %seg = sp(iint,2);
		md = nanmedian( seg );
        mds(wi) = md; wss(wi) = ws; wes(wi) = we;
        sdd = nanstd(sp(iint,2));
%         sdd = quantile(seg, 0.75) - md;
        ub = md+sdd*thrld; lb = md-sdd*thrld;
		% percentage of median as tolerance
		if seg(w) > ub && m == 1
            olrmark(wi) = 1;
        end
        if seg(w) < lb && m == 2
            olrmark(wi) = 1;
        end

    end

    if m == 1, spikesM = spmax(olrmark==1,1);
    else    spikesm = spmin(olrmark==1,1); 
    end
end

    
if ifplot ==1
    figure; hold all;
    plot(sig)
    plot(spikesM, sig(spikesM),'o');
    plot(spikesm, sig(spikesm),'*')
    legend('raw data', 'detected spike (max)','detected spike (min)')
end