Bugfixes and add tests