Moved loop to outer function