factored out common finalization code