function indx = bsssub2ind(siz,bsspartsubs)
%BSSSUB2IND Linear index from multiple subscripts as a row in a matrix.
%   BSSSUB2IND is used to determine the equivalent single linear index
%   corresponding to a given set of subscript values.
%
%   INDX = BSSSUB2IND(SIZ,ISUBS) returns the linear index equivalent to the
%   subscripts in the rows of the matrix BSSPARTSUBS for an array of size
%   SIZ. 
%

%
% This is a modified version of the MATLAB function SUB2IND that was
% developed to accept a matrix of subscripts as the input rather than
% multiple arguments.
%
% Modifications were made to use a matrix with subscripts as rows rather
% than multiple inputs and varargin as the input to compute the linear
% index.
%
% This simple change makes the interface uniform for all dimensions.
%
% Thanks go to Mathworks for the initial version.
%

%
% Copyright 2014-2018 Biometrics Northwest LLC
%

%
% Modified: 2016-03-27
% Author  : Kevin R. Gehringer
%
%    Removed a call to DOUBLE to convert the values in SIZ. It was not
%    necessary for this function.
%
%    Rearranged the code to be slightly more efficient, looping from 2 to
%    LENSIZ rather than 1 to LENSIZ to eliminate a multiplication by one.
%
%    Removed use of CUMPROD to create a an array of cumulated dimensions.
%    This is now computed as a scalar as the loop is executed.
%
% Created: 2014-11-25
% Author : Kevin R. Gehringer
%

lensiz = length(siz);
if (lensiz < 1)
    error('InvalidSize');
end

subs_dim = size(bsspartsubs,2);

if (lensiz ~= subs_dim)
    error('DimensionMismatch');
end

if (subs_dim == 1 )
    
    indx = bsspartsubs;
    
else
%
%   Compute linear indices
%
    k = 1;
    indx = bsspartsubs(:,1);
    for i = 2:lensiz;
%
%        Verify subscripts are within range
%
%        if (any(bsspartsubs(:,i) < 1)) || (any(bsspartsubs(:,i) > siz(i)))
%            error('IndexOutOfRange');
%        end
        k = k*siz(i-1);
        indx = indx + (bsspartsubs(:,i)-1)*k;
    end
    
end
