refactor duplicate cleanup code