Refactor code and debug output