Started optimum gain calculations code