Sorted problem with infinite loops (mainly)