Further refactoring of cleanup tasks, to try to make more reusable