#
# Take the data passed from a call to plot_poset and use it to printf a
#  plot in the DOT language. Reference: <www.graphviz.org>.
# The top level proc is just a wrapper that sets up quiet output and
#  traps errors that interfere with restoring output to the terminal.
#
`posets/dotplot`:=proc(file) local f,q;
  q:=interface('quiet'); interface('quiet'=true);
  if nops(file)=1 then printf(`\n`) else writeto(file[2]) fi;
  f:=traperror(`posets/dotplot/main`(args[2..nargs]));
  if nops(file)=1 then printf(`\n`) else writeto('terminal') fi;
  interface('quiet'=q);
  if f=lasterror then ERROR(lasterror) fi
end:
#
# The real work is here. Each line of output for the first color class
#  begins with a declaration of a vertex x, followed by the list of edges
#  with tail x. All other color classes are output as edge-lists only.
# Exceptional case: there might be no edges and no color classes.
# If a level-partition F is supplied, DOT can use it, but the language
#  doesn't seem to support user-specified ordering within levels.
# Note that the default vcolor in Maple V R3 or earlier is white,
#  which is almost certainly not what you want when using DOT.
#  
`posets/dotplot/main`:=proc(C,X,F,vclr,labs) local down,x,c,Y,first;
  printf(`digraph some_poset {\n`);
  if type(labs,'table') then
    printf(`node [color=%s,fontcolor=%s];\n`,vclr,vclr)
  else
    printf(`node [color=%s,shape=point];\n`,vclr) fi;
  for c in C do
    if first=NULL then printf(`edge [color=%s];\n`,c[1])
      else printf(`edge [arrowhead=none,color=%s];\n`,c[1]) fi;
    down:=`posets/coversets`(c[2],X);
    for x in X do `posets/dotplot/line`(x,down[x],labs,first) od;
    first:=NULL
  od;
  if nops(C)=0 then for x in X do
    `posets/dotplot/line`(x,down[x],labs,first) od fi;
  if type(F,'list') then for Y in F do
    printf(`  { rank=same; `);
    for x in Y do printf(`%a; `,x) od;
    printf(`}\n`)
  od fi;
  printf(`}\n`)
end:
#
# Process edges with tail x in the current color. The first time through,
# declare x as a node in case it has a special label or is isolated.
#
`posets/dotplot/line`:=proc(x,Y,L) local y,s;
  if nargs>3 then s:=``;
    if type(L,'table') then s:=cat(` [label="`,L[x],`"]`) fi;
    printf(`%a%s;`,x,s)
  fi;
  if nops(Y)>0 then
    for y in Y do printf(` %a -> %a;`,x,y) od fi;
  if nargs>3 or nops(Y)>0 then printf(`\n`) fi
end:
#
save `posets/dotplot`, `posets/dotplot/main`, `posets/dotplot/line`,
  cat(HomeLib,`/posets/dotplot.m`);
quit;

