Added tests and some error reporting refactoring