More tests, error handling, and refactoring