function R = randg(A, varargin)
%RANDG Gamma random numbers (unit scale) on the GPU.
%   R = RANDG(A)
%   R = RANDG(A,M,N,...) or R = RANDG(A,[M,N,...])
%   R = RANDG(..., CLASSNAME)
%   R = RANDG(..., "like", G)
%
%   The calculation is performed on the GPU only if A or G is on the GPU or
%   CLASSNAME is "gpuArray".
%
%   See also randg, gpuArray.

% Copyright 2019 The MathWorks, Inc.

% We might get here because a dimension is on the GPU. If so we should
% gather them and call back to the CPU version.

% Check for "like". 
if nargin>2 && strcmp(varargin{end-1},"like")
    prototype = varargin{end};
    runOnGPU = isa(prototype, "gpuArray");
    
elseif isa(A, "gpuArray")
    runOnGPU = true;
    % If the trailing arg was a class name other than gpuArray, cast A to
    % that and replace it with "like" A.
    if nargin>1 && matlab.internal.datatypes.isScalarText(varargin{end})
        if ~strcmp(varargin{end}, "gpuArray")
            try
                A = cast(A, varargin{end});
            catch
                error(message('stats:randg:BadInputType'));
            end
        end
        varargin(end) = [];
    end
    varargin = [varargin, {"like", A}];
        
elseif nargin>1 && strcmp(varargin{end}, "gpuArray")
    runOnGPU = true;
    % Just requested running on the GPU. All other type traits should be
    % based on A. Replace with "like" an empty gpuArray version of A.
    varargin = [varargin(1:end-1), {"like", gpuArray(A([]))}];
    
else
    % No valid reason to run on GPU
    runOnGPU = false;
end
    
if runOnGPU
    R = internal.stats.gpu.randg(A, varargin{:});
else
    % Gather all and call into the standard version
    [A, varargin{:}] = gather(A, varargin{:});
    R = randg(A,varargin{:});
end
