#
# perm_rep(J,R) produces the permutation representation of W(R) acting
# on cosets of the parabolic subgroup indexed by J (a list or set of
# indices in the range 1..n). If J is omitted, then the default is to
# take J to be [1,2,...n-1] (faithful iff R is irreducible).
# The format follows group[permgroup], or can be exported to gap format.
#
`coxeter/perm_rep`:=proc() local S,i,j,v,orb,pg,pi,m,find,EPS,alive,c,eq;
  m:=nargs; if args[m]='gap' then m:=m-1 fi;
  S:=coxeter['base'](args[m]);
  if m>1 then m:=args[1] else m:=[$1..(nops(S)-1)] fi;
  m:=subsop(seq(i=0,i=m),[1$nops(S)]);
  v:=convert([seq(c[i]*S[i],i=1..nops(S))],`+`);
  v:=collect(v,indets(S));
  eq:={seq(coxeter['iprod'](S[i],v)=m[i],i=1..nops(S))};
  v:=subs(`coxeter/linsolve`(eq,indets(eq)),v);
  orb:=coxeter['orbit'](v,S); pg:=NULL;
  if nops(orb)>256 and [op(I)]=[1] and args[nargs]='gap' then
    ERROR(`degree of permutation group too large to export`) fi;
  if type(S,'list'('polynom'('rational'))) then
    find:=proc(u,L) local j; member(u,L,'j'); j end;
  else
    EPS:=`coxeter/default`['epsilon'];
    find:=proc(u,L,ep) local j;
      for j to nops(L) do
        if convert(map(abs,[coeffs(u-L[j])]),`+`)<ep then RETURN(j) fi
      od; ERROR(`floating-point inaccuracies`)
    end;
  fi;
  for i to nops(S) do
    alive:=orb; m:=[$1..nops(orb)]; pi:=NULL;
    while nops(m)>1 do
      v:=coxeter['reflect'](S[i],alive[1]);
      j:=find(v,alive,EPS);
      if j>1 then pi:=pi,[m[1],m[j]] fi;
      alive:=subsop(1=NULL,j=NULL,alive);
      m:=subsop(1=NULL,j=NULL,m);
    od;
    pg:=pg,cat('s',i)=[pi]
  od;
  if args[nargs]<>'gap' then permgroup(nops(orb),{pg}) else
    `coxeter/perm_rep/gap`(nops(S),{pg},args[nargs-1])
  fi
end:
#
`coxeter/perm_rep/gap`:=proc(n,pg) local pi,i,c,lpr,R;
  if [op(I)]=[1] then lpr:=proc() printf(`%0.1200s\n`,args) end
    else lpr:=proc() lprint(args) end fi;
  lpr(` `);
  for i to n do
    pi:=subs(pg,cat('s',i));
    if nops(pi)=0 then c:=[`()`] else
      c:=map(y->convert(y,'string'),pi);
      c:=map(y->cat(`(`,substring(y,2..length(y)-1),`)`),c);
    fi;
    lpr(cat('s',i,`:=`,op(c),`;`));
  od;
  if n=0 then lpr(`G:=Group(());`)
    else lpr(cat(`G:=Group(s1`,seq(op([`,s`,i]),i=2..n),`);`))
  fi;
  R:=coxeter['name_of'](args[3]);
  lpr(cat(`G.name:="`,convert(R,'string'),`";`)); lpr(` `);
end:
#
save `coxeter/perm_rep`, `coxeter/perm_rep/gap`,
  cat(HomeLib,`/coxeter/perm_rep.m`);
read cat(HomeLib,`/help/coxeter/perm_rep`);
quit;

