function [y,nonnan] = castLikeAndReplaceNaNs(x,nanrep)
%MATLAB Code Generation Private Function
%
%    Generates efficient code for:
%    Y = cast(X,'like',NANREP);
%    Y(isnan(X)) = NANREP;
%    NONNAN = coder.internal.indexInt(~isnan(X));
%
%   Copyright 2002-2019 The MathWorks, Inc.
%#codegen

coder.internal.prefer_const(nanrep);
coder.internal.allowHalfInputs;
coder.internal.allowEnumInputs;
if ~isfloat(x)
    % Don't bother looking for what can't be.
    if issparse(x)
        y = cast(x,'like',sparse(nanrep));
    else
        y = cast(x,'like',nanrep);
    end
    if nargout == 2
        nonnan = ones(size(x),coder.internal.indexIntClass);
    end
elseif nargout == 2
    [y,nonnan] = replaceNaNsIter(x,nanrep);
else
    y = replaceNaNsIter(x,nanrep);
end

%--------------------------------------------------------------------------

function [y,nonnan] = replaceNaNsIter(x,nanrep,y,nonnan,dim,varargin)
coder.inline('always');
coder.internal.prefer_const(nanrep);
ONE = coder.internal.indexInt(1);
ND = coder.internal.indexInt(coder.internal.ndims(x));
if issparse(x)
    y = spfun(@(d)replaceNaNsIter(d,nanrep),x);
    return
end
if nargin >= 5
    coder.internal.prefer_const(dim);
else
    % Preallocate the outputs.
    if ~isreal(x) && isreal(nanrep)
        y = eml_expand(complex(nanrep),size(x));
    else
        y = eml_expand(nanrep,size(x));
    end
    if nargout == 2
        nonnan = zeros(size(x),coder.internal.indexIntClass);
    else
        nonnan = coder.internal.indexInt([]);
    end
    if coder.isRowMajor
        dim = ONE;
    else
        dim = ND;
    end
end
if dim >= ONE && dim <= ND
    if coder.isRowMajor
        if nargout == 2
            for k = ONE:size(x,dim)
                [y,nonnan] = replaceNaNsIter(x,nanrep,y,nonnan,dim + 1, ...
                    varargin{:},k);
            end
        else
            for k = ONE:size(x,dim)
                y = replaceNaNsIter(x,nanrep,y,nonnan,dim + 1, ...
                    varargin{:},k);
            end
        end
    else
        if nargout == 2
            for k = ONE:size(x,dim)
                [y,nonnan] = replaceNaNsIter(x,nanrep,y,nonnan,dim - 1, ...
                    k,varargin{:});
            end
        else
            for k = ONE:size(x,dim)
                y = replaceNaNsIter(x,nanrep,y,nonnan,dim - 1, ...
                    k,varargin{:});
            end
        end
    end
else
    xk = x(varargin{:});
    if ~isnan(xk)
        y(varargin{:}) = xk;
        if nargout == 2
            nonnan(varargin{:}) = 1;
        end
    end
end

%--------------------------------------------------------------------------
