function g = harray_select(h,varargin)

% harray_select - select elements from an harray array
% ----------------------------------------------------
%
% g = harray_select(h,'field','value', ... )
%
% Input:
% ------
%  h - harray structure array
%  field - selection field
%  selection value
%
% Output:
% -------
%  g - selected harray elements

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 976 $
% $Date: 2005-04-25 19:27:22 -0400 (Mon, 25 Apr 2005) $
%--------------------------------

%--
% get field value pairs
%--

% TODO: add allowed fields

[field,value] = get_field_value(varargin);

%--
% select harray elements
%--

g = h;

for k = 1:length(field) 
	
	%--
	% perform selection based on field
	%--
	
	switch (field{k})
		
		%--
		% select by level
		%--
		
		case ('level')
				
			g = g(find(harray_get(g,'level') == value{k}));
			
		%--
		% select by row, column, or full position
		%--
		
		% NOTE: currently this supports single index selection
		
		case ({'row','col','position'})
			
			%--
			% get position
			%--
			
			pos = harray_get(g,'position');
			
			%--
			% select row, column or full index
			%--
			
			switch (field{k})
				
				case ('row')
					g = g(find(pos(:,1) == value{k}));
				
				case ('col')
					g = g(find(pos(:,2) == value{k}));
					
				case ('position')
					g = g(find(sum(pos == ones(size(pos,1),1) * value{k},2) == 2));
					
			end
			
		%--
		% select by parent
		%--
		
		case ('parent')
					
			g = g(find(harray_get(g,'parent') == value{k}));
		
		%--
		% select parent of child
		%--
		
		case ('child')
			
			% NOTE: children are returned as a cell array of matrices
			
			values = harray_get(g,'children');
			
			for j = 1:length(values)
				
				% NOTE: a child has a single parent so we can break
				
				if (~isempty(find(values{k} == values{j})))
					g = g(j); break;
				end
				
			end
			
		%--
		% select ancestors
		%--
		
		case ('ancestors')
			
		%--
		% select descendants
		%--
		
		case ('descendants')
			
		%--
		% select by index pattern
		%--
		
		case ('index')
		
		%--
		% unrecognized selection field
		%--
		
		otherwise
			
	end
	
end