Code cleanup and refactoring for DRY