Refactored code, removed code duplication