Refactoring the cleanup function