function [A, count, errmsg, nextindex] = sscanf(inStr, formatSpec, varargin)
%MATLAB Code Generation Library Function

%   Limitations:
%   1. The %s and %[...] specifiers are not supported.
%   2. Returning an error message when sscanf fails to read all data is not
%   supported.
%   3. Returning the index of the position in str that immediately follows
%   the last character scanned is not supported.
%   4. If you read an integer value x into an integer format for which
%   intmax is smaller than x, the MATLAB output saturates at intmax. In the
%   generated code, this situation causes an overflow.

%   Copyright 2023 The MathWorks, Inc.
%#codegen

narginchk(2,3);

errmsg = "";
nextindex = 0;
coder.internal.assert(nargout < 3, 'Coder:toolbox:SscanfTwoOutputs')
coder.internal.assert(isstring(inStr)||ischar(inStr), 'Coder:toolbox:SscanfInvalidInput')

% if inStr is a string, convert it to char
inStrChar = char(inStr);
inStrCharRow = reshape(inStrChar,1,numel(inStrChar));
inStr = [inStrCharRow,0];

if nargin == 3
    coder.internal.assert(coder.internal.isBuiltInNumeric(varargin{1}), ...
        'Coder:toolbox:eml_assert_valid_size_arg_3', ...
        'IfNotConst','Fail');    
    sizeA = floor(full(varargin{1}));
    if (isscalar(sizeA) && ~isinf(sizeA)) || (~isscalar(sizeA) && ~isinf(sizeA(2)))
        coder.internal.assertValidSizeArg(sizeA);
    elseif ~isscalar(sizeA)
        coder.internal.assertValidSizeArg(sizeA(1));
    end
    if isscalar(sizeA) && isinf(sizeA)
        [A, count] = cSscanf(inStr, formatSpec);
    else
        [A, count] = cSscanf(inStr, formatSpec, sizeA);
    end    
else
    [A, count] = cSscanf(inStr, formatSpec);
end

end

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

function [A, count] = cSscanf(inStr, formatSpec, varargin)
fname = 'sscanf';
[A,count] = coder.internal.io.scanf(inStr, formatSpec, fname, varargin{:});

end