Fixing Gradient function. Adding unit tests for problematic areas, including gradient checking for gradient of cost function.