function x = bssgridpoints(xgrid)
% GRIDPOINTS Generate the grid points as an N by NDIM matrix where N is the
% total number of points.
%
% % INPUTS:
%
%    xgrid:
%       A cell containing grid vectors defining a compact grid used
%       for a gridded interpolation.
%
% OUTPUTS:
%
%    x:
%       The values for the gridded points as an N by NDIM matrix.
%
%       GRIDPOINTS performs the same function as NDGRID except that it
%       places all of the values into a matrix of gridded data points, one
%       point per row, rather than producing the full grid as separate
%       variables.
%

%
% Copyright 2014-2018 Biometrics Northwest LLC
%

%
% Created: 2016-04-22
% Author : Kevin R. Gehringer
%

ndims = length(xgrid);
if ( ndims == 1 )
    if (iscolumn(xgrid{1}) )
        x = xgrid{1};
    else
        x = xgrid{1}';
    end
else
    ndim = zeros(1,ndims);
    for i = 1:ndims
        ndim(i) = length(xgrid{i});
    end
    cpn = cumprod(ndim);

    x = zeros(cpn(end),ndims);
    tmpnd = ndim(2:end);
    if (iscolumn(xgrid{1}) )
        x(:,1) = repmat(xgrid{1},prod(ndim(2:end)),1);
    else
        x(:,1) = repmat(xgrid{1}',prod(ndim(2:end)),1);
    end
    for i = 2:ndims-1
        tmpnd(i-1) = 1;
        if (iscolumn(xgrid{i}) )
            tmp = repmat(xgrid{i}',cpn(i-1),1);
        else
            tmp = repmat(xgrid{i},cpn(i-1),1);
        end
        x(:,i) = repmat(tmp(:),prod(tmpnd),1);
    end
    if (iscolumn(xgrid{ndims}))
        tmp = repmat(xgrid{ndims}',cpn(ndims-1),1);
    else
        tmp = repmat(xgrid{ndims},cpn(ndims-1),1);
    end
    x(:,ndims) = tmp(:);
end
end
