Added failure handling and fixed unit tests.