lots of fixes and unit tests