function CPT_to_C(bnet, fid)
% CPT_TO_C Create C arrays containing all the CPTs
% CPT_to_C(bnet, fid)
%
% Example - for the file examples/discrete1.m this function creates
% double CPT0[2] = {0.500, 0.500};
% double CPT1[2][2] = {0.500, 0.500, 0.900, 0.100};
% double CPT2[2][2] = {0.800, 0.200, 0.200, 0.800};
% double CPT3[2][2][2] = {1.000, 0.000, 0.100, 0.900, 0.100, 0.900, 0.010, 0.990};


n = length(bnet.adj_mat);
ns = bnet.node_sizes;
for i=1:n
  e = bnet.equiv_class(i);
  assert(strcmp(bnet.bnodes{e}.type, 'tabular'));
  ps = bnet.bnodes{e}.parents;
  CPT = bnet.bnodes{e}.CPT;
  if length(ps)>=1
    CPT = permute(CPT, length(ps)+1:-1:1); % so last dim becomes first (C order)
  end
  CPT = CPT(:);
  j = i-1; % C numbers nodes from 0
  switch length(ps)
    case 0, fprintf(fid, 'double CPT%d[%d] = {', j, ns(i));
    case 1, fprintf(fid, 'double CPT%d[%d][%d] = {', j, ns(ps(1)), ns(i));
    case 2, fprintf(fid, 'double CPT%d[%d][%d][%d] = {', j, ns(ps(1)), ns(ps(2)), ns(i));
    otherwise, error('too many parents');
  end
  for j=1:length(CPT)-1
    fprintf(fid, '%5.3f, ', CPT(j));
  end
  j = length(CPT);
  fprintf(fid, '%5.3f};\n', CPT(j));
end
