function [A, names] = mk_adj_mat(connections, names, topological)
% MAKE_ADJ_MAT Make a directed adjacency matrix from a list of connections between named nodes.
% [A, names] = mk_adj_mat(connections, names, topsort)
%
% Example:
% names = {'WetGrass', 'Sprinkler', 'Cloudy', 'Rain'}; 
% connections = {'Cloudy', 'Sprinkler'; 'Cloudy', 'Rain'; 'Sprinkler', 'WetGrass'; 'Rain', 'WetGrass'}; 
% adds the arcs C -> S, C -> R, S -> W, R -> W. Node 1 is W, 2 is S, 3 is C, 4 is R.
%
% Note that in this example, the nodes are not in topological order (parents before children).
% If we set topsort=1, the numbering becomes: node 1 is C, 2 is R, 3 is S, 4 is W
% (since the return value of names is {'Cloudy', 'Rain', 'Sprinkler', 'WetGrass'}).
% To access the Rain node after sorting, use bnet.bnodes{stringmatch('Rain',names)}, etc.
% Note that topological sorting the graph is only possible if it has no directed cycles.
% (Alternatively, we could have used names = {'Cloudy', 'Sprinkler', 'Rain', 'WetGrass'} and topsort=0.)

if ~exist('topological'), topological = 0; end
  
n=length(names);
A=zeros(n);
[nr nc] = size(connections);
for r=1:nr
  from = stringmatch(connections{r,1}, names);
  assert(~isempty(from));
  to = stringmatch(connections{r,2}, names);
  assert(~isempty(to));
  %fprintf(1, 'from %s %d to %s %d\n', connections{r,1}, from, connections{r,2}, to);
  A(from,to) = 1;
end

if topological
  order = topsort(A); 
  A = A(order, order); 
  names = names(order); 
end


