function B = belief(F,S,Y)
% BELIEF Calculate (approximate) marginal belief from factor and messages
%
% B = BELIEF(F,S) where S are the variable to function messages
%
% B = BELIEF(F,S,Y) where S are the variable to function messages
  
% WORDFACTOR.BELIEF
    
% Jerod Weinman
% jerod@acm.org
    
% $Id: belief.m 1 2009-06-17 20:04:43Z weinman $
 
% Jerod Weinman
% jerod@acm.org
% Copyright 2006, 2008, 2009, 2011
 
%    This file is part of VIDI.
%
%    VIDI 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.
%
%    VIDI 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 VIDI.  If not, see <http://www.gnu.org/licenses/>.
    
  if nargin<3
    B = zeros( zeros(1,nargs(F)) );
    return;
  end;
  
  % Arguments / Node names
  A = chararguments(F);

  % If told it's a word, but not in the wordlist, then impossible
  if Y(end)==2 & ~any(all(Y(ones(1,numwords(F)),1:end-1)==F.words,2))
    B = -Inf;
    return;
  end;
    
  % Add word node to factor message 
  mx = max(S{F.wordnode});
  B = S{F.wordnode}(Y(end)) - mx - log(sum(exp(S{F.wordnode}-mx)));
  
  for c=1:wordlen(F)
    mx = max(S{A(c)});
    B = B + S{A(c)}(Y(c)) - mx - log(sum(exp(S{A(c)}-mx)));
  end;
  
  
  
