Added more detailed error handling and tests.