Several fixes and unit tests