function B = belief(F,S)
% BELIEF Calculate (approximate) marginal belief from factor and messages
%
% B = BELIEF(F,S) where S are the variable to function messages
  
% FACTOR.BELIEF
	
        
% Jerod Weinman
% jerod@acm.org
    
% $Id: belief.m 1 2009-05-07 13:41:00Z weinman $
 
% Jerod Weinman
% jerod@acm.org
% Copyright 2008, 2009, 2011
 
%    This file is part of MatLibFactorGraph.
%
%    MatLibFactorGraph 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.
%
%    MatLibFactorGraph 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 MatLibFactorGraph.  If not, see <http://www.gnu.org/licenses/>.
    
  % Arguments / Node names
  A = F.arguments;
  
  % Label dimensions for argument nodes
  L = size(F.table);
  

  if length(A)==1
	% Singleton factor
	B = F.table + S{A};
  else
	% Linear indices spanning values for each variable of the factor
	for a=1:length(A)
	  I{a} = 1:L(a);
	end;
	
	% Combinatorial subscripts for Cartesian product
	T = cellndgrid(I);
	
	% Take (log) product of combinatorial combinations
	B = F.table;
	
	for a=1:length(A)
	  B = B + S{A(a)}(T{a});
	end;
  end;
  
  % Normalize
  mx = maxv(B);
  
  B = B - (mx + log(sumv(exp(B-mx))));
  
