function ext = extension_initialize(ext, context)

% extension_initialize - set extension parameters using context
% -------------------------------------------------------------
%
% ext = ext_initialize(ext, context)
%
% Input:
% ------
%  ext - extensions
%  context - context
%
% Output:
% -------
%  ext - initialized extensions

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

% TODO: add extension input check, eventually object extensions

%--
% handle multiple extensions recursively
%---

if (numel(ext) > 1)

	for k = 1:length(ext)
		ext(k) = extension_initialize(ext(k), context);
	end

	return;

end

%--------------------
% INITIALIZE
%--------------------

%--
% extract functions and update context
%--

fun = ext.fun; context.ext = ext;

%--
% create default parameters if needed
%--

if ~isempty(fun.parameter.create)

	try
		ext.parameter = fun.parameter.create(context);
	catch
		extension_warning(ext, 'Parameter creation failed.', lasterror); return;
	end

end

%--
% compile parameters if needed
%--

% NOTE: compilation should typically create new fields not clobber parameter fields

if ~isempty(fun.parameter.compile)

	try
		ext.parameter = fun.parameter.compile(ext.parameter, context);
	catch
		extension_warning(ext, 'Parameter compilation failed.', lasterror); return;
	end

end

%--
% set control values if needed
%--

if ~isempty(fun.parameter.control.create)
	
	% TODO: implement a better way of setting initial control values

	ext.control = ext.parameter;
	 
end

