Improve test coverage, and fix issues found by new tests
refactoring for readability and safety