Optimized the sorting function again (7h > 5min)