fixed sorting bug, tidy up a bit