Several bugfixes and test suite improvements