Refactored code and created helper functions