function [token,remain] = strtok(x,delim)
%MATLAB Code Generation Library Function
%
% Limitations:
% 
%  1. Does not support a cell array for the first argument

%   Copyright 1984-2015 The MathWorks, Inc.
%#codegen

eml_invariant(nargin > 0, ...
    'MATLAB:minrhs');
coder.internal.prefer_const(x);
eml_invariant(~iscell(x), 'Coder:toolbox:CellArraysNotSupported', mfilename);
eml_invariant(isvector(x), ...
    'Coder:MATLAB:strtok_inputMustBeVector');
if nargin == 1
    delim = char([9,10,11,12,13,32]); % MATLAB hardcodes this set.
else
    coder.internal.prefer_const(delim);
end
[itoken,iremain] = find_token(x,delim);
remain = x(iremain:end);
token = x(itoken:iremain-1);

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

function [itoken,iremain] = find_token(x,delim)
n = coder.internal.indexInt(numel(x));
k = coder.internal.indexInt(1);
% Skip over leading delimiters.
while k <= n && isdelim(x(k),delim)
    k = k + 1;
end
itoken = k;
while k <= n && ~isdelim(x(k),delim)
    k = k + 1;
end
iremain = k;

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

function p = isdelim(c,delim)
coder.internal.prefer_const(delim);
% We expect a very small set of delimiters, so we just do a linear search.
for k = 1:numel(delim)
    if c == delim(k)
        p = true;
        return
    end
end
p = false;

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