function globalLinInd = hLocalToGlobalLinearIndices(codistr, localLinInd, workerIdx)
; %#ok<NOSEM> % Undocumented

%   Implementation of hLocalToGlobalLinearIndices for codistributor2dbc.
%   Convert linear indices inton the local part into global linear indices.

%   Copyright 2019-2022 The MathWorks, Inc.

    if nargin < 3
        workerIdx = spmdIndex;
    end
    
    if ~distributedutil.CodistParser.isValidSPMDIndex(workerIdx)
        error(message('parallel:codistributors:InvalidSpmdIndex'));
    end
    
    localSize = codistr.hLocalSize();
    localNumel = prod(localSize);
    if  any(~isPositiveIntegerValuedNumeric(localLinInd) | ...
            localLinInd < 1 | localLinInd > localNumel)
        error(message('parallel:codistributors:InvalidLocalIndex'));
    end
    
    % First convert the local linear index into separate row and column
    % indices. 
    [localRowIdx, localColIdx] = ind2sub(localSize, localLinInd);
    
    % Use the existing helper to work out the global row and column
    globalRowIdx = codistr.hLocalToGlobalIndices(localRowIdx, 1, workerIdx);
    globalColIdx = codistr.hLocalToGlobalIndices(localColIdx, 2, workerIdx);
    
    % Convert back to linear
    globalLinInd = sub2ind(codistr.Cached.GlobalSize, globalRowIdx, globalColIdx);
end

