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

%   Implementation of hLocalToGlobalLinearIndices for codistributor1d.
%   Convert linear indices into 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 subscripts.
    gsize = codistr.Cached.GlobalSize;
    if codistr.Dimension > numel(gsize)
        gsize(end+1:codistr.Dimension) = 1;
    end
    
    localSize = gsize;
    localSize(codistr.Dimension) = codistr.Partition(workerIdx);
    
    subs = cell(1, numel(gsize));
    [subs{:}] = ind2sub(localSize, localLinInd);
    
    % Adjust the subscript in the distribution dimension
    offset = sum(codistr.Partition(1:workerIdx-1));
    subs{codistr.Dimension} = subs{codistr.Dimension} + offset;
    
    % Convert back to linear
    globalLinInd = sub2ind(gsize, subs{:});
end

