function m = marginal_family(bnet, i, t)
% MARGINAL_FAMILY Return the posterior marginal on a family (a node and its parents).
%
% M = MARGINAL_FAMILY(BNET, i, t) returns a structure: see MARGINAL_NODES for details.

if nargin < 3, t = 1; end

ss = bnet.slice_size;

switch bnet.algo
  case 'pearl',
    assert(t==1);
    m=pearl_family_marginal(bnet, i, t);
  otherwise,
    switch bnet.algo
      case {'lw', 'ls', 'sof', 'hmm', 'lds'}
	c = -1;
      case {'jtree', 'bk'}
	c = find_clique_containing_family(bnet, i, t);
    end
    if t==1
      fam = family(bnet.adj_mat, i);
      m = marginal_nodes(bnet, fam, t, c);
    else
      fam = family(bnet.adj_mat, i+ss);
      if any(fam<=ss)
	% i has a parent in the preceeding slice
	% Hence the lowest numbered slice containing the family is t-1
	m = marginal_nodes(bnet, fam, t-1, c);
      else
	% The family all fits inside slice t
	% Hence shift the indexes back to slice 1
	m = marginal_nodes(bnet, fam-ss, t, c);
      end
    end
end


%%%%%%%%

function m = pearl_family_marginal(bnet, i, t)
% PEARL_FAMILY_MARGINAL Compute the marginal on i's family from Pearl's messages.
% m = pearl_family_marginal(bnet, i, t)
% patch added by Y Weiss

assert(t==1);
ns=bnet.node_sizes;
ps = parents(bnet.adj_mat, i);
fam = [ps i];
T = mk_table(fam, ns(fam)); % initializes to 1s
for j=1:length(ps)
  p=ps(j);
  pi_from_parent = mk_table(p, ns(p));
  pi_from_parent.T = bnet.pearl.msg{i}.pi_from_parent{j};
  T = multiply_by_table(T, pi_from_parent);
end
CPT = mk_table_from_bnode(bnet.bnodes{i});
T =  multiply_by_table(T, CPT);
% now we need to multiply by lambda. We do that by constructing a
% table from lambda. it is the same size as the marginal table
Tlambda = bnet.pearl.marginal{i};
Tlambda.T = bnet.pearl.msg{i}.lambda;
T = multiply_by_table(T,Tlambda);
T.T = normalise(T.T);
m=T;
