Improved cleanup function