Bug fixes and more unit tests