function s = insertBefore(str,pos,text)
%INSERTBEFORE Insert text before a specified position.
%   S = INSERTBEFORE(STR, POS, TEXT)
%
%   Limitations:
%   Pattern objects are not supported.
%
%   See also INSERTBEFORE, TALL/STRING.

%   Copyright 2016-2020 The MathWorks, Inc.

narginchk(3,3);

% We require that the first input is the tall array and the others are
% plain strings or similarly sized tall arrays of strings. The POS input
% can also be a number.
tall.checkIsTall(upper(mfilename), 1, str);
str = validateAndMaybeWrap(str, mfilename, 1, {'string', 'cell'});
pos = validateAndMaybeWrap(pos, mfilename, 2, {'string', 'cell', 'numeric'});
text = validateAndMaybeWrap(text, mfilename, 3, {'string', 'cell'});

s = elementfun(@insertBefore, str, pos, text);

% Type is preserved, but size may have changed.
s.Adaptor = copySizeInformation(str.Adaptor, s.Adaptor);
end

function arg = validateAndMaybeWrap(arg, fcnName, argIdx, validTypes)
% Check a string input to make sure it is valid. If a char array, wrap it
% to prevent dimension expansion.

% Pattern objects are not supported
matlab.bigdata.internal.util.errorIfPatternInput('tall', arg);

if ~istall(arg) && ischar(arg)
    arg = wrapPositionInput(arg, argIdx);
else
    % Check tall or local input against valid types
    arg = tall.validateType(arg, fcnName, validTypes, argIdx);
end
end % validateAndMaybeWrap

