refactor loop body into a separate function