function varargout = aamio_loadModel(varargin)
% function varargout = aamio_loadModel(varargin)
%
%
% Dr. A. I. Hanna (2007)
error(nargchk(0,inf,nargin));
filename = '';
if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error(['Arguments to ', mfilename, ' must come param/value in pairs.'])
end
for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'filename'
            filename = varargin{i+1};
        otherwise
            error(['Unknown parameter name passed to ', mfilename, '.  Name was ' varargin{i}])
    end
end
if isempty(filename)
    modelname = [];
    [filename, pathname] = uigetfile('*.mat', 'Pick a Model File');
    if isequal(filename,0) || isequal(pathname,0)
        disp('User pressed cancel');
        varargout{1} = [];
        varargout{2} = filename;
        return
    end
    filename = [pathname, filesep, filename];
end
model = load(filename, '-mat');

if ~isfield(model, 'pdm')
    model = [];
else
    expected_fieldnames = {'Xm', 'P', 'b'};
    model = model.pdm;
    % if ~all(isfield(model, expected_fieldnames))
    %     model = [];
    % end
    for i=1:length(expected_fieldnames)
        if ~isfield(model, expected_fieldnames{i})
            model = [];
        end
    end
end
varargout{1} = model;
varargout{2} = filename;
return