Depth-sorting

Depth-sorting must be improved but it works and is better for the future then breaking the for-loops.