#
# Given a level-partition F of P and initial horizontal coordinates within
#  each level (supplied as args[4]), fix the coordinates for a plot.
# The output is a list of triples [x,h,v], where x is a vertex of P and
#  [h,v] are the horizontal and (unstretched) vertical coordinates of x.
# If flag=true, then proportional spacing of vertices is used.
#
# Synopsis: First, locate dangerous edges that jump more than one level.
# Next, loop over the vertices by level, and within each level,
#  start in the center and work outwards from there, left and right.
# For each vertex x in the loop, examine all dangerous edges with tail x.
# If the edge passes through a vertex in an intermediate level (BAD!),
#  shift the position of x and all vertices to the left or right of x,
#  depending on the relative position of x within its level.
# Repeat until no dangerous edges with tail x do bad things.
#
`posets/layout`:=proc(P,F,flag) local f,jmp,hc,i,j,dh,n,d;
  f:=nops(F); hc:=array(1..f+1,args[4]); dh:=1;
  jmp:=`posets/layout/jump`(P,F,f);
  for i to f do
    n:=nops(F[i]); d:=-1; j:=iquo(n,2)+1;
    if flag then dh:=1/n fi;
    while j>0 and j<=n do
      while `posets/layout/bad`([i,j],jmp[i,j],hc) do
        hc[i]:=`posets/layout/shift`(hc[i],n,dh,j,d)
      od;
      j:=j+d; d:=-d-signum(d)
    od
  od;
  [seq(seq([F[i][j],hc[i][j],i],j=1..nops(F[i])),i=1..f)];
end:
#
# Assemble the dangerous edges that jump more than one level.
# Also, barf if any edge goes somewhere it shouldn't.
# Note that it is more convenient to label vertices by their vertical
# and horizontal rank (vhr), as determined by the level partition F.
#
`posets/layout/jump`:=proc(P,F,f) local vhr,jmp,i,j,e,x,y,dr;
  vhr:=table([seq(seq(F[i][j]=(i,j),j=1..nops(F[i])),i=1..f)]);
  jmp:=table([seq(seq((i,j)=[],j=1..nops(F[i])),i=1..f)]);
  for e in P do
    y:=vhr[e[2]]; x:=vhr[e[1]]; dr:=y[1]-x[1];
    if dr<1 then ERROR(`invalid level partition`)
      elif dr>1 then jmp[y]:=[op(jmp[y]),[x]] fi
  od; op(jmp)
end:
#
# Determine if there is a dangerous edge with tail x that does bad
# things (i.e., passes through a vertex in an intermediate level).
#
`posets/layout/bad`:=proc(x,dang,hc) local y,dv,dh,hy,r;
  for y in dang do
    dv:=x[1]-y[1]; hy:=hc[y[1]][y[2]];
    dh:=(hc[x[1]][x[2]]-hy)/dv;
    for r from y[1]+1 to x[1]-1 do
      hy:=hy+dh; if member(hy,hc[r]) then RETURN(true) fi
    od
  od; false
end:
#
# Shift some horizontal coordinates by dh to avoid a bad situation.
#
`posets/layout/shift`:=proc(hc,n,dh,j,d) local i;
  if d<0 then [op(1..j-1,hc),seq(hc[i]+dh,i=j..n)]
    else [seq(hc[i]-dh,i=1..j),op(j+1..n,hc)] fi
end:
#
save `posets/layout`, `posets/layout/jump`, `posets/layout/bad`,
  `posets/layout/shift`, cat(HomeLib,`/posets/layout.m`);
quit;

