Better error reporting and refactoring