function findelem(node,elem,range,varargin)
% FINDELEM highlights some elements.
%
%    findelem(node,elem,range) finds all elements whose indices are in the
%    range array by displaying these elements in yellow.
%
%    findelem(node,elem) finds all elements.
%   
%    findelem(...,'noindex') skip the display of indices.
%
%    findelem(node,elem,range,'param','value','param','value'...) allows
%    additional patch param/value pairs to highlight the elements.
%    
% Example:
%     node = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0];
%     elem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8];
%     subplot(1,2,1);
%     showmesh(node,elem);
%     findelem(node,elem,[1 3],'noindex','FaceColor','r','MarkerSize',24);
%     subplot(1,2,2);
%     showmesh(node,elem);
%     findelem(node,elem);
%
%   See also findelem, findnode3, findedge.

% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

hold on
if (nargin==2)
    range = (1:size(elem,1))'; 
end
if islogical(range)
    range = find(range); 
end
if size(range,2)>size(range,1)
    range = range'; 
end

center=(node(elem(range,1),:)+node(elem(range,2),:)+node(elem(range,3),:))/3;
if length(range)<size(elem,1)
    x = [node(elem(range,1),1), node(elem(range,2),1), node(elem(range,3),1)]';
    y = [node(elem(range,1),2), node(elem(range,2),2), node(elem(range,3),2)]';
    h = patch(x,y,'y');
    if nargin > 3
        if strcmp(varargin{1},'noindex') || strcmp(varargin{1},'index')
            startidx = 2;
        else
            startidx = 1;
        end
        set(h,varargin{startidx:end});
    end
else
    plot(center(:,1),center(:,2),'o','LineWidth',1,'MarkerEdgeColor','k',...
         'MarkerFaceColor','y','MarkerSize',20);    
end
if (nargin <4) || ~(strcmp(varargin{1},'noindex'))
text(center(:,1)-0.01,center(:,2),int2str(range),'FontSize',14,...
    'FontWeight','bold','Color','b');
end