%mathpiper,def="MultiGcd"

//TODO optimize this! keeps on converting to and from internal format!

10 # MultiGcd( 0,_g) <-- g;
10 # MultiGcd(_f, 0) <-- f;

20 # MultiGcd(_f,_g) <--
[
  Local(v);
  v:=MultiExpressionList(f+g);  //hier
  NormalForm(MultiGcd(MakeMultiNomial(f,v),MakeMultiNomial(g,v)));
];


5 # MultiGcd(f_IsMulti,g_IsMulti)_(MultiTermLess({MultiLM(f),1},{MultiLM(g),1})) <--
[
//Echo("lesser");
  MultiGcd(g,f);
];

5  # MultiGcd(MultiNomial(_vars,_terms),g_IsMulti)_(MultiLM(MultiNomial(vars,terms)) = MultiLM(g))
     <-- CreateTerm(vars,{FillList(0,Length(vars)),1});

5  # MultiGcd(MultiNomial(_vars,_terms),g_IsMulti)_( Select(MultiLM(MultiNomial(vars,terms))-MultiLM(g), {{n},n<0} ) != {})
     <-- CreateTerm(vars,{FillList(0,Length(vars)),1});

5  # MultiGcd(MultiNomial(_vars,_terms),g_IsMulti)_(NormalForm(g) = 0)
     <-- CreateTerm(vars,{FillList(0,Length(vars)),1});
10 # MultiGcd(f_IsMulti,g_IsMulti) <--
[
  LocalSymbols(a)
  [
    Bind(f,Subst(a,a)f);
    Bind(g,Subst(a,a)g);
  ];
  Local(new);
  While(g != 0)
  [
//Echo("before f",f,NormalForm(f));
//Echo("before g",g,NormalForm(g));
    Bind(new, MultiDivide(f,{g}));
//Echo("new g",NormalForm(new[1][1]),NormalForm(new[2]));
If(new[1][1]=0,
[
  g:=MakeMultiNomial(1,MultiVars(f));
//Echo("PRIM ",MultiPrimitivePart(g));
  new[2]:=0;
]);
    Bind(new, new[2]);
    Bind(f,g);
    Bind(g,new);

//Echo("after f",f,NormalForm(f));
//Echo("after g",g,NormalForm(g));
  ];
  MultiPrimitivePart(f);
];

%/mathpiper