private static LinkedList<AngleInterval> flattenIntervals(Heap<AngleInterval> startAngles, StatWriter writer)
    {
        int opt = startAngles.size();   //Original amount of sectors is stored for stats collecting.
        Queue<AngleInterval> flat = new Queue<>();  //This will be returned.
        Heap<AngleInterval> endAngles = new Heap<>(15, new EndDirectionComparator());   //This holds sectors in between which lastAngle lies.
        Tree<AngleInterval> distances = new Tree<>(new DistanceComparator());   //Same as endAngles but with different comparatot, telling which sector is closer to src.
        double lastAngle = -Math.PI;    //Angle marker which makes a full rotation from -PI to +PI.
        
        while (!sectorsAreExhausted(startAngles, endAngles))
        {
            AngleInterval newAngle = startAngles.peek();
            while (sectorsRightAngleBeforeLastAngle(endAngles, lastAngle))
                distances.remove(endAngles.pop());
            if (sectorsAreExhausted(startAngles, endAngles))    break;
            AngleInterval oldAngle = endAngles.peek();
            
            if (newAngleBeforeOldAngle(newAngle, oldAngle))
            {
                if (endAngles.isEmpty())
                    lastAngle = newAngle.leftAngle;
                else if (nextSectorIsClosest(newAngle, distances, lastAngle))
                {
                    flat.enqueue(createSectorBeforeNewAngle(lastAngle, distances.getMin(), newAngle));
                    lastAngle = newAngle.leftAngle;
                }
                distances.add(newAngle);
                endAngles.insert(newAngle);
                startAngles.pop();
            }
            else
            {
                boolean wasClosest = (oldAngle == distances.getMin());
                distances.remove(oldAngle);
                if (wasClosest && lastAngle != oldAngle.rightAngle)
                {
                    flat.enqueue(closeOldSector(lastAngle, oldAngle));
                    lastAngle = oldAngle.rightAngle;
                }
                overWriteFirstSectorsAfterLoop(oldAngle, flat);
                endAngles.pop();
            }
        }
        
        writeStats(writer, opt, flat.size());
        return flat.toLinkedList();
    }