clean up sort function
refactor stuff into generators