Move loop code to separate function.