Improve error handling and clean up code