function G = addevidenceflat(M,V,Y)
% ADDEVIDENCE Add evidence (observations) to a graphical model
%
% G = ADDEVIDENCEFLAT(M,V,Y) where M is the original model, V are
% the nodes whose observed values Y are being added as evidence

% Jerod Weinman
% jerod@acm.org
    
% $Id: addevidenceflat.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 length(V)~=length(Y)
	error('Node and label lists must be the same length');
  end;

  if any(V)<1 || any(V)>M.numNodes
	error('Node index out of range');
  end;
  
  if any(Y)<1 || any(Y)>M.numLabels
	error('Label index out of range');
  end;

  
  L = M.numLabels;

  E0 = M.adjmat(:,1);
  E1 = M.adjmat(:,2);

  Ex = ones(length(E0),1);
  
  H = M.node; % NxL
  S = M.edge; % |E|xL²

  for v=1:length(V)
	
	vv = V(v);
	
    En = [E0==vv E1==vv];
    
	for e=find(any(En,2))'
	 	  
      psi = reshape(M.edge(e,:),[L L]); % (E0,E1)
      
      if E0(e)==vv
        % E0 is observed
        if any(E1(e)==V)
          continue; % No need to modify other observations
        end;

        uu = E1(e);

      else
        % E1 is observed
        if any(E0(e)==V) % No need to modify other observations
          continue;
        end;
        
        uu = E0(e);
        psi = psi';
      end;
      
	  H(uu,:) = H(uu,:) + psi(Y(v),:);
      Ex(e) = 0;
	end;
	
	  p0 = -Inf*ones(1,L);
	  p0(Y(v)) = 0;
	  
	  H(vv,:) = p0;
  end;
  


  G = struct('numNodes', {M.numNodes}, ...
			 'adjmat', {M.adjmat(find(Ex),:)}, ...
			 'numLabels', {L}, ...
			 'node', {H}, ...
			 'edge', {M.edge(find(Ex),:)} );
  
