Various bugfixes; port unit tests over