Improve error reporting, refactor