function [pdm, msg, PDMfile] = get_pdm(PDMfile)
% GET_PDM load and check a point distribution model 
%  [PDM, MSG] = GET_PDM(FNAME) loads a point distribution model and 
%  checks the validity of the file. If a structure is given, this 
%  is useful to check it is a valid point distribution model.
%
%  The point distribution model is returned in PDM and MSG contains
%  any errors encountered when opening, or checking the file.
%
%  The optional output is the path to and name of the PDM file loaded.
%
%
% Copyright (c),
% Barry-John Theobald, b.theobald@uea.ac.uk
% School of Information Systems, University of East Anglia,
% Norwich, NR4 7TJ, UK
%
% Version 1.1

% HISTORY:
%     21/11/2002 - 1.0 - Optionally return the filename
%     20/11/2002 - 1.0 - Initial revision


if((nargin < 1) | isempty(PDMfile))
	% No - prompt for it
	[fname pname] = uigetfile('*_pdm.mat', 'Load PDM');
	if(~any(fname)) 
		pdm = [];
		msg = 'Cancelled by user';
		return;	
	end
	PDMfile = strcat(pname, fname);
end

% Try and load the model
msg = '';
if(ischar(PDMfile))
	eval(sprintf('tmpPDM = load(''%s'');', PDMfile), ...
		sprintf('msg = ''Could not load from file: %s'';', PDMfile));
end

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


% tmpPDM must be a struct here, either a PDM was passed, 
% or the load function is returning a structure.
if(~isstruct(tmpPDM))
	pdm = [];
	msg = 'Given PDM is invalid';
	PDMfile = '';
	return;
end


% If a PDM was passed, just check the fieldnames
if(isfield(tmpPDM, 'Xm') & isfield(tmpPDM, 'P') & isfield(tmpPDM, 'b'))
	% The PDM is OK
	pdm = tmpPDM;
	msg = 'Given PDM is valid';
	return
end
	

% Must have used the load function - check the variables that were in the file
names = fieldnames(tmpPDM);
% Find the PDM in the variables stored in the given file
for k = 1:length(names)
	% Check for a structure, with a fields 'Xm', 'P' and 'b'
	if(isstruct(eval(sprintf('tmpPDM.%s', char(names(k))))) & ...
			isfield(eval(sprintf('tmpPDM.%s', char(names(k)))), 'Xm') & ...
			isfield(eval(sprintf('tmpPDM.%s', char(names(k)))), 'P') & ...
			isfield(eval(sprintf('tmpPDM.%s', char(names(k)))), 'b'))
		pdm = eval(sprintf('tmpPDM.%s', char(names(k))));
		msg = 'PDM loaded from disc and is valid';
		return;
	end
end


% Finally getting to this point means something is wrong.
pdm = [];
msg = 'PDM is invalid or not stored in the given file';
PDMfile = '';