Refactored cleanup code