function x = loadstruct(fname)
% loadstruct  Load object saved previously by SAVESTRUCT.
%
% Syntax
% =======
%
%     X = loadstruct(FNAME)
%
% Input arguments
% ================
%
% * `FNAME` [ char ] - File name.
%
% Output arguments
% =================
%
% * `X` [ ... ] - Object loaded.
%
% Description
% ============
%
% The functions `savestruct` and `loadstruct` were introduced to deal with
% some inefficiencies in standard saving and loading procedures in older
% Matlabs. In current versions of Matlab, this is no longer necessary, and
% `savestruct` and `loadstruct` functions are considered obsolete.
%

% -IRIS Toolbox.
% -Copyright (c) 2007-2008 Jaromir Benes.

%**************************************************************************

% Load all entries.
% Because keywords are loaded with underscores, fix their names.
list = who('-file',fname);
list = list(:).';
index = cellfun(@iskeyword,list);
if any(~index)
    % Silence warnings about unknown object classes.
    state = warning('query');
    warning('off'); %#ok<WNOFF>
    x = load('-mat',fname,list{~index});
    warning(state);
else
    x = struct();
end
if any(index)
    state = warning('query');
    warning('off','MATLAB:load:loadingKeywordVariable');
    temp = load('-mat',fname,list{index});
    temp = struct2cell(temp);
    for i = find(index)
        x.(list{i}) = temp{i};
    end
    warning(state);
else
    state = warning('query');
    warning('off'); %#ok<WNOFF>
    x = load('-mat',fname);
    warning(state);
end

% Determine class of the saved object.
if isfield(x,'SAVESTRUCT_CLASS')
    cl = x.SAVESTRUCT_CLASS;
    x = rmfield(x,'SAVESTRUCT_CLASS');
else
   if isfield(x,'IRIS_MODEL')
      cl = 'model';
      x = rmfield(x,'IRIS_MODEL');
   elseif isfield(x,'IRIS_VAR')
      cl = 'VAR';
      x = rmfield(x,'IRIS_VAR');
   elseif isfield(x,'IRIS_RVAR')
      cl = 'VAR';
      x = rmfield(x,'IRIS_RVAR');
   elseif isfield(x,'IRIS_TSERIES') || ( ...
         isfield(x,'start') && isfield(x,'data'))
      cl = 'tseries';
      x = rmfield(x,'IRIS_TSERIES');
   elseif isfield(x,'IRIS_CONTAINER')
      cl = 'container';
      x = rmfield(x,'IRIS_CONTAINER');
   else
      cl = 'struct';
   end
end

switch cl
    case 'model'
        x = model.loadobj(x);
    case 'VAR'
        x = VAR.loadobj(x);
    case 'tseries'
        x = tseries(x);
    case 'container'
        x = container.loadobj(x);
end

end
