sorting stages moved from main to functions