I'd take all the code inside this `if` statement and turn in into a function that takes `$first-val` and whatever other arguments it needs, and returns just `$gradients`.

That would make things a bit easier to read.