Move loop variable definition into loop headers

This removes false impression that the loop variable is used after the loop