function savestruct(fname,x)
% savestruct  Convert an object to a struct and save field by field.
%
% Syntax
% =======
%
%     savestruct(FNAME,X)
%
% Input arguments
% ================
%
% * `FNAME` [ char ] - File name.
%
% * `X` [ .... ] - Object to be saved.
%
% Description
% ============
%
% `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.

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

% Allow both savestruct(fname,d) and savestruct(d,fname).
if (isobject(fname) || isstruct(fname) || iscell(fname)) && ischar(x)
    [fname,x] = deal(x,fname);
end

cl = class(x);
switch cl
    case {'model','VAR','container','tseries'}
        status = warning();
        warning('off','MATLAB:structOnObject');
        x = saveobj(x);
        x = struct(x);
        warning(status);
    case 'struct'
        % Do nothing.
    otherwise
        utils.error('Cannot save %s objects using SAVESTRUCT.',cl);
end

x.SAVESTRUCT_CLASS = cl; %#ok<STRNU>

% Save individual fields of underlying struct.
save(fname,'-struct','x','-mat');

end