Optimizing and adding some sorting