function [flag, g] = control_callback(par, pal, control, data)

% control_callback - update control in palette
% ------------------------------------------
%
% [flag, g] = control_callback(par, pal, control)
%
% Input:
% ------
%  par - parent figure of control if using palette name
%  pal - palette name or handle
%  control - control name
%
% Output:
% -------
%  flag - callback evaluation success
%  g - control handles

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 5940 $
% $Date: 2006-08-04 16:24:08 -0400 (Fri, 04 Aug 2006) $
%--------------------------------

% NOTE: there are some unclear aspects when calling with empty handle 'par'

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

%--
% try to get parent userdata
%--

if ((nargin < 4) || isempty(data))
	
	if (~isempty(par))
		data = get(par,'userdata');
	else
		data = [];
	end
	
end

%--
% check that control is a string
%--

% TODO: allow calling of this function with a single handle to control

% NOTE: then we could use 'get_callback_context' to get other information

if (~ischar(control))
	error('Control name must be a string.'); 
end

%-------------------------------------
% GET CONTROL HANDLES
%-------------------------------------

g = control_update(par,pal,control,[],data);

%--
% warn and return if we do not find the control
%--

if (isempty(g))
	
	warning(['Unable to find control ''' control ''' in parent figure.']);
	
	flag = 0; return;
	
end

%-------------------------------------
% TRY TO EVALUATE CALLBACK
%-------------------------------------

% NOTE: each control contains various uicontrol objects

flag = 0;

for k = 1:length(g)
	
	%--
	% get callback from objects that have callbacks
	%--
		
	% NOTE: for multiple uicontrols with callbacks, the first is evaluated
	
	callback = [];
	
	switch (get(g(k),'type'))
		
		case ('uicontrol')
			callback = get(g(k),'callback');
			
		case ('axes')
			callback = get(g(k),'buttondown');
			
	end
		
	%--
	% continue if no callback
	%--
	
	if (isempty(callback))
		continue;
	end
	
	%--
	% evaluate function handle callback
	%--
	
	switch (class(callback))
		
		%--
		% function handle based forms
		%--
		
		case ('cell')
			
			% NOTE: separate arguments and callback function handle
			
			args = callback(2:end); callback = callback{1}; 
			
			callback(g(k),[],args{:});
			
		case ('function_handle')
	
			callback(g(k),[]);
			
		%--
		% string to evaluate callback
		%--
		
		case ('char')
			
			eval(callback);
								
	end
	
end