Bugfixes with tests