finally fixed bug in sorting