Refactoring second loop to function