Refactored code to use functions