Bugfixes in rebalancing and error handling with tests