% Copyright (C) Daphne Koller, Stanford University, 2012

function [MEU OptimalDecisionRule] = OptimizeWithJointUtility( I )
  % Inputs: An influence diagram I with a single decision node and one or more utility nodes.
  %         I.RandomFactors = list of factors for each random variable.  These are CPDs, with
  %              the child variable = D.var(1)
  %         I.DecisionFactors = factor for the decision node.
  %         I.UtilityFactors = list of factors representing conditional utilities.
  % Return value: the maximum expected utility of I and an optimal decision rule
  % (represented again as a factor) that yields that expected utility.
  % You may assume that there is a unique optimal decision.

  % This is similar to OptimizeMEU except that we must find a way to
  % combine the multiple utility factors.  Note: This can be done with very
  % little code.

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %
  % YOUR CODE HERE
  %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  U = I.UtilityFactors;
  JointU = U(1);
  for k = 2:numel(U)
    JointU = FactorSum(JointU, U(k));
  endfor

  I1.RandomFactors = I.RandomFactors;
  I1.DecisionFactors = I.DecisionFactors;
  I1.UtilityFactors = JointU;
  [MEU OptimalDecisionRule] = OptimizeMEU(I1);

end
