function sb = swimbout_detect(bonset, boffset, sr, ibi_th, bst_num, sbd_th)

% Input
% -------------------------------------------------------------------------
% bonset: burst onset times (array)
% boffset: burst offset times (array)
% sr: sampling rate
% ibi_th: maximum inter-burst-interval to determine if two bursts belong
%       to the same swimming bout
% bst_num: minimum burst number that a swimming bout should contain for data
%       analysis consideration.
% sbd_th: minimum swimming bout duration
%
% Output
% -------------------------------------------------------------------------
% sb: burst onset and ofset times (2-column matrix)
  
% --------------------------------------------------------------
% main function
%---------------------------------------------------------------

% check that bonset and boffset have same lengths
if length(bonset)~=length(boffset)
    error('There is a mismatch btwn onset and offset timing of bursts');
end

% initialization
swimboutonset = bonset(1);       % swimming bout onset time

n = 0;                      % burst index
count = 0;                  % number of bursts 
sb = [];               % swimming bout onset and offset times and burst number 

while n < length(bonset)
    
    n = n + 1;
    count = count + 1;
    
    if n == length(bonset)
        
        swimboutoffset = boffset(n,1);
        sb = [sb;[swimboutonset,swimboutoffset,count]];
    
    else
        
        if bonset(n+1,1) - boffset(n,1) > ibi_th*sr
        
            swimboutoffset = boffset(n,1);
            sb = [sb;[swimboutonset,swimboutoffset,count]];
        
            % initialize variables
            swimboutonset = bonset(n+1);
            count = 0;
        
        end
        
    end
    
end

% delete bursts that contain very few spikes or with short duration 
tempi = sb(:,3)<bst_num | sb(:,2)-sb(:,1)<sbd_th;
sb(tempi,:) = [];

%isolate initial bursts of each swim
