Improve code and add top-level sort