moving function definition outside of loop