Improved debug output and error reporting
Cherry-picked bugfix from master branch