function spktimes = spike_detect(rcd, sr, mtd, v1, v2, spkd_th, ref_th, vflag) 


% variables
if nargin<8
    vflag = 0;
end

% --------------------------------------------------------------
% main function
%---------------------------------------------------------------

% normalize rcd
rcd = (rcd - mean(rcd)) / std(rcd);

% time
t=(1:length(rcd))'/sr;

if mtd=='MAN'
    
    fig = figure; 
    plot(t, rcd,'k'); 
    title('Click on two points along the y-axis to determine the min and max threshold values for spike detection'); 
    [~,trsh] = ginput(2);
    hold on;
    plot(t, trsh(1)*ones(length(rcd),1),'g','Linewidth',2);
    plot(t, trsh(2)*ones(length(rcd),1),'g','Linewidth',2);
    hold off;
    pause(2);
    close(fig);
    
else
    switch(mtd)

        case 'SDV'
            trsh(1) = v1*std(rcd);
            trsh(2) = v2*std(rcd);
        case 'RMS'
            trsh(1) = v1*rms(rcd);
            trsh(2) = v2*rms(rcd);
        case 'ABS'
            trsh(1) = v1;
            trsh(2) = v2;
        case 'MAX'
            trsh(1) = v1*max(rcd);
            trsh(2) = v2*max(rcd);
            
    end
end

% generate a binary spike train
bout = ones(length(rcd),1);
if trsh(1) > 0
    bout(rcd<trsh(1)) = 0;             
    bout(rcd>trsh(2)) = 0;             
else
    bout(rcd>trsh(1)) = 0;             
    bout(rcd<trsh(2)) = 0;             
end

% detect onset and offset spike
onbout = find(diff(bout)>0.5);                              % detect onset
offbout = find(diff(bout)<-0.5);                            % detect offset

% check any spike has been detected
if isempty(onbout) 
    
    disp('There are no detected spikes!'); 
    spktimes = [];

else
    
    % remove spikes not having onset and offset together
    if onbout(1) > offbout(1), offbout(1) = []; end
    if onbout(end) > offbout(end), onbout(end) = []; end

    % check if onset and offset arrays have the same lengnth
    if length(onbout) ~= length(offbout)
        display('There is a mismatch between between onset and offset data points');
        display(['length(onset) = ',num2str(length(onbout))]); 
        display(['length(offset) = ',num2str(length(offbout))]);        
    end

    % compute spike duration
    spkd = offbout - onbout;                                  

    % remove spikes with small duration
    onbout = onbout(spkd>spkd_th*sr);                      
    offbout = offbout(spkd>spkd_th*sr);
    
    % detect maximum value of each spikes

    if isempty(onbout) 
        
        disp('There are no detected spikes!'); 
        spktimes = [];
        
    else
        
        % compute inter-spike interval
        isi = onbout(2:end) - offbout(1:end-1);
        
        % remove spikes in the refractory period
        temp = isi<ref_th*sr; temp = temp+1;
        onbout(temp)=[]; 
        offbout(temp)=[];
        
        % detect spike peaks
        spktimes = nan(length(onbout),3);
        for k=1:length(onbout)
           [~,maxi] = max(rcd(onbout(k):offbout(k))); 
           spktimes(k,:) = [onbout(k), offbout(k), onbout(k)+maxi-1];
        end

    end
    
    % visualize detected spikes
    if vflag
        figure;
        hold on;
        plot(t,rcd,'k');
        plot(t(spktimes(:,3)),rcd(spktimes(:,3)),'o','MarkerSize',6,'MarkerEdgeColor','g','MarkerFaceColor','g');
        plot(t, trsh(1)*ones(length(rcd),1), 'r--','Linewidth',2);
        plot(t, trsh(2)*ones(length(rcd),1), 'r--','Linewidth',2);
        hold off;
        xlabel('Time (s)');
        
        figure;
        hist(rcd(spktimes(:,3)))
        
    end
    
end



