function [g, h, K] = marginalize_canonical(g0, h0, K0, keep, sum_over, dom1, ns)
% MARGINALIZE_CANONICAL Marginalize a canonical potential
% [g, h, K] = marginalize_canonical(g0, h0, K0, keep, sum_over, dom1, node_sizes)

n = sum(ns(sum_over));
if n==0 % isempty(sum_over)
  g = g0; h = h0; K = K0;
else
  [h1, h2, K11, K12, K21, K22] = partition_matrix_vec(h0, K0, sum_over, keep, dom1, ns(dom1));
  n = length(h1);
  K11inv = inv(K11);
  g = g0 + 0.5*(n*log(2*pi) - log(det(K11)) + h1'*K11inv*h1);
  if length(h2) > 0 % ~isempty(keep) % we are are actually keeping something
    A = K21*K11inv;
    h = h2 - A*h1;
    K = K22 - A*K12;
  else
    h = [];
    K = [];
  end
end

