Code cleanup and refactoring to make it cleaner and less repetetive.