Added gradient calculation