refactored maybe_cleanup per @lordnull