Completed cost function