Implement balance function and tests