Removed duplicate code and refactored