function [narg, method, extrapVal] = methodAndExtrapval(varargin)
%METHODANDEXTRAPVAL parses the method and ExtrapVal from the arguments
%   [NARG, METHOD, EXTRAPVAL] = METHODANDEXTRAPVAL(VARARGIN)
%   Parses VARARGIN to extract METHOD, and EXTRAPVAL and returns the number
%   of remaining arguments in NARG. This is a common utility function used
%   by INTERP2, INTERP3, INTERPN
%

%   Copyright 2012-2021 The MathWorks, Inc.

narg = nargin;
extrapVal = [];
if isnumeric(varargin{end}) && isscalar(varargin{end}) && ...
        matlab.internal.datatypes.isScalarText(varargin{end-1})
    % User supplied an extrap val
    extrapVal = varargin{end};
    extrapVal = distributedutil.CodistParser.gatherIfCodistributed(extrapVal);
    method_arg = varargin{end-1};
    narg = narg-2;
elseif matlab.internal.datatypes.isScalarText(varargin{end})
    method_arg = varargin{end};
    narg = narg-1;
else
    method_arg = 'linear';
end

% Parse the method_arg

if startsWith(method_arg, '*')
    method_arg = method_arg(2:end);
    % TODO issue a deprecation WARNING
end
method_arg = lower(method_arg);
if startsWith(method_arg, 'n')
    method = 'nearest';
elseif startsWith(method_arg, 'l') || startsWith(method_arg, 'bil')
    method = 'linear';
elseif startsWith(method_arg, 's')
    method = 'spline';
elseif startsWith(method_arg, 'c') || startsWith(method_arg,'bic')
    method = 'cubic';
elseif startsWith(method_arg, 'm')
    method = 'makima';
else
    method = method_arg;
end

end
