function [B,G,flag] = marginals(C,X,A,L)
% MARGINALS Approximate node and edge marginal beliefs
%
% [B,G,flag] = MARGINALS(C,X) where C is the gcrf and X is a grid
% graph struct. B are the node marginals matrix and G are the edge
% marginals cell.

% GCRF.MARGINALS


% Jerod Weinman
% jerod@acm.org
    
% $Id: marginals.m 1 2009-05-07 13:41:00Z weinman $
 
% Jerod Weinman
% jerod@acm.org
% Copyright 2004, 2008, 2009
 
%    This file is part of Matlab GridCRF.
%
%    Matlab GridCRF is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    Matlab GridCRF is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with Matlab GridCRF.  If not, see <http://www.gnu.org/licenses/>.
    
	
  if nargin<3
	A = 0;
  end;
  
  if nargin<4
	L = 0;
  end;
  
  if 0
  M = unrollgm(C,X.node,X.hEdge,X.vEdge);
  
  if A==0
	%D = gridsize(X.node,X.hEdge);
	%F = gridSpanTrees(D(1),D(2));
	
	%[B,G,flag] = trp({M.adjmat, F{:}}, M.nodeEnergies, M.edgeEnergies,0,[],L);
  
	[B,G,flag] = asyncbp(M.adjmat, M.nodeEnergies, M.edgeEnergies,0,[],L);
  else
	B = meanfield(M.adjmat, M.nodeEnergies, M.edgeEnergies);
  end;
  else
 
  M = unrollgridflat(get(C,'weights'),X.node,X.hEdge,X.vEdge,get(C,'defEdge'));
  K = nodenum(gridsize(X.node,X.hEdge));
  [B,flag] = gridsyncbp(K,M,0);

  G = B;
  B = B.node;
  
  end;
