function varargout = A_EPdetect2(EPSource,Th,Int,fs,ThM)
% OUPUT=A_EPdetect2(EPSource,Th,Int,F,ThM)
%    Output is marked as 1 in the corresponding slots of "EPSource" array
%    EPdetect2 is for compatibility for Matlab 2014a, otherwise use
%    EPdetect
% Detailed descrption
%"EPSource": a 1D array for threshold detection
% "Th": Threshold
% "Int": minimal selected time interval for EP 
%       (has to silent longer than this interval), defined in second
% "F": sampling frequency for the Source
% "ThM": Thresholding method: 1==positive thresholding; -1==negative
%        tresholding
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% Main function %%%%
if size(EPSource,1)>=2;
    EPSource=EPSource';
end
TpInt(1:Int*fs-1)=1; % defined the Timepoints(Tp)for detection interval
% thresholding source
if ThM==1;
    Data=(EPSource>=Th);
    %EPSource(2,:)=(EPSource>=Th);
else if ThM==-1;
        Data=(EPSource<=Th);
        %EPSource(2,:)=(EPSource<=Th);        
    else
        error('Wrong threhold method')
        return
    end
end
% define detection points
Data=double(Data);
DTh=conv(Data,TpInt);
Data(2,:)=DTh(1:length(Data)); % Data is a logic struture allow only 0 or 1
Data=logical(Data);
%DTh(2:3,1:length(Data))=Data;
DetPoint=Data(2,:)-[0,Data(2,1:end-1)];
%%%%%% Define output %%%%%
varargout{1}=DetPoint;
end

