Improved error handling and some minor fixes