Fix for IllegalStateException

Also fixes some older unit tests and adds new unit tests.