Add unit tests, some bugfixes