Various bug fixes and unit tests