Improved cleanup code