Small changes in error handling and added tests

Some code restructuring to make it easier to test.