Move set/unset of i closer to its usage