Cleaned up the objective function and gradient implementations.