Added the sorting functionality for multiple phases. Still need to test it.