added cost and gradient functions