Improved error handling and some code formatting.