bugfixes, add a few unit tests