Bug fixes and improved test coverage