Cleanup and improved error handling