function CPT = mk_CPT_from_mux(gate, input, arity, b)
% MK_CPT_FROM_MUX Make a CPT representation of a multiplexer
% CPT = mk_CPT_from_mux(gate, input, arity)

n = length(input);
an = arity^n;
if b
  CPT = zeros(an, n, arity);
  U = ind2subv(arity*ones(1,n), 1:an);
  for g=1:n
    tmp = sparse(1:an, U(:,g), ones(an,1), an, n);
    CPT(:,g,:) = full(tmp);
  end
  CPT = reshape(CPT, [arity*ones(1, n) n arity]);
  
  % We may need to re-order the dimensions to be consistent with the node numbering.
  % e.g., gate = 1, input = 2:3
  % Then we need to put the gate's dimension (assumed to be n+1=3 above) first.
  if gate < input
    perm = [n+1 1:n n+2];
    CPT = permute(CPT, perm);
  end
  
else
  
  ns = zeros(1, n+2);
  ns(gate) = n;
  ns(end) = arity;
  ns(input) = arity;
  CPT = myzeros(ns);
  for g=1:n
    for ui=1:arity^n
      u = ind2subv(ns(input), ui);
      v = zeros(1,n+1);
      v(gate)=g;
      v(input)=u;
      j = subv2ind(ns, [v u(g)]);
    CPT(j)=1.0;
    end 
  end
  
end
