Refactored balancing and added tests