function [FLAG,LIST] = isnan(THIS,varargin)
% isnan  Check for NaNs in model object.
%
% Syntax
% =======
%
%     [FLAG,LIST] = isnan(M,'parameters')
%     [FLAG,LIST] = isnan(M,'sstate')
%     [FLAG,LIST] = isnan(M,'derivatives')
%
% Input arguments
% ================
%
% * `M` [ model ] - Model object.
%
% Output arguments
% =================
%
% * `FLAG` [ `true` | `false` ] - True if at least one `NaN` value exists
% in the queried category.
%
% * `LIST` [ cellstr ] - List of parameters (if called with `'parameters'`)
% or variables (if called with `'variables'`) that are assigned NaN in at
% least one parameterisation, or equations (if called with `'derivatives'`)
% that produce an NaN derivative in at least one parameterisation.
%
% Description
% ============
%
% Example
% ========
%

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

if ~isempty(varargin) && (ischar(varargin{1}) &&  ~strcmp(varargin{1},':'))
    request = lower(strtrim(varargin{1}));
    varargin(1) = [];
else
    request = 'all';
end

if ~isempty(varargin) && (isnumeric(varargin{1}) || islogical(varargin{1}))
    alt = varargin{1};
    if isinf(alt)
        alt = ':';
    end
else
    alt = ':';
end

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

switch request
    case 'all'
        assign = THIS.Assign(1,:,alt);
        index = any(isnan(assign),3);
        if nargout > 1
            LIST = THIS.name(index);
        end
        FLAG = any(index);
    case {'p','parameter','parameters'}
        assign = THIS.Assign(1,:,alt);
        index = any(isnan(assign),3) & THIS.nametype == 4;
        if nargout > 1
            LIST = THIS.name(index);
        end
        FLAG = any(index);
    case {'sstate'}
        assign = THIS.Assign(1,:,alt);
        index = any(isnan(assign),3) & THIS.nametype <= 3;
        if nargout > 1
            LIST = THIS.name(index);
        end
        FLAG = any(index);
    case {'solution'}
        solution = THIS.solution{1}(:,:,alt);
        index = any(any(isnan(solution),1),2);
        index = index(:)';
        if nargout > 1
            LIST = index;
        end
        FLAG = any(index);
    case {'expansion'}
        expand = THIS.Expand{1}(:,:,alt);
        index = any(any(isnan(expand),1),2);
        index = index(:)';
        if nargout > 1
            LIST = index;
        end
        FLAG = any(index);
    case {'derivative','derivatives'}
        nalt = size(THIS.Assign,3);
        neqtn = length(THIS.eqtn);
        eqselect = true(1,neqtn);
        LIST = false(1,neqtn);
        FLAG = false;
        for ialt = 1 : nalt
            [~,~,nanderiv] = myderiv(THIS,eqselect,ialt,true);
            FLAG = FLAG || any(nanderiv);
            LIST(nanderiv) = true;
        end
        LIST = THIS.eqtn(LIST);
    otherwise
        error('Incorrect input argument: %s.',varargin{1});
end

end