function bsscheckmemory(n,type)
%BSSCHECKMEMORY  Check to see if available memory may be exceeded
%
% INPUTS:
%
%    n:
%        The NDIM by 1 or 1 by NDIM vector specifying the size of a
%        B-spline series partition or gridded interpolant.
%
%        Check to be sure the gridded interpolant will fit into available
%        memory. We do a coarse-grained check to see if 2*8*prod(ngrid) is
%        greater than 90% of available memory. If so, signal an error.
%
%        This value represents the size needed to store a B-spline series
%        gridded interpolant.
%
%    type:
%        This must be either 'bss' or 'grid'.
%
%        bss : checks against the size of a B-spline series data structure
%        grid: checks against the size of a gridded interpolant
%
% OUTPUTS:
%
%    None. The function signals an error if memory might be exceeded.

%
% Copyright 2014-2018 Biometrics Northwest LLC
%

%
% Modified: 2018-08-28
% Author  : Kevin R. Gehringer
%
%     Added tests to see if the storage requirements were less than
%     intmax('uint32') bytes. If so, assume everything is OK and just
%     return. Otherwise check the memory. The call to memory() was taking a
%     huge amount of time.
%
% Created: 2014-11-25
% Author : Kevin R. Gehringer
%

if ( ~isvector(n) )
    error('The size of the B-spline series or gridded interpolant must be a vector.');
end

switch (type)

    case 'bss'
        ndim = size(n,1);

        if ( 8*(2+2*ndim+prod(n)+3*ndim+max(n)*ndim) < intmax('uint32') )
            return
        end
        
        [~,mem] = memory;
        
        if ( 8*(2+2*ndim+prod(n)+3*ndim+max(n)*ndim) > 0.9*mem.PhysicalMemory.Available )
            error('The size of the B-spline series data structure exceeds available memory.');
        end
    case 'grid'
        if ( 2*8*prod(n) < intmax('uint32') )
            return
        end
        
        [~,mem] = memory;
        
        if ( 2*8*prod(n) > 0.9*mem.PhysicalMemory.Available )
            error('The size of the B-spline series gridded interpolant exceeds available memory.');
        end
    otherwise
        error('The type of memory check was not recognized. Allowed values area: ''bss'', and ''grid''.');
end
