function pal = get_palette(par, str, data)

% get_palette - get palette figure handle by name
% -----------------------------------------------
%
% pal = get_palette(par, name, data)
%
% Input:
% ------
%  par - parent handle
%  name - palette name
%  data - parent data (where palettes are registered)
%
% Output:
% -------
%  pal - palette handle

% TODO: rename variables as in help

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 3168 $
% $Date: 2006-01-11 16:54:20 -0500 (Wed, 11 Jan 2006) $
%--------------------------------

% TODO: refactor completely

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

%--
% get palette through root
%--

% TODO: fix this, it's wrong

if isempty(par) || (par == 0)
	pal = findobj(get(0, 'children'), 'flat', 'name', str); return;
end

%--
% get parent data if needed
%--

if (nargin < 3) || isempty(data)
	data = get_browser(par);
end

%-------------------------
% GET PALETTE
%-------------------------

%--
% get palettes from parent
%--

% NOTE: consider storage in 'data.APP_CODE.palettes' with the application code stored in the parent tag

try
	pals = data.browser.palettes;
catch
	pals = data.browser.palette.handle;
end

%--
% remove stranded palette handles
%--

for k = length(pals):-1:1
	if ~ishandle(pals(k))
		pals(k) = [];
	end
end

if isempty(pals)
	pal = []; return;
end

% NOTE: return all palettes if no selection

if (nargin < 2) || isempty(str)
	pal = pals; return;
end

%--
% select palette by name
%--

% this requires that proper handles in the palette array

% for the moment deal with stranded handles in the palette array

try
	name = get(pals,'tag');
catch
	pal = []; return;
end

if (length(pals) == 1)
	
	tmp = name;
	clear name;
	name{1} = tmp;
	
end
		
ix = [];	

for k = 1:length(name)	
	
	%--
	% find string at the end of the tag
	%--
		
	% this is a partial parsing of the tag string
	
	try
		flag = strcmp(name{k}(end - length(str) + 1:end),str);
	catch
		continue;
	end
	
	if (flag == 1)
		ix = k; break;
	end	
	
end

%--
% output palette figure handle
%--

if (~isempty(ix))
	pal = pals(ix);
else
	pal = [];
end
	