Refactored code into functions