function E = gadjmat(K,D)
% GADJMAT Grid adjacency matrix
%
% E = GADJMAT(K) where K is the node numbers.
%
% E = GADJMAT(K,D) where D=1 indicates only horizontal edges should
% be included, D=2 indicates only vertical edges, and all other
% values include all edges.

    
% 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<2
	D = 0;
  end;
  
  
  E = logical(sparse(K(end),K(end)));
  
  if D~=2
	% Horizontal edges
	E0 = mkvector(K(:,1:end-1));
	E1 = mkvector(K(:,2:end));
	
	ndx = sub2ind(size(E),E0,E1);
	
	E(ndx) = 1;
  end;
  
  if D~=1
	% Vertical edges
	E0 = mkvector(K(1:end-1,:));
	E1 = mkvector(K(2:end,:));
	
	ndx = sub2ind(size(E),E0,E1);
  
	E(ndx) = 1;
  end;
  
