Fixed infinite loop bug
Fixed sorting in the wrong order