refactor loop into its own function