Refactored the looping version