function y = pBesselCommon(fcn, errScaleNotScalar, errDimMismatch, nu, z, scale)
%pBesselCommon Common logic for all codistributed Bessel functions
%   Y = codistributed.pBesselCommon(FCN, ERRSCALENOTSCALAR, ERRDIMMISMATCH, NU, Z, SCALE)
%   performs some input checking and throws ERRSCALENOTSCALAR if SCALE is not
%   scalar and ERRDIMMISMATCH if NU and Z are not of the correct dimension.
%   It then calls FCN with the relevant arguments.


%   Copyright 2013-2021 The MathWorks, Inc.

narginchk(5, 6); % Scale is optional

% The SCALE parameter should be scalar and can be gathered.
% NU and Z are both "data" so we use the binary op helper.

% If provided, check SCALE is scalar before gathering
if nargin>5
    if ~isscalar(scale)
        throwAsCaller(MException(message(errScaleNotScalar)));
    end
    scale = distributedutil.CodistParser.gatherIfCodistributed(scale);
    
    fcncall = @(a,b) fcn(a, b, scale);
else
    fcncall = fcn;
end

% Inputs nu and z must be the same size or one must be a scalar.
if ~isequal(size(nu), size(z)) && ~(isscalar(nu) || isscalar(z))
    throwAsCaller(MException(message(errDimMismatch)));
end

try
    y = codistributed.pElementwiseOp(fcncall, nu, z);
    return;
catch E
    throwAsCaller(E);
end

