Improved error handling and added a debug mode