Writing the balancing algo