Better error handling and code cleanup