function repeatedIndicesVec = repeatindicesbycounts( countsVec )
    % This function will return a vector of indices (positive integers for
    % indexing a vector) repeated by the number of times indicated by the
    % count in the correspondingly indexed position of a supplied vector.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % countsVec - vector of counts. Can be a vector in any dimension (i.e.
    % the singleton dimension can be anything).
    %
    % repeatedIndicesVec - a vector in the same dimension as countsVec.
    % Contains the indices of the non-zeros in countsVec, repeated by the
    % corresponding number. These indices will appear in ascending order.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % CHANGELOG
    % 13.10.2014 - copied from old version. No changes necessary.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
%     if any((rem(countsVec, 1) ~= 0) | (countsVec < 0)),
%         error('countsVec must be a vector of nonnegative integers!')
%     end
    
    dims = size(countsVec);
    [~, indexingDim] = max(dims);

    totalCount = sum(countsVec);
    
    if totalCount == 0,
        repeatedIndicesVec = [];
        return;
    end

    newDims = ones([1, length(dims)]);    
    newDims(indexingDim) = totalCount;
    
    indsToRepeatLog = countsVec > 0;
    % These are the indices that have non-zero count, and should therefore
    % appear in the result at least once.
    indsToRepeat = find(indsToRepeatLog);

    cumCounts = cumsum(countsVec(indsToRepeatLog));
    cumCounts(2:end) = cumCounts(1:(end - 1)) + 1;
    cumCounts(1) = 1;

    indicesForPlacement = zeros(newDims);
    % By putting a 1 at appropriate intervals then cumsumming, we obtain
    % repeated indices that index indsToRepeat;
    indicesForPlacement(cumCounts) = 1;
    indicesForPlacement = cumsum(indicesForPlacement);

    repeatedIndicesVec = indsToRepeat(indicesForPlacement);
end