Refactored code from initial try