Improve error handling, add tests