function [opts, msg] = get_options(type, tmpOptions)
% GET_OPTIONS load and check an options structure 
%  [OPTS, MSG] = GET_OPTIONS(TYPE, OPTS) loads an options structure 
%  and checks the validity of the file. If a structure is given, 
%  this is useful to check it is a valid options structure.
%
%  The options are returned in OPTS and MSG reports the error
%  encountered when checking the file.
%  
%
% Barry-John Theobald, b.theobald@uea.ac.uk
% School of Information Systems, University of East Anglia,
% Norwich, NR4 7TJ, UK
%
% Version 1.0

% HISTORY:
%     19/11/2002 - 1.0 - Initial revision


% Must specify the type to options we are looking for
if((nargin < 1) | ~ischar(type))	
	error('TYPE must a string defining the type of options'); 
end


if((nargin < 2) | isempty(tmpOptions))
	% No - filename or options given, prompt
	[fname pname] = uigetfile('*.mat', 'Load options');
	if(~any(fname)) 
		opts = [];
		msg = 'Cancelled by user';
		return;	
	end
	tmpOptions = strcat(pname, fname);
end


% If we have a file name, try and load
msg = '';
if(ischar(tmpOptions))
	eval(sprintf('tmpOptions = load(''%s'');', tmpOptions), ...
		sprintf('msg = ''Could not load from file: %s'';', tmpOptions));
end


% Did we load from the file?
if(~isempty(msg))
	opts = [];
	return;
end



% tmpOptions must be a struct here, either options were passed, 
% or the load function is returning a structure.
if(~isstruct(tmpOptions))
	opts = [];
	msg = 'Given options are invalid';
	return;
end

% First check if the structure itself is valid
if(isfield(tmpOptions, 'Type') & strcmp(tmpOptions.Type, type))
	opts = tmpOptions;
	msg = 'The given options are valid';
	return
end

% If we have got to here were are probably dealing with a structure from
% the load function. Just check the fields for an options structure
names = fieldnames(tmpOptions);
% Find the options in the variables stored in the given file
for k = 1:length(names)
	% Check for a structure, with a field 'Type' and the value 'soptions'.
	if(isstruct(eval(sprintf('tmpOptions.%s', char(names(k))))) & ...
			isfield(eval(sprintf('tmpOptions.%s', char(names(k)))), 'Type') & ...
			strcmp(eval(sprintf('tmpOptions.%s.Type', char(names(k)))), type))
		opts = eval(sprintf('tmpOptions.%s', char(names(k))));
		msg = 'Options loaded from disc and are valid';
		return;
	end
end


% Finally getting to this point means something is wrong.
% The options are not valid.
opts = [];
msg = 'Options are invalid or not stored in the given file';