function discard = discard_lower_quality(detection,ix)

% discard_lower_quality - determine overlapped events to discard
% --------------------------------------------------------------
%
% discard = discard_lower_quality(detection,ix)
%
% Input:
% ------
%  detection - detection array
%  ix - indices to consider for overlap
%
% Output:
% -------
%  discard - indices of events to discard

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 1000 $
% $Date: 2005-05-03 19:36:26 -0400 (Tue, 03 May 2005) $
%--------------------------------

% NOTE: this code needs some serious cleaning up and optimization

% NOTE: we have to separate events by channel to perform this computation

%--
% get indices of detections from this block
%--

A = event_intersect(detection(ix));

A = triu(A,1);

%--
% initialize output
%--

discard = [];

%--
% there are overlapped events
%--

% TODO: flatten this with a return on no intersection before it

if (full(sum(A(:))))

	%--
	% look through rows of intersection matrix
	%--
	
	for k = 1:length(ix)

		%--
		% check for overlapping events
		%--
		
		overlap = find(A(k,:));
		
		if (~isempty(overlap))

			clear dix; clear value;
		
			%--
			% get indices and values from overlapping events
			%--
			
			% event on diagonal
			
			dix(1) = ix(k);
			value(1) = detection(ix(k)).detection.value;

			% off-diagonal events
			
			for j = 1:length(overlap)

				dix(j + 1) = ix(overlap(j));
				value(j + 1) = detection(ix(overlap(j))).detection.value;

			end 
			
			%--
			% setup quality test
			%--
						
			test = [dix', struct_field(value,'corr')];

			%--
			% select maximum event to keep
			%--
			
			[ignore,tmp] = max(test(:,2));

			%--
			% discard non-maximum events
			%--
			
			% NOTE: we do this by removing the best from the list and
			% adding the rest to the discard array
			
			test(tmp(1),:) = []; % NOTE: select the first entry to handle possible ties
							
			discard = [discard; test(:,1)];
			
		end

	end
		
end

%--
% get template mode information from detections
%--

% NOTE: the template mode is temporarily stored in the userdata

mode = struct_field(detection(ix),'userdata');

%--
% update discard list to include reject mode templates
%--

% NOTE: the number 3 is the code for rejection

rix = find(mode == 3);

if (~isempty(rix))
	rix = ix(rix)';
	discard = [discard; rix];
end

%--
% compute unique discard indices
%--

discard = unique(discard); 

%--
% update discard list to exclude non-exclusive templates
%--

% NOTE: the number 2 is the code for always keeping

kix = find(mode == 2);

if (~isempty(kix))
	kix = ix(kix)';
	discard = setdiff(discard,kix);
end