Factor out a common loop.