Refactored the code into relevant functions.