function L = gridlogprob(K,Y,B,C)
%    GRIDLOGPROB Return the log probability of a configuration
%
%  L = LOGPROB(K,Y,B) where E is the adjacency matrix, Y is the
%  configuration, B are the grid beliefs
%
%  L = LOGPROB(K,Y,B,C) where C==1 indicates the beliefs are in
%  logspace.


% See Equation (39) in
%
% JS Yedidia, WT Freeman, Y Weiss. Constructing Free Energy
% Approximations and Generalized Belief Propagation Algorithms. IEEE
% Transactions on Information Theory, 2005

% Jerod Weinman
% jerod@acm.org
    
% $Id%
 
% 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<4
	C = 0;
  end;

  nL = size(B.node,1);
  
  dg = 4*ones(size(K));
  dg([1 end],:) = 3;
  dg(:,[1 end],:) = 3;
  dg(1,1) = 2;
  dg(1,end) = 2;
  dg(end,1) = 2;
  dg(end,end) = 2;
  
  dg = dg(:)';
  
  nx = sub2ind( size(B.node), Y, 1:length(Y) );

  if C
	L = -sum( (dg-1) .* B.node(nx) );
  else
	L = -sum( (dg-1) .* log( B.node(nx) ) );
  end;
  
  [E0,E1,nH] = gedges(K);

  YE = sub2ind([nL nL],Y(E0),Y(E1));
  
  hx = sub2ind(size(B.hEdge),1:nH,YE(1:nH));
  vx = sub2ind(size(B.vEdge),((nH+1):length(YE))-nH,YE(nH+1:end));

  if C
    L = L + sum(B.hEdge(hx)) + sum(B.vEdge(vx));
  else
    L = L + sum(log(B.hEdge(hx))) + sum(log(B.vEdge(vx)));
  end;

