started refactoring of gradient calculation for max terms