function varargout = pagesvd(varargin)
%PAGESVD   Page-wise singular value decomposition for codistributed array.
%   S = PAGESVD(X)
%   [U,S] = PAGESVD(X)
%   [U,S,V] = PAGESVD(X)
%   [...] = PAGESVD(X, 'econ')
%   [...] = PAGESVD(..., OUTPUTFORM)
%   
%   See also CODISTRIBUTED, PAGEFUN.


%   Copyright 2021 The MathWorks, Inc.

narginchk(1, 3);
nargoutchk(1, 3);

% Gather trailing arguments.
if nargin >= 2
    varargin(2:end) = distributedutil.CodistParser.gatherElements(varargin(2:end));
end

A = varargin{1};
% Call in-memory if A is not codistributed.
if ~iscodistributed(A)
    [varargout{1:nargout}] = pagesvd(varargin{:});
    return
end

% Throw the same error as in-memory PAGESVD.
if issparse(A)
    error(message("MATLAB:pagesvd:noSVDsparse"));
end

% PAGESVD does not support the 0 economy argument, but SVD does and so does
% PAGEFUN(@svd, _).
if numel(varargin) > 1 && ...
        isnumeric(varargin{2}) && isscalar(varargin{2}) && varargin{2} == 0
    error(message("MATLAB:pagesvd:invalidOption"));
end

% Finally call PAGEFUN.
[varargout{1:nargout}] = pagefun(@svd, varargin{:});
end

