Fixed nasty bug found only thanks to unittests.
Added more tests - tests of the error handling.