Refactoring to allow testing, generate sorted output