Refactor general error handling. Also fixes #6