Refactored code to simplify it