Sped up sorting; still need to simplifiy logic