Fix sorting not working correctly and speed up a little bit.