Refactored code to multiple methods for easier understanding