         }
         headPtr = floatBitsToUint(val.x);
     }
+    // Update pointer to selected fragment.
     lastPtr = minPtr;
     return closestVal;
 }

}

vec4 selectionSortNext(uint headPtr, float lastDepth, inout uint lastPtr) {
    vec4 closestVal = vec4(-1.0);
    float minDepth = 1.0;
    bool passedLastPtr = false;
    uint minPtr = 0;
    while (headPtr != 0) {
        vec4 val = readPixelStorage(headPtr - 1);
        if (headPtr == lastPtr) passedLastPtr = true;
        else if (val.y < minDepth && (val.y > lastDepth || (passedLastPtr && val.y == lastDepth) )) {
            minDepth = val.y;
            closestVal = val;

void fillFragmentArray(uint idx, out int numFrag);
// Fill local memory array with lowest values
void fillFragmentArraySortedUntilDepth(uint pixelIdx, float maxDepth, out int numFrag);
// Selection sort, allowing to get the next elements of a larger series.
// Returns the next fragment with lowest depth but behind/at the same depth as the last.
vec4 selectionSortNext(uint headPtr, float lastDepth, inout uint lastPtr);

// Bubble sort used to sort fragments
