Move all cleanup actions out of inner loop.