Moved reused variables outside of the loops.