function sessions = get_sound_sessions(sound,collapse)

% get_sound_sessions - get the recording session boundaries
% ---------------------------------------------------------
%
% sessions = get_sound_sessions(sound)
%
% Inputs:
% -------
% sound - an XBAT sound structure
% collapse - collapse sessions to recording time
%
% Outputs:
% --------
% sessions - vector of session start/end times

%--------------------------------
% Author: Matt Robbins
%--------------------------------
% $Revision$
% $Date$
%--------------------------------

%-------------------------
% HANDLE INPUT
%-------------------------

%--
% return empty for no sessions
%--

if isempty(sound.time_stamp)
	sessions = []; return;
end

if ~isfield(sound.time_stamp, 'table')
	sessions = []; return;
end
	

if isempty(sound.time_stamp.table)
	sessions = []; return;
end

%--
% get collapse state from sound if not provided
%--

% NOTE: this allows override of sound collapse state

if nargin < 2 || isempty(collapse)
	collapse = sound.time_stamp.collapse;
end

%-------------------------
% BUILD SESSIONS
%-------------------------

durations = diff([sound.time_stamp.table(:, 1); sound.duration]);

if collapse
	start_times = sound.time_stamp.table(:, 1);
else
	start_times = sound.time_stamp.table(:, 2);
end

end_times = start_times + durations;

sessions = empty(struct('start', [], 'end', []));

for k = 1:length(start_times)
	sessions(end + 1) = struct('start', start_times(k), 'end', end_times(k));
end

