Refactored code to remove loops