move sort to a separate function.