Code cleanup, and refactoring