Bugfixes and unit tests improvements