Added various fix and optimizations to gradients