more refactoring and improved output formatting