Test improvements and fixes to the code based on issues discovered in tests.