Added modular square free factorization.
[ginac.git] / ginac / factor.cpp
index 12405dd696e870fa4f0e001e860ac764f1866095..204010be3750294640434dc28da698f9f452db69 100644 (file)
@@ -1,7 +1,12 @@
 /** @file factor.cpp
  *
- *  Polynomial factorization routines.
- *  Only univariate at the moment and completely non-optimized!
+ *  Polynomial factorization code (implementation).
+ *
+ *  Algorithms used can be found in
+ *    [W1]  An Improved Multivariate Polynomial Factoring Algorithm,
+ *          P.S.Wang, Mathematics of Computation, Vol. 32, No. 144 (1978) 1215--1231.
+ *    [GCL] Algorithms for Computer Algebra,
+ *          K.O.Geddes, S.R.Czapor, G.Labahn, Springer Verlag, 1992.
  */
 
 /*
 
 //#define DEBUGFACTOR
 
-#ifdef DEBUGFACTOR
-#include <ostream>
-#include <ginac/ginac.h>
-using namespace GiNaC;
-#else
 #include "factor.h"
 
 #include "ex.h"
@@ -41,21 +41,21 @@ using namespace GiNaC;
 #include "mul.h"
 #include "normal.h"
 #include "add.h"
-#endif
 
 #include <algorithm>
+#include <cmath>
+#include <limits>
 #include <list>
 #include <vector>
+#ifdef DEBUGFACTOR
+#include <ostream>
+#endif
 using namespace std;
 
 #include <cln/cln.h>
 using namespace cln;
 
-#ifdef DEBUGFACTOR
-namespace Factor {
-#else
 namespace GiNaC {
-#endif
 
 #ifdef DEBUGFACTOR
 #define DCOUT(str) cout << #str << endl
@@ -67,657 +67,563 @@ namespace GiNaC {
 #define DCOUT2(str,var)
 #endif
 
+// anonymous namespace to hide all utility functions
 namespace {
 
-typedef vector<cl_MI> Vec;
-typedef vector<Vec> VecVec;
-
+typedef vector<cl_MI> mvec;
 #ifdef DEBUGFACTOR
-ostream& operator<<(ostream& o, const Vec& v)
+ostream& operator<<(ostream& o, const vector<int>& v)
 {
-       Vec::const_iterator i = v.begin(), end = v.end();
+       vector<int>::const_iterator i = v.begin(), end = v.end();
        while ( i != end ) {
                o << *i++ << " ";
        }
        return o;
 }
-#endif // def DEBUGFACTOR
-
-#ifdef DEBUGFACTOR
-ostream& operator<<(ostream& o, const VecVec& v)
+ostream& operator<<(ostream& o, const vector<cl_I>& v)
 {
-       VecVec::const_iterator i = v.begin(), end = v.end();
+       vector<cl_I>::const_iterator i = v.begin(), end = v.end();
        while ( i != end ) {
-               o << *i++ << endl;
+               o << *i << "[" << i-v.begin() << "]" << " ";
+               ++i;
        }
        return o;
 }
-#endif // def DEBUGFACTOR
-
-struct Term
-{
-       cl_MI c;          // coefficient
-       unsigned int exp; // exponent >=0
-};
-
-#ifdef DEBUGFACTOR
-ostream& operator<<(ostream& o, const Term& t)
+ostream& operator<<(ostream& o, const vector<cl_MI>& v)
 {
-       if ( t.exp ) {
-               o << "(" << t.c << ")x^" << t.exp;
+       vector<cl_MI>::const_iterator i = v.begin(), end = v.end();
+       while ( i != end ) {
+               o << *i << "[" << i-v.begin() << "]" << " ";
+               ++i;
        }
-       else {
-               o << "(" << t.c << ")";
+       return o;
+}
+ostream& operator<<(ostream& o, const vector< vector<cl_MI> >& v)
+{
+       vector< vector<cl_MI> >::const_iterator i = v.begin(), end = v.end();
+       while ( i != end ) {
+               o << i-v.begin() << ": " << *i << endl;
+               ++i;
        }
        return o;
 }
-#endif // def DEBUGFACTOR
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+// modular univariate polynomial code
 
-struct UniPoly
+typedef std::vector<cln::cl_MI> umodpoly;
+typedef std::vector<cln::cl_I> upoly;
+typedef vector<umodpoly> upvec;
+
+// COPY FROM UPOLY.HPP
+
+// CHANGED size_t -> int !!!
+template<typename T> static int degree(const T& p)
 {
-       cl_modint_ring R;
-       list<Term> terms;  // highest exponent first
-
-       UniPoly(const cl_modint_ring& ring) : R(ring) { }
-       UniPoly(const cl_modint_ring& ring, const ex& poly, const ex& x) : R(ring)
-       { 
-               // assert: poly is in Z[x]
-               Term t;
-               for ( int i=poly.degree(x); i>=poly.ldegree(x); --i ) {
-                       int coeff = ex_to<numeric>(poly.coeff(x,i)).to_int();
-                       if ( coeff ) {
-                               t.c = R->canonhom(coeff);
-                               if ( !zerop(t.c) ) {
-                                       t.exp = i;
-                                       terms.push_back(t);
-                               }
-                       }
-               }
-       }
-       UniPoly(const cl_modint_ring& ring, const UniPoly& poly) : R(ring)
-       { 
-               if ( R->modulus == poly.R->modulus ) {
-                       terms = poly.terms;
-               }
-               else {
-                       list<Term>::const_iterator i=poly.terms.begin(), end=poly.terms.end();
-                       for ( ; i!=end; ++i ) {
-                               terms.push_back(*i);
-                               terms.back().c = R->canonhom(poly.R->retract(i->c));
-                               if ( zerop(terms.back().c) ) {
-                                       terms.pop_back();
-                               }
-                       }
-               }
-       }
-       UniPoly(const cl_modint_ring& ring, const Vec& v) : R(ring)
-       {
-               Term t;
-               for ( unsigned int i=0; i<v.size(); ++i ) {
-                       if ( !zerop(v[i]) ) {
-                               t.c = v[i];
-                               t.exp = i;
-                               terms.push_front(t);
-                       }
-               }
-       }
-       unsigned int degree() const
-       {
-               if ( terms.size() ) {
-                       return terms.front().exp;
-               }
-               else {
-                       return 0;
-               }
-       }
-       bool zero() const { return (terms.size() == 0); }
-       const cl_MI operator[](unsigned int deg) const
-       {
-               list<Term>::const_iterator i = terms.begin(), end = terms.end();
-               for ( ; i != end; ++i ) {
-                       if ( i->exp == deg ) {
-                               return i->c;
-                       }
-                       if ( i->exp < deg ) {
-                               break;
-                       }
-               }
-               return R->zero();
+       return p.size() - 1;
+}
+
+template<typename T> static typename T::value_type lcoeff(const T& p)
+{
+       return p[p.size() - 1];
+}
+
+static bool normalize_in_field(umodpoly& a)
+{
+       if (a.size() == 0)
+               return true;
+       if ( lcoeff(a) == a[0].ring()->one() ) {
+               return true;
        }
-       void set(unsigned int deg, const cl_MI& c)
-       {
-               list<Term>::iterator i = terms.begin(), end = terms.end();
-               while ( i != end ) {
-                       if ( i->exp == deg ) {
-                               if ( !zerop(c) ) {
-                                       i->c = c;
-                               }
-                               else {
-                                       terms.erase(i);
-                               }
-                               return;
-                       }
-                       if ( i->exp < deg ) {
-                               break;
-                       }
+
+       const cln::cl_MI lc_1 = recip(lcoeff(a));
+       for (std::size_t k = a.size(); k-- != 0; )
+               a[k] = a[k]*lc_1;
+       return false;
+}
+
+template<typename T> static void
+canonicalize(T& p, const typename T::size_type hint = std::numeric_limits<typename T::size_type>::max())
+{
+       if (p.empty())
+               return;
+
+       std::size_t i = p.size() - 1;
+       // Be fast if the polynomial is already canonicalized
+       if (!zerop(p[i]))
+               return;
+
+       if (hint < p.size())
+               i = hint;
+
+       bool is_zero = false;
+       do {
+               if (!zerop(p[i])) {
                        ++i;
+                       break;
                }
-               if ( !zerop(c) ) {
-                       Term t;
-                       t.c = c;
-                       t.exp = deg;
-                       terms.insert(i, t);
-               }
-       }
-       ex to_ex(const ex& x, bool symmetric = true) const
-       {
-               ex r;
-               list<Term>::const_iterator i = terms.begin(), end = terms.end();
-               if ( symmetric ) {
-                       numeric mod(R->modulus);
-                       numeric halfmod = (mod-1)/2;
-                       for ( ; i != end; ++i ) {
-                               numeric n(R->retract(i->c));
-                               if ( n > halfmod ) {
-                                       r += pow(x, i->exp) * (n-mod);
-                               }
-                               else {
-                                       r += pow(x, i->exp) * n;
-                               }
-                       }
-               }
-               else {
-                       for ( ; i != end; ++i ) {
-                               r += pow(x, i->exp) * numeric(R->retract(i->c));
-                       }
-               }
-               return r;
-       }
-       void unit_normal()
-       {
-               if ( terms.size() ) {
-                       if ( terms.front().c != R->one() ) {
-                               list<Term>::iterator i = terms.begin(), end = terms.end();
-                               cl_MI cont = i->c;
-                               i->c = R->one();
-                               while ( ++i != end ) {
-                                       i->c = div(i->c, cont);
-                                       if ( zerop(i->c) ) {
-                                               terms.erase(i);
-                                       }
-                               }
-                       }
+               if (i == 0) {
+                       is_zero = true;
+                       break;
                }
+               --i;
+       } while (true);
+
+       if (is_zero) {
+               p.clear();
+               return;
        }
-       cl_MI unit() const
-       {
-               return terms.front().c;
+
+       p.erase(p.begin() + i, p.end());
+}
+
+// END COPY FROM UPOLY.HPP
+
+static void expt_pos(umodpoly& a, unsigned int q)
+{
+       if ( a.empty() ) return;
+       cl_MI zero = a[0].ring()->zero(); 
+       int deg = degree(a);
+       a.resize(degree(a)*q+1, zero);
+       for ( int i=deg; i>0; --i ) {
+               a[i*q] = a[i];
+               a[i] = zero;
        }
-       void divide(const cl_MI& x)
-       {
-               list<Term>::iterator i = terms.begin(), end = terms.end();
-               for ( ; i != end; ++i ) {
-                       i->c = div(i->c, x);
-                       if ( zerop(i->c) ) {
-                               terms.erase(i);
-                       }
-               }
+}
+
+template<typename T>
+static T operator+(const T& a, const T& b)
+{
+       int sa = a.size();
+       int sb = b.size();
+       if ( sa >= sb ) {
+               T r(sa);
+               int i = 0;
+               for ( ; i<sb; ++i ) {
+                       r[i] = a[i] + b[i];
+               }
+               for ( ; i<sa; ++i ) {
+                       r[i] = a[i];
+               }
+               canonicalize(r);
+               return r;
        }
-       void divide(const cl_I& x)
-       {
-               list<Term>::iterator i = terms.begin(), end = terms.end();
-               for ( ; i != end; ++i ) {
-                       i->c = cl_MI(R, the<cl_I>(R->retract(i->c) / x));
+       else {
+               T r(sb);
+               int i = 0;
+               for ( ; i<sa; ++i ) {
+                       r[i] = a[i] + b[i];
                }
-       }
-       void reduce_exponents(unsigned int prime)
-       {
-               list<Term>::iterator i = terms.begin(), end = terms.end();
-               while ( i != end ) {
-                       if ( i->exp > 0 ) {
-                               // assert: i->exp is multiple of prime
-                               i->exp /= prime;
-                       }
-                       ++i;
-               }
-       }
-       void deriv(UniPoly& d) const
-       {
-               list<Term>::const_iterator i = terms.begin(), end = terms.end();
-               while ( i != end ) {
-                       if ( i->exp ) {
-                               cl_MI newc = i->c * i->exp;
-                               if ( !zerop(newc) ) {
-                                       Term t;
-                                       t.c = newc;
-                                       t.exp = i->exp-1;
-                                       d.terms.push_back(t);
-                               }
-                       }
-                       ++i;
+               for ( ; i<sb; ++i ) {
+                       r[i] = b[i];
                }
+               canonicalize(r);
+               return r;
        }
-       bool operator<(const UniPoly& o) const
-       {
-               if ( terms.size() != o.terms.size() ) {
-                       return terms.size() < o.terms.size();
-               }
-               list<Term>::const_iterator i1 = terms.begin(), end = terms.end();
-               list<Term>::const_iterator i2 = o.terms.begin();
-               while ( i1 != end ) {
-                       if ( i1->exp != i2->exp ) {
-                               return i1->exp < i2->exp;
-                       }
-                       if ( i1->c != i2->c ) {
-                               return R->retract(i1->c) < R->retract(i2->c);
-                       }
-                       ++i1; ++i2;
-               }
-               return true;
+}
+
+template<typename T>
+static T operator-(const T& a, const T& b)
+{
+       int sa = a.size();
+       int sb = b.size();
+       if ( sa >= sb ) {
+               T r(sa);
+               int i = 0;
+               for ( ; i<sb; ++i ) {
+                       r[i] = a[i] - b[i];
+               }
+               for ( ; i<sa; ++i ) {
+                       r[i] = a[i];
+               }
+               canonicalize(r);
+               return r;
        }
-       bool operator==(const UniPoly& o) const
-       {
-               if ( terms.size() != o.terms.size() ) {
-                       return false;
+       else {
+               T r(sb);
+               int i = 0;
+               for ( ; i<sa; ++i ) {
+                       r[i] = a[i] - b[i];
                }
-               list<Term>::const_iterator i1 = terms.begin(), end = terms.end();
-               list<Term>::const_iterator i2 = o.terms.begin();
-               while ( i1 != end ) {
-                       if ( i1->exp != i2->exp ) {
-                               return false;
-                       }
-                       if ( i1->c != i2->c ) {
-                               return false;
-                       }
-                       ++i1; ++i2;
+               for ( ; i<sb; ++i ) {
+                       r[i] = -b[i];
                }
-               return true;
-       }
-       bool operator!=(const UniPoly& o) const
-       {
-               bool res = !(*this == o);
-               return res;
+               canonicalize(r);
+               return r;
        }
-};
+}
 
-static UniPoly operator*(const UniPoly& a, const UniPoly& b)
+static upoly operator*(const upoly& a, const upoly& b)
 {
-       unsigned int n = a.degree()+b.degree();
-       UniPoly c(a.R);
-       Term t;
-       for ( unsigned int i=0 ; i<=n; ++i ) {
-               t.c = a.R->zero();
-               for ( unsigned int j=0 ; j<=i; ++j ) {
-                       t.c = t.c + a[j] * b[i-j];
-               }
-               if ( !zerop(t.c) ) {
-                       t.exp = i;
-                       c.terms.push_front(t);
+       upoly c;
+       if ( a.empty() || b.empty() ) return c;
+
+       int n = degree(a) + degree(b);
+       c.resize(n+1, 0);
+       for ( int i=0 ; i<=n; ++i ) {
+               for ( int j=0 ; j<=i; ++j ) {
+                       if ( j > degree(a) || (i-j) > degree(b) ) continue;
+                       c[i] = c[i] + a[j] * b[i-j];
                }
        }
+       canonicalize(c);
        return c;
 }
 
-static UniPoly operator-(const UniPoly& a, const UniPoly& b)
+static umodpoly operator*(const umodpoly& a, const umodpoly& b)
 {
-       list<Term>::const_iterator ia = a.terms.begin(), aend = a.terms.end();
-       list<Term>::const_iterator ib = b.terms.begin(), bend = b.terms.end();
-       UniPoly c(a.R);
-       while ( ia != aend && ib != bend ) {
-               if ( ia->exp > ib->exp ) {
-                       c.terms.push_back(*ia);
-                       ++ia;
-               }
-               else if ( ia->exp < ib->exp ) {
-                       c.terms.push_back(*ib);
-                       c.terms.back().c = -c.terms.back().c;
-                       ++ib;
-               }
-               else {
-                       Term t;
-                       t.exp = ia->exp;
-                       t.c = ia->c - ib->c;
-                       if ( !zerop(t.c) ) {
-                               c.terms.push_back(t);
-                       }
-                       ++ia; ++ib;
+       umodpoly c;
+       if ( a.empty() || b.empty() ) return c;
+
+       int n = degree(a) + degree(b);
+       c.resize(n+1, a[0].ring()->zero());
+       for ( int i=0 ; i<=n; ++i ) {
+               for ( int j=0 ; j<=i; ++j ) {
+                       if ( j > degree(a) || (i-j) > degree(b) ) continue;
+                       c[i] = c[i] + a[j] * b[i-j];
                }
        }
-       while ( ia != aend ) {
-               c.terms.push_back(*ia);
-               ++ia;
-       }
-       while ( ib != bend ) {
-               c.terms.push_back(*ib);
-               c.terms.back().c = -c.terms.back().c;
-               ++ib;
-       }
+       canonicalize(c);
        return c;
 }
 
-static UniPoly operator*(const UniPoly& a, const cl_MI& fac)
+static upoly operator*(const upoly& a, const cl_I& x)
 {
-       unsigned int n = a.degree();
-       UniPoly c(a.R);
-       Term t;
-       for ( unsigned int i=0 ; i<=n; ++i ) {
-               t.c = a[i] * fac;
-               if ( !zerop(t.c) ) {
-                       t.exp = i;
-                       c.terms.push_front(t);
-               }
+       if ( zerop(x) ) {
+               upoly r;
+               return r;
        }
-       return c;
+       upoly r(a.size());
+       for ( size_t i=0; i<a.size(); ++i ) {
+               r[i] = a[i] * x;
+       }
+       return r;
 }
 
-static UniPoly operator+(const UniPoly& a, const UniPoly& b)
+static upoly operator/(const upoly& a, const cl_I& x)
 {
-       list<Term>::const_iterator ia = a.terms.begin(), aend = a.terms.end();
-       list<Term>::const_iterator ib = b.terms.begin(), bend = b.terms.end();
-       UniPoly c(a.R);
-       while ( ia != aend && ib != bend ) {
-               if ( ia->exp > ib->exp ) {
-                       c.terms.push_back(*ia);
-                       ++ia;
-               }
-               else if ( ia->exp < ib->exp ) {
-                       c.terms.push_back(*ib);
-                       ++ib;
-               }
-               else {
-                       Term t;
-                       t.exp = ia->exp;
-                       t.c = ia->c + ib->c;
-                       if ( !zerop(t.c) ) {
-                               c.terms.push_back(t);
-                       }
-                       ++ia; ++ib;
-               }
-       }
-       while ( ia != aend ) {
-               c.terms.push_back(*ia);
-               ++ia;
+       if ( zerop(x) ) {
+               upoly r;
+               return r;
        }
-       while ( ib != bend ) {
-               c.terms.push_back(*ib);
-               ++ib;
+       upoly r(a.size());
+       for ( size_t i=0; i<a.size(); ++i ) {
+               r[i] = exquo(a[i],x);
        }
-       return c;
+       return r;
 }
 
-// static UniPoly operator-(const UniPoly& a)
-// {
-//     list<Term>::const_iterator ia = a.terms.begin(), aend = a.terms.end();
-//     UniPoly c(a.R);
-//     while ( ia != aend ) {
-//             c.terms.push_back(*ia);
-//             c.terms.back().c = -c.terms.back().c;
-//             ++ia;
-//     }
-//     return c;
-// }
+static umodpoly operator*(const umodpoly& a, const cl_MI& x)
+{
+       umodpoly r(a.size());
+       for ( size_t i=0; i<a.size(); ++i ) {
+               r[i] = a[i] * x;
+       }
+       canonicalize(r);
+       return r;
+}
 
-#ifdef DEBUGFACTOR
-ostream& operator<<(ostream& o, const UniPoly& t)
+static void upoly_from_ex(upoly& up, const ex& e, const ex& x)
 {
-       list<Term>::const_iterator i = t.terms.begin(), end = t.terms.end();
-       if ( i == end ) {
-               o << "0";
-               return o;
+       // assert: e is in Z[x]
+       int deg = e.degree(x);
+       up.resize(deg+1);
+       int ldeg = e.ldegree(x);
+       for ( ; deg>=ldeg; --deg ) {
+               up[deg] = the<cl_I>(ex_to<numeric>(e.coeff(x, deg)).to_cl_N());
        }
-       for ( ; i != end; ) {
-               o << *i++;
-               if ( i != end ) {
-                       o << " + ";
-               }
+       for ( ; deg>=0; --deg ) {
+               up[deg] = 0;
        }
-       return o;
+       canonicalize(up);
 }
-#endif // def DEBUGFACTOR
 
-#ifdef DEBUGFACTOR
-ostream& operator<<(ostream& o, const list<UniPoly>& t)
+static void umodpoly_from_upoly(umodpoly& ump, const upoly& e, const cl_modint_ring& R)
 {
-       list<UniPoly>::const_iterator i = t.begin(), end = t.end();
-       o << "{" << endl;
-       for ( ; i != end; ) {
-               o << *i++ << endl;
+       int deg = degree(e);
+       ump.resize(deg+1);
+       for ( ; deg>=0; --deg ) {
+               ump[deg] = R->canonhom(e[deg]);
        }
-       o << "}" << endl;
-       return o;
+       canonicalize(ump);
 }
-#endif // def DEBUGFACTOR
-
-typedef vector<UniPoly> UniPolyVec;
 
-#ifdef DEBUGFACTOR
-ostream& operator<<(ostream& o, const UniPolyVec& v)
+static void umodpoly_from_ex(umodpoly& ump, const ex& e, const ex& x, const cl_modint_ring& R)
 {
-       UniPolyVec::const_iterator i = v.begin(), end = v.end();
-       while ( i != end ) {
-               o << *i++ << " , " << endl;
-       }
-       return o;
+       // assert: e is in Z[x]
+       int deg = e.degree(x);
+       ump.resize(deg+1);
+       int ldeg = e.ldegree(x);
+       for ( ; deg>=ldeg; --deg ) {
+               cl_I coeff = the<cl_I>(ex_to<numeric>(e.coeff(x, deg)).to_cl_N());
+               ump[deg] = R->canonhom(coeff);
+       }
+       for ( ; deg>=0; --deg ) {
+               ump[deg] = R->zero();
+       }
+       canonicalize(ump);
 }
-#endif // def DEBUGFACTOR
 
-struct UniFactor
+static void umodpoly_from_ex(umodpoly& ump, const ex& e, const ex& x, const cl_I& modulus)
 {
-       UniPoly p;
-       unsigned int exp;
+       umodpoly_from_ex(ump, e, x, find_modint_ring(modulus));
+}
 
-       UniFactor(const cl_modint_ring& ring) : p(ring) { }
-       UniFactor(const UniPoly& p_, unsigned int exp_) : p(p_), exp(exp_) { }
-       bool operator<(const UniFactor& o) const
-       {
-               return p < o.p;
+static ex upoly_to_ex(const upoly& a, const ex& x)
+{
+       if ( a.empty() ) return 0;
+       ex e;
+       for ( int i=degree(a); i>=0; --i ) {
+               e += numeric(a[i]) * pow(x, i);
        }
-};
+       return e;
+}
 
-struct UniFactorVec
+static ex umodpoly_to_ex(const umodpoly& a, const ex& x)
 {
-       vector<UniFactor> factors;
-
-       void unique()
-       {
-               sort(factors.begin(), factors.end());
-               if ( factors.size() > 1 ) {
-                       vector<UniFactor>::iterator i = factors.begin();
-                       vector<UniFactor>::const_iterator cmp = factors.begin()+1;
-                       vector<UniFactor>::iterator end = factors.end();
-                       while ( cmp != end ) {
-                               if ( i->p != cmp->p ) {
-                                       ++i;
-                                       ++cmp;
-                               }
-                               else {
-                                       i->exp += cmp->exp;
-                                       ++cmp;
-                               }
-                       }
-                       if ( i != end-1 ) {
-                               factors.erase(i+1, end);
-                       }
-               }
-       }
-};
+       if ( a.empty() ) return 0;
+       cl_modint_ring R = a[0].ring();
+       cl_I mod = R->modulus;
+       cl_I halfmod = (mod-1) >> 1;
+       ex e;
+       for ( int i=degree(a); i>=0; --i ) {
+               cl_I n = R->retract(a[i]);
+               if ( n > halfmod ) {
+                       e += numeric(n-mod) * pow(x, i);
+               } else {
+                       e += numeric(n) * pow(x, i);
+               }
+       }
+       return e;
+}
 
-#ifdef DEBUGFACTOR
-ostream& operator<<(ostream& o, const UniFactorVec& ufv)
+static upoly umodpoly_to_upoly(const umodpoly& a)
 {
-       for ( size_t i=0; i<ufv.factors.size(); ++i ) {
-               if ( i != ufv.factors.size()-1 ) {
-                       o << "*";
-               }
-               else {
-                       o << " ";
-               }
-               o << "[ " << ufv.factors[i].p << " ]^" << ufv.factors[i].exp << endl;
-       }
-       return o;
+       upoly e(a.size());
+       if ( a.empty() ) return e;
+       cl_modint_ring R = a[0].ring();
+       cl_I mod = R->modulus;
+       cl_I halfmod = (mod-1) >> 1;
+       for ( int i=degree(a); i>=0; --i ) {
+               cl_I n = R->retract(a[i]);
+               if ( n > halfmod ) {
+                       e[i] = n-mod;
+               } else {
+                       e[i] = n;
+               }
+       }
+       return e;
 }
-#endif // def DEBUGFACTOR
 
-static void rem(const UniPoly& a_, const UniPoly& b, UniPoly& c)
+static umodpoly umodpoly_to_umodpoly(const umodpoly& a, const cl_modint_ring& R, unsigned int m)
 {
-       if ( a_.degree() < b.degree() ) {
-               c = a_;
-               return;
-       }
+       umodpoly e;
+       if ( a.empty() ) return e;
+       cl_modint_ring oldR = a[0].ring();
+       size_t sa = a.size();
+       e.resize(sa+m, R->zero());
+       for ( int i=0; i<sa; ++i ) {
+               e[i+m] = R->canonhom(oldR->retract(a[i]));
+       }
+       canonicalize(e);
+       return e;
+}
 
-       unsigned int k, n;
-       n = b.degree();
-       k = a_.degree() - n;
+/** Divides all coefficients of the polynomial a by the integer x.
+ *  All coefficients are supposed to be divisible by x. If they are not, the
+ *  the<cl_I> cast will raise an exception.
+ *
+ *  @param[in,out] a  polynomial of which the coefficients will be reduced by x
+ *  @param[in]     x  integer that divides the coefficients
+ */
+static void reduce_coeff(umodpoly& a, const cl_I& x)
+{
+       if ( a.empty() ) return;
 
-       if ( n == 0 ) {
-               c.terms.clear();
-               return;
+       cl_modint_ring R = a[0].ring();
+       umodpoly::iterator i = a.begin(), end = a.end();
+       for ( ; i!=end; ++i ) {
+               // cln cannot perform this division in the modular field
+               cl_I c = R->retract(*i);
+               *i = cl_MI(R, the<cl_I>(c / x));
        }
+}
 
-       c = a_;
-       Term termbuf;
-
-       while ( true ) {
-               cl_MI qk = div(c[n+k], b[n]);
+/** Calculates remainder of a/b.
+ *  Assertion: a and b not empty.
+ *
+ *  @param[in]  a  polynomial dividend
+ *  @param[in]  b  polynomial divisor
+ *  @param[out] r  polynomial remainder
+ */
+static void rem(const umodpoly& a, const umodpoly& b, umodpoly& r)
+{
+       int k, n;
+       n = degree(b);
+       k = degree(a) - n;
+       r = a;
+       if ( k < 0 ) return;
+
+       do {
+               cl_MI qk = div(r[n+k], b[n]);
                if ( !zerop(qk) ) {
-                       unsigned int j;
-                       for ( unsigned int i=0; i<n; ++i ) {
-                               j = n + k - 1 - i;
-                               c.set(j, c[j] - qk*b[j-k]);
+                       for ( int i=0; i<n; ++i ) {
+                               unsigned int j = n + k - 1 - i;
+                               r[j] = r[j] - qk * b[j-k];
                        }
                }
-               if ( k == 0 ) break;
-               --k;
-       }
-       list<Term>::iterator i = c.terms.begin(), end = c.terms.end();
-       while ( i != end ) {
-               if ( i->exp <= n-1 ) {
-                       break;
-               }
-               ++i;
-       }
-       c.terms.erase(c.terms.begin(), i);
+       } while ( k-- );
+
+       fill(r.begin()+n, r.end(), a[0].ring()->zero());
+       canonicalize(r);
 }
 
-static void div(const UniPoly& a_, const UniPoly& b, UniPoly& q)
+/** Calculates quotient of a/b.
+ *  Assertion: a and b not empty.
+ *
+ *  @param[in]  a  polynomial dividend
+ *  @param[in]  b  polynomial divisor
+ *  @param[out] q  polynomial quotient
+ */
+static void div(const umodpoly& a, const umodpoly& b, umodpoly& q)
 {
-       if ( a_.degree() < b.degree() ) {
-               q.terms.clear();
-               return;
-       }
-
-       unsigned int k, n;
-       n = b.degree();
-       k = a_.degree() - n;
+       int k, n;
+       n = degree(b);
+       k = degree(a) - n;
+       q.clear();
+       if ( k < 0 ) return;
+
+       umodpoly r = a;
+       q.resize(k+1, a[0].ring()->zero());
+       do {
+               cl_MI qk = div(r[n+k], b[n]);
+               if ( !zerop(qk) ) {
+                       q[k] = qk;
+                       for ( int i=0; i<n; ++i ) {
+                               unsigned int j = n + k - 1 - i;
+                               r[j] = r[j] - qk * b[j-k];
+                       }
+               }
+       } while ( k-- );
 
-       UniPoly c = a_;
-       Term termbuf;
+       canonicalize(q);
+}
 
-       while ( true ) {
-               cl_MI qk = div(c[n+k], b[n]);
+/** Calculates quotient and remainder of a/b.
+ *  Assertion: a and b not empty.
+ *
+ *  @param[in]  a  polynomial dividend
+ *  @param[in]  b  polynomial divisor
+ *  @param[out] r  polynomial remainder
+ *  @param[out] q  polynomial quotient
+ */
+static void remdiv(const umodpoly& a, const umodpoly& b, umodpoly& r, umodpoly& q)
+{
+       int k, n;
+       n = degree(b);
+       k = degree(a) - n;
+       q.clear();
+       r = a;
+       if ( k < 0 ) return;
+
+       q.resize(k+1, a[0].ring()->zero());
+       do {
+               cl_MI qk = div(r[n+k], b[n]);
                if ( !zerop(qk) ) {
-                       Term t;
-                       t.c = qk;
-                       t.exp = k;
-                       q.terms.push_back(t);
-                       unsigned int j;
-                       for ( unsigned int i=0; i<n; ++i ) {
-                               j = n + k - 1 - i;
-                               c.set(j, c[j] - qk*b[j-k]);
+                       q[k] = qk;
+                       for ( int i=0; i<n; ++i ) {
+                               unsigned int j = n + k - 1 - i;
+                               r[j] = r[j] - qk * b[j-k];
                        }
                }
-               if ( k == 0 ) break;
-               --k;
-       }
+       } while ( k-- );
+
+       fill(r.begin()+n, r.end(), a[0].ring()->zero());
+       canonicalize(r);
+       canonicalize(q);
 }
 
-static void gcd(const UniPoly& a, const UniPoly& b, UniPoly& c)
+/** Calculates the GCD of polynomial a and b.
+ *
+ *  @param[in]  a  polynomial
+ *  @param[in]  b  polynomial
+ *  @param[out] c  GCD
+ */
+static void gcd(const umodpoly& a, const umodpoly& b, umodpoly& c)
 {
-       c = a;
-       c.unit_normal();
-       UniPoly d = b;
-       d.unit_normal();
+       if ( degree(a) < degree(b) ) return gcd(b, a, c);
 
-       if ( c.degree() < d.degree() ) {
-               gcd(b, a, c);
-               return;
-       }
-
-       while ( !d.zero() ) {
-               UniPoly r(a.R);
+       c = a;
+       normalize_in_field(c);
+       umodpoly d = b;
+       normalize_in_field(d);
+       umodpoly r;
+       while ( !d.empty() ) {
                rem(c, d, r);
                c = d;
                d = r;
        }
-       c.unit_normal();
+       normalize_in_field(c);
 }
 
-static bool is_one(const UniPoly& w)
+/** Calculates the derivative of the polynomial a.
+ *  
+ *  @param[in]  a  polynomial of which to take the derivative
+ *  @param[out] d  result/derivative
+ */
+static void deriv(const umodpoly& a, umodpoly& d)
 {
-       if ( w.terms.size() == 1 && w[0] == w.R->one() ) {
-               return true;
+       d.clear();
+       if ( a.size() <= 1 ) return;
+
+       d.insert(d.begin(), a.begin()+1, a.end());
+       int max = d.size();
+       for ( int i=1; i<max; ++i ) {
+               d[i] = d[i] * (i+1);
        }
-       return false;
+       canonicalize(d);
 }
 
-static void sqrfree_main(const UniPoly& a, UniFactorVec& fvec)
+static bool unequal_one(const umodpoly& a)
 {
-       unsigned int i = 1;
-       UniPoly b(a.R);
-       a.deriv(b);
-       if ( !b.zero() ) {
-               UniPoly c(a.R), w(a.R);
-               gcd(a, b, c);
-               div(a, c, w);
-               while ( !is_one(w) ) {
-                       UniPoly y(a.R), z(a.R);
-                       gcd(w, c, y);
-                       div(w, y, z);
-                       if ( !is_one(z) ) {
-                               UniFactor uf(z, i);
-                               fvec.factors.push_back(uf);
-                       }
-                       ++i;
-                       w = y;
-                       UniPoly cbuf(a.R);
-                       div(c, y, cbuf);
-                       c = cbuf;
-               }
-               if ( !is_one(c) ) {
-                       unsigned int prime = cl_I_to_uint(c.R->modulus);
-                       c.reduce_exponents(prime);
-                       unsigned int pos = fvec.factors.size();
-                       sqrfree_main(c, fvec);
-                       for ( unsigned int p=pos; p<fvec.factors.size(); ++p ) {
-                               fvec.factors[p].exp *= prime;
-                       }
-                       return;
-               }
-       }
-       else {
-               unsigned int prime = cl_I_to_uint(a.R->modulus);
-               UniPoly amod = a;
-               amod.reduce_exponents(prime);
-               unsigned int pos = fvec.factors.size();
-               sqrfree_main(amod, fvec);
-               for ( unsigned int p=pos; p<fvec.factors.size(); ++p ) {
-                       fvec.factors[p].exp *= prime;
-               }
-               return;
-       }
+       if ( a.empty() ) return true;
+       return ( a.size() != 1 || a[0] != a[0].ring()->one() );
 }
 
-static void squarefree(const UniPoly& a, UniFactorVec& fvec)
+static bool equal_one(const umodpoly& a)
 {
-       sqrfree_main(a, fvec);
-       fvec.unique();
+       return ( a.size() == 1 && a[0] == a[0].ring()->one() );
 }
 
-class Matrix
+/** Returns true if polynomial a is square free.
+ *
+ *  @param[in] a  polynomial to check
+ *  @return       true if polynomial is square free, false otherwise
+ */
+static bool squarefree(const umodpoly& a)
 {
-       friend ostream& operator<<(ostream& o, const Matrix& m);
+       umodpoly b;
+       deriv(a, b);
+       if ( b.empty() ) {
+               return true;
+       }
+       umodpoly c;
+       gcd(a, b, c);
+       return equal_one(c);
+}
+
+// END modular univariate polynomial code
+////////////////////////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////////////////////////
+// modular matrix
+
+class modular_matrix
+{
+       friend ostream& operator<<(ostream& o, const modular_matrix& m);
 public:
-       Matrix(size_t r_, size_t c_, const cl_MI& init) : r(r_), c(c_)
+       modular_matrix(size_t r_, size_t c_, const cl_MI& init) : r(r_), c(c_)
        {
                m.resize(c*r, init);
        }
@@ -727,7 +633,7 @@ public:
        cl_MI operator()(size_t row, size_t col) const { return m[row*c + col]; }
        void mul_col(size_t col, const cl_MI x)
        {
-               Vec::iterator i = m.begin() + col;
+               mvec::iterator i = m.begin() + col;
                for ( size_t rc=0; rc<r; ++rc ) {
                        *i = *i * x;
                        i += c;
@@ -735,8 +641,8 @@ public:
        }
        void sub_col(size_t col1, size_t col2, const cl_MI fac)
        {
-               Vec::iterator i1 = m.begin() + col1;
-               Vec::iterator i2 = m.begin() + col2;
+               mvec::iterator i1 = m.begin() + col1;
+               mvec::iterator i2 = m.begin() + col2;
                for ( size_t rc=0; rc<r; ++rc ) {
                        *i1 = *i1 - *i2 * fac;
                        i1 += c;
@@ -746,8 +652,8 @@ public:
        void switch_col(size_t col1, size_t col2)
        {
                cl_MI buf;
-               Vec::iterator i1 = m.begin() + col1;
-               Vec::iterator i2 = m.begin() + col2;
+               mvec::iterator i1 = m.begin() + col1;
+               mvec::iterator i2 = m.begin() + col2;
                for ( size_t rc=0; rc<r; ++rc ) {
                        buf = *i1; *i1 = *i2; *i2 = buf;
                        i1 += c;
@@ -785,7 +691,7 @@ public:
        }
        bool is_col_zero(size_t col) const
        {
-               Vec::const_iterator i = m.begin() + col;
+               mvec::const_iterator i = m.begin() + col;
                for ( size_t rr=0; rr<r; ++rr ) {
                        if ( !zerop(*i) ) {
                                return false;
@@ -796,7 +702,7 @@ public:
        }
        bool is_row_zero(size_t row) const
        {
-               Vec::const_iterator i = m.begin() + row*c;
+               mvec::const_iterator i = m.begin() + row*c;
                for ( size_t cc=0; cc<c; ++cc ) {
                        if ( !zerop(*i) ) {
                                return false;
@@ -807,25 +713,25 @@ public:
        }
        void set_row(size_t row, const vector<cl_MI>& newrow)
        {
-               Vec::iterator i1 = m.begin() + row*c;
-               Vec::const_iterator i2 = newrow.begin(), end = newrow.end();
+               mvec::iterator i1 = m.begin() + row*c;
+               mvec::const_iterator i2 = newrow.begin(), end = newrow.end();
                for ( ; i2 != end; ++i1, ++i2 ) {
                        *i1 = *i2;
                }
        }
-       Vec::const_iterator row_begin(size_t row) const { return m.begin()+row*c; }
-       Vec::const_iterator row_end(size_t row) const { return m.begin()+row*c+r; }
+       mvec::const_iterator row_begin(size_t row) const { return m.begin()+row*c; }
+       mvec::const_iterator row_end(size_t row) const { return m.begin()+row*c+r; }
 private:
        size_t r, c;
-       Vec m;
+       mvec m;
 };
 
 #ifdef DEBUGFACTOR
-Matrix operator*(const Matrix& m1, const Matrix& m2)
+modular_matrix operator*(const modular_matrix& m1, const modular_matrix& m2)
 {
        const unsigned int r = m1.rowsize();
        const unsigned int c = m2.colsize();
-       Matrix o(r,c,m1(0,0));
+       modular_matrix o(r,c,m1(0,0));
 
        for ( size_t i=0; i<r; ++i ) {
                for ( size_t j=0; j<c; ++j ) {
@@ -840,55 +746,52 @@ Matrix operator*(const Matrix& m1, const Matrix& m2)
        return o;
 }
 
-ostream& operator<<(ostream& o, const Matrix& m)
+ostream& operator<<(ostream& o, const modular_matrix& m)
 {
-       vector<cl_MI>::const_iterator i = m.m.begin(), end = m.m.end();
-       size_t wrap = 1;
-       for ( ; i != end; ++i ) {
-               o << *i << " ";
-               if ( !(wrap++ % m.c) ) {
-                       o << endl;
+       cl_modint_ring R = m(0,0).ring();
+       o << "{";
+       for ( size_t i=0; i<m.rowsize(); ++i ) {
+               o << "{";
+               for ( size_t j=0; j<m.colsize()-1; ++j ) {
+                       o << R->retract(m(i,j)) << ",";
+               }
+               o << R->retract(m(i,m.colsize()-1)) << "}";
+               if ( i != m.rowsize()-1 ) {
+                       o << ",";
                }
        }
-       o << endl;
+       o << "}";
        return o;
 }
 #endif // def DEBUGFACTOR
 
-static void q_matrix(const UniPoly& a, Matrix& Q)
-{
-       unsigned int n = a.degree();
-       unsigned int q = cl_I_to_uint(a.R->modulus);
-// fast and buggy
-//     vector<cl_MI> r(n, a.R->zero());
-//     r[0] = a.R->one();
-//     Q.set_row(0, r);
-//     unsigned int max = (n-1) * q;
-//     for ( size_t m=1; m<=max; ++m ) {
-//             cl_MI rn_1 = r.back();
-//             for ( size_t i=n-1; i>0; --i ) {
-//                     r[i] = r[i-1] - rn_1 * a[i];
-//             }
-//             r[0] = -rn_1 * a[0];
-//             if ( (m % q) == 0 ) {
-//                     Q.set_row(m/q, r);
-//             }
-//     }
-// slow and (hopefully) correct
-       for ( size_t i=0; i<n; ++i ) {
-               UniPoly qk(a.R);
-               qk.set(i*q, a.R->one());
-               UniPoly r(a.R);
-               rem(qk, a, r);
-               Vec rvec;
-               for ( size_t j=0; j<n; ++j ) {
-                       rvec.push_back(r[j]);
+// END modular matrix
+////////////////////////////////////////////////////////////////////////////////
+
+static void q_matrix(const umodpoly& a_, modular_matrix& Q)
+{
+       umodpoly a = a_;
+       normalize_in_field(a);
+
+       int n = degree(a);
+       unsigned int q = cl_I_to_uint(a[0].ring()->modulus);
+       umodpoly r(n, a[0].ring()->zero());
+       r[0] = a[0].ring()->one();
+       Q.set_row(0, r);
+       unsigned int max = (n-1) * q;
+       for ( size_t m=1; m<=max; ++m ) {
+               cl_MI rn_1 = r.back();
+               for ( size_t i=n-1; i>0; --i ) {
+                       r[i] = r[i-1] - (rn_1 * a[i]);
+               }
+               r[0] = -rn_1 * a[0];
+               if ( (m % q) == 0 ) {
+                       Q.set_row(m/q, r);
                }
-               Q.set_row(i, rvec);
        }
 }
 
-static void nullspace(Matrix& M, vector<Vec>& basis)
+static void nullspace(modular_matrix& M, vector<mvec>& basis)
 {
        const size_t n = M.rowsize();
        const cl_MI one = M(0,0).ring()->one();
@@ -926,41 +829,46 @@ static void nullspace(Matrix& M, vector<Vec>& basis)
        }
        for ( size_t i=0; i<n; ++i ) {
                if ( !M.is_row_zero(i) ) {
-                       Vec nu(M.row_begin(i), M.row_end(i));
+                       mvec nu(M.row_begin(i), M.row_end(i));
                        basis.push_back(nu);
                }
        }
 }
 
-static void berlekamp(const UniPoly& a, UniPolyVec& upv)
+static void berlekamp(const umodpoly& a, upvec& upv)
 {
-       Matrix Q(a.degree(), a.degree(), a.R->zero());
+       cl_modint_ring R = a[0].ring();
+       umodpoly one(1, R->one());
+
+       modular_matrix Q(degree(a), degree(a), R->zero());
        q_matrix(a, Q);
-       VecVec nu;
+       vector<mvec> nu;
        nullspace(Q, nu);
+
        const unsigned int k = nu.size();
        if ( k == 1 ) {
                return;
        }
 
-       list<UniPoly> factors;
+       list<umodpoly> factors;
        factors.push_back(a);
        unsigned int size = 1;
        unsigned int r = 1;
-       unsigned int q = cl_I_to_uint(a.R->modulus);
+       unsigned int q = cl_I_to_uint(R->modulus);
 
-       list<UniPoly>::iterator u = factors.begin();
+       list<umodpoly>::iterator u = factors.begin();
 
        while ( true ) {
                for ( unsigned int s=0; s<q; ++s ) {
-                       UniPoly g(a.R);
-                       UniPoly nur(a.R, nu[r]);
-                       nur.set(0, nur[0] - cl_MI(a.R, s));
+                       umodpoly nur = nu[r];
+                       nur[0] = nur[0] - cl_MI(R, s);
+                       canonicalize(nur);
+                       umodpoly g;
                        gcd(nur, *u, g);
-                       if ( !is_one(g) && g != *u ) {
-                               UniPoly uo(a.R);
+                       if ( unequal_one(g) && g != *u ) {
+                               umodpoly uo;
                                div(*u, g, uo);
-                               if ( is_one(uo) ) {
+                               if ( equal_one(uo) ) {
                                        throw logic_error("berlekamp: unexpected divisor.");
                                }
                                else {
@@ -968,21 +876,18 @@ static void berlekamp(const UniPoly& a, UniPolyVec& upv)
                                }
                                factors.push_back(g);
                                size = 0;
-                               list<UniPoly>::const_iterator i = factors.begin(), end = factors.end();
+                               list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
                                while ( i != end ) {
-                                       if ( i->degree() ) ++size; 
+                                       if ( degree(*i) ) ++size; 
                                        ++i;
                                }
                                if ( size == k ) {
-                                       list<UniPoly>::const_iterator i = factors.begin(), end = factors.end();
+                                       list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
                                        while ( i != end ) {
                                                upv.push_back(*i++);
                                        }
                                        return;
                                }
-//                             if ( u->degree() < nur.degree() ) {
-//                                     break;
-//                             }
                        }
                }
                if ( ++r == k ) {
@@ -992,121 +897,299 @@ static void berlekamp(const UniPoly& a, UniPolyVec& upv)
        }
 }
 
-static void factor_modular(const UniPoly& p, UniPolyVec& upv)
-{
-       berlekamp(p, upv);
-       return;
-}
-
-static void exteuclid(const UniPoly& a, const UniPoly& b, UniPoly& g, UniPoly& s, UniPoly& t)
+static void expt_1_over_p(const umodpoly& a, unsigned int prime, umodpoly& ap)
+{
+       size_t newdeg = degree(a)/prime;
+       ap.resize(newdeg+1);
+       ap[0] = a[0];
+       for ( size_t i=1; i<=newdeg; ++i ) {
+               ap[i] = a[i*prime];
+       }
+}
+
+static void modsqrfree(const umodpoly& a, upvec& factors, vector<int>& mult)
+{
+       const unsigned int prime = cl_I_to_uint(a[0].ring()->modulus);
+       int i = 1;
+       umodpoly b;
+       deriv(a, b);
+       if ( b.size() ) {
+               umodpoly c;
+               gcd(a, b, c);
+               umodpoly w;
+               div(a, c, w);
+               while ( unequal_one(w) ) {
+                       umodpoly y;
+                       gcd(w, c, y);
+                       umodpoly z;
+                       div(w, y, z);
+                       factors.push_back(z);
+                       mult.push_back(i);
+                       ++i;
+                       w = y;
+                       umodpoly buf;
+                       div(c, y, buf);
+                       c = buf;
+               }
+               if ( unequal_one(c) ) {
+                       umodpoly cp;
+                       expt_1_over_p(c, prime, cp);
+                       size_t previ = mult.size();
+                       modsqrfree(cp, factors, mult);
+                       for ( size_t i=previ; i<mult.size(); ++i ) {
+                               mult[i] *= prime;
+                       }
+               }
+       }
+       else {
+               umodpoly ap;
+               expt_1_over_p(a, prime, ap);
+               size_t previ = mult.size();
+               modsqrfree(ap, factors, mult);
+               for ( size_t i=previ; i<mult.size(); ++i ) {
+                       mult[i] *= prime;
+               }
+       }
+}
+
+static void distinct_degree_factor(const umodpoly& a_, vector<int>& degrees, upvec& ddfactors)
+{
+       umodpoly a = a_;
+
+       cl_modint_ring R = a[0].ring();
+       int q = cl_I_to_int(R->modulus);
+       int nhalf = degree(a)/2;
+
+       int i = 1;
+       umodpoly w(2);
+       w[0] = R->zero();
+       w[1] = R->one();
+       umodpoly x = w;
+
+       bool nontrivial = false;
+       while ( i <= nhalf ) {
+               expt_pos(w, q);
+               umodpoly buf;
+               rem(w, a, buf);
+               w = buf;
+               umodpoly wx = w - x;
+               gcd(a, wx, buf);
+               if ( unequal_one(buf) ) {
+                       degrees.push_back(i);
+                       ddfactors.push_back(buf);
+               }
+               if ( unequal_one(buf) ) {
+                       umodpoly buf2;
+                       div(a, buf, buf2);
+                       a = buf2;
+                       nhalf = degree(a)/2;
+                       rem(w, a, buf);
+                       w = buf;
+               }
+               ++i;
+       }
+       if ( unequal_one(a) ) {
+               degrees.push_back(degree(a));
+               ddfactors.push_back(a);
+       }
+}
+
+static void same_degree_factor(const umodpoly& a, upvec& upv)
+{
+       cl_modint_ring R = a[0].ring();
+       int deg = degree(a);
+
+       vector<int> degrees;
+       upvec ddfactors;
+       distinct_degree_factor(a, degrees, ddfactors);
+
+       for ( size_t i=0; i<degrees.size(); ++i ) {
+               if ( degrees[i] == degree(ddfactors[i]) ) {
+                       upv.push_back(ddfactors[i]);
+               }
+               else {
+                       berlekamp(ddfactors[i], upv);
+               }
+       }
+}
+
+static void factor_modular(const umodpoly& p, upvec& upv)
+{
+       upvec factors;
+       vector<int> mult;
+       modsqrfree(p, factors, mult);
+
+#define USE_SAME_DEGREE_FACTOR
+#ifdef USE_SAME_DEGREE_FACTOR
+       for ( size_t i=0; i<factors.size(); ++i ) {
+               upvec upvbuf;
+               same_degree_factor(factors[i], upvbuf);
+               for ( int j=mult[i]; j>0; --j ) {
+                       upv.insert(upv.end(), upvbuf.begin(), upvbuf.end());
+               }
+       }
+#else
+       for ( size_t i=0; i<factors.size(); ++i ) {
+               upvec upvbuf;
+               berlekamp(factors[i], upvbuf);
+               if ( upvbuf.size() ) {
+                       for ( size_t j=0; j<upvbuf.size(); ++j ) {
+                               upv.insert(upv.end(), mult[i], upvbuf[j]);
+                       }
+               }
+               else {
+                       for ( int j=mult[i]; j>0; --j ) {
+                               upv.push_back(factors[i]);
+                       }
+               }
+       }
+#endif
+}
+
+/** Calculates polynomials s and t such that a*s+b*t==1.
+ *  Assertion: a and b are relatively prime and not zero.
+ *
+ *  @param[in]  a  polynomial
+ *  @param[in]  b  polynomial
+ *  @param[out] s  polynomial
+ *  @param[out] t  polynomial
+ */
+static void exteuclid(const umodpoly& a, const umodpoly& b, umodpoly& s, umodpoly& t)
 {
-       if ( a.degree() < b.degree() ) {
-               exteuclid(b, a, g, t, s);
+       if ( degree(a) < degree(b) ) {
+               exteuclid(b, a, t, s);
                return;
        }
-       UniPoly c1(a.R), c2(a.R), d1(a.R), d2(a.R), q(a.R), r(a.R), r1(a.R), r2(a.R);
-       UniPoly c = a; c.unit_normal();
-       UniPoly d = b; d.unit_normal();
-       c1.set(0, a.R->one());
-       d2.set(0, a.R->one());
-       while ( !d.zero() ) {
-               q.terms.clear();
+
+       umodpoly one(1, a[0].ring()->one());
+       umodpoly c = a; normalize_in_field(c);
+       umodpoly d = b; normalize_in_field(d);
+       s = one;
+       t.clear();
+       umodpoly d1;
+       umodpoly d2 = one;
+       umodpoly q;
+       while ( true ) {
                div(c, d, q);
-               r = c - q * d;
-               r1 = c1 - q * d1;
-               r2 = c2 - q * d2;
+               umodpoly r = c - q * d;
+               umodpoly r1 = s - q * d1;
+               umodpoly r2 = t - q * d2;
                c = d;
-               c1 = d1;
-               c2 = d2;
+               s = d1;
+               t = d2;
+               if ( r.empty() ) break;
                d = r;
                d1 = r1;
                d2 = r2;
        }
-       g = c; g.unit_normal();
-       s = c1;
-       s.divide(a.unit());
-       s.divide(c.unit());
-       t = c2;
-       t.divide(b.unit());
-       t.divide(c.unit());
+       cl_MI fac = recip(lcoeff(a) * lcoeff(c));
+       umodpoly::iterator i = s.begin(), end = s.end();
+       for ( ; i!=end; ++i ) {
+               *i = *i * fac;
+       }
+       canonicalize(s);
+       fac = recip(lcoeff(b) * lcoeff(c));
+       i = t.begin(), end = t.end();
+       for ( ; i!=end; ++i ) {
+               *i = *i * fac;
+       }
+       canonicalize(t);
 }
 
-static ex replace_lc(const ex& poly, const ex& x, const ex& lc)
+static upoly replace_lc(const upoly& poly, const cl_I& lc)
 {
-       ex r = expand(poly + (lc - poly.lcoeff(x)) * pow(x, poly.degree(x)));
+       if ( poly.empty() ) return poly;
+       upoly r = poly;
+       r.back() = lc;
        return r;
 }
 
-static ex hensel_univar(const ex& a_, const ex& x, unsigned int p, const UniPoly& u1_, const UniPoly& w1_, const ex& gamma_ = 0)
+static void hensel_univar(const upoly& a_, unsigned int p, const umodpoly& u1_, const umodpoly& w1_, upoly& u, upoly& w)
 {
-       ex a = a_;
-       const cl_modint_ring& R = u1_.R;
+       upoly a = a_;
+       const cl_modint_ring& R = u1_[0].ring();
 
        // calc bound B
-       ex maxcoeff;
-       for ( int i=a.degree(x); i>=a.ldegree(x); --i ) {
-               maxcoeff += pow(abs(a.coeff(x, i)),2);
+       cl_R maxcoeff = 0;
+       for ( int i=degree(a); i>=0; --i ) {
+               maxcoeff = maxcoeff + square(abs(a[i]));
        }
-       cl_I normmc = ceiling1(the<cl_R>(cln::sqrt(ex_to<numeric>(maxcoeff).to_cl_N())));
-       unsigned int maxdegree = (u1_.degree() > w1_.degree()) ? u1_.degree() : w1_.degree();
-       unsigned int B = cl_I_to_uint(normmc * expt_pos(cl_I(2), maxdegree));
+       cl_I normmc = ceiling1(the<cl_R>(cln::sqrt(maxcoeff)));
+       cl_I maxdegree = (degree(u1_) > degree(w1_)) ? degree(u1_) : degree(w1_);
+       cl_I B = normmc * expt_pos(cl_I(2), maxdegree);
 
        // step 1
-       ex alpha = a.lcoeff(x);
-       ex gamma = gamma_;
-       if ( gamma == 0 ) {
-               gamma = alpha;
-       }
-       unsigned int gamma_ui = ex_to<numeric>(abs(gamma)).to_int();
-       a = a * gamma;
-       UniPoly nu1 = u1_;
-       nu1.unit_normal();
-       UniPoly nw1 = w1_;
-       nw1.unit_normal();
-       ex phi;
-       phi = expand(gamma * nu1.to_ex(x));
-       UniPoly u1(R, phi, x);
-       phi = expand(alpha * nw1.to_ex(x));
-       UniPoly w1(R, phi, x);
+       cl_I alpha = lcoeff(a);
+       a = a * alpha;
+       umodpoly nu1 = u1_;
+       normalize_in_field(nu1);
+       umodpoly nw1 = w1_;
+       normalize_in_field(nw1);
+       upoly phi;
+       phi = umodpoly_to_upoly(nu1) * alpha;
+       umodpoly u1;
+       umodpoly_from_upoly(u1, phi, R);
+       phi = umodpoly_to_upoly(nw1) * alpha;
+       umodpoly w1;
+       umodpoly_from_upoly(w1, phi, R);
 
        // step 2
-       UniPoly s(R), t(R), g(R);
-       exteuclid(u1, w1, g, s, t);
+       umodpoly s;
+       umodpoly t;
+       exteuclid(u1, w1, s, t);
 
        // step 3
-       ex u = replace_lc(u1.to_ex(x), x, gamma);
-       ex w = replace_lc(w1.to_ex(x), x, alpha);
-       ex e = expand(a - u * w);
-       unsigned int modulus = p;
+       u = replace_lc(umodpoly_to_upoly(u1), alpha);
+       w = replace_lc(umodpoly_to_upoly(w1), alpha);
+       upoly e = a - u * w;
+       cl_I modulus = p;
+       const cl_I maxmodulus = 2*B*abs(alpha);
 
        // step 4
-       while ( !e.is_zero() && modulus < 2*B*gamma_ui ) {
-               ex c = e / modulus;
-               phi = expand(s.to_ex(x)*c);
-               UniPoly sigmatilde(R, phi, x);
-               phi = expand(t.to_ex(x)*c);
-               UniPoly tautilde(R, phi, x);
-               UniPoly q(R), r(R);
-               div(sigmatilde, w1, q);
-               rem(sigmatilde, w1, r);
-               UniPoly sigma = r;
-               phi = expand(tautilde.to_ex(x) + q.to_ex(x) * u1.to_ex(x));
-               UniPoly tau(R, phi, x);
-               u = expand(u + tau.to_ex(x) * modulus);
-               w = expand(w + sigma.to_ex(x) * modulus);
-               e = expand(a - u * w);
+       while ( !e.empty() && modulus < maxmodulus ) {
+               // ad-hoc divisablity check
+               for ( size_t k=0; k<e.size(); ++k ) {
+                       if ( !zerop(mod(e[k], modulus)) ) {
+                               goto quickexit;
+                       }
+               }
+               upoly c = e / modulus;
+               phi = umodpoly_to_upoly(s) * c;
+               umodpoly sigmatilde;
+               umodpoly_from_upoly(sigmatilde, phi, R);
+               phi = umodpoly_to_upoly(t) * c;
+               umodpoly tautilde;
+               umodpoly_from_upoly(tautilde, phi, R);
+               umodpoly r, q;
+               remdiv(sigmatilde, w1, r, q);
+               umodpoly sigma = r;
+               phi = umodpoly_to_upoly(tautilde) + umodpoly_to_upoly(q) * umodpoly_to_upoly(u1);
+               umodpoly tau;
+               umodpoly_from_upoly(tau, phi, R);
+               u = u + umodpoly_to_upoly(tau) * modulus;
+               w = w + umodpoly_to_upoly(sigma) * modulus;
+               e = a - u * w;
                modulus = modulus * p;
        }
+quickexit: ;
 
        // step 5
-       if ( e.is_zero() ) {
-               ex delta = u.content(x);
-               u = u / delta;
-               w = w / gamma * delta;
-               return lst(u, w);
+       if ( e.empty() ) {
+               cl_I g = u[0];
+               for ( size_t i=1; i<u.size(); ++i ) {
+                       g = gcd(g, u[i]);
+                       if ( g == 1 ) break;
+               }
+               if ( g != 1 ) {
+                       u = u / g;
+                       w = w * g;
+               }
+               if ( alpha != 1 ) {
+                       w = w / alpha;
+               }
        }
        else {
-               return lst();
+               u.clear();
        }
 }
 
@@ -1140,27 +1223,24 @@ static unsigned int next_prime(unsigned int p)
        throw logic_error("next_prime: should not reach this point!");
 }
 
-class Partition
+class factor_partition
 {
 public:
-       Partition(size_t n_) : n(n_)
+       factor_partition(const upvec& factors_) : factors(factors_)
        {
+               n = factors.size();
                k.resize(n, 1);
                k[0] = 0;
                sum = n-1;
+               one.resize(1, factors.front()[0].ring()->one());
+               split();
        }
        int operator[](size_t i) const { return k[i]; }
        size_t size() const { return n; }
        size_t size_first() const { return n-sum; }
        size_t size_second() const { return sum; }
 #ifdef DEBUGFACTOR
-       void get() const
-       {
-               for ( size_t i=0; i<k.size(); ++i ) {
-                       cout << k[i] << " ";
-               }
-               cout << endl;
-       }
+       void get() const { DCOUTVAR(k); }
 #endif
        bool next()
        {
@@ -1168,65 +1248,92 @@ public:
                        if ( k[i] ) {
                                --k[i];
                                --sum;
-                               return sum > 0;
+                               if ( sum > 0 ) {
+                                       split();
+                                       return true;
+                               }
+                               else {
+                                       return false;
+                               }
                        }
                        ++k[i];
                        ++sum;
                }
                return false;
        }
+       void split()
+       {
+               left = one;
+               right = one;
+               for ( size_t i=0; i<n; ++i ) {
+                       if ( k[i] ) {
+                               right = right * factors[i];
+                       }
+                       else {
+                               left = left * factors[i];
+                       }
+               }
+       }
+public:
+       umodpoly left, right;
 private:
+       upvec factors;
+       umodpoly one;
        size_t n, sum;
        vector<int> k;
 };
 
-static void split(const UniPolyVec& factors, const Partition& part, UniPoly& a, UniPoly& b)
-{
-       a.set(0, a.R->one());
-       b.set(0, a.R->one());
-       for ( size_t i=0; i<part.size(); ++i ) {
-               if ( part[i] ) {
-                       b = b * factors[i];
-               }
-               else {
-                       a = a * factors[i];
-               }
-       }
-}
-
 struct ModFactors
 {
-       ex poly;
-       UniPolyVec factors;
+       upoly poly;
+       upvec factors;
 };
 
 static ex factor_univariate(const ex& poly, const ex& x)
 {
-       ex unit, cont, prim;
-       poly.unitcontprim(x, unit, cont, prim);
+       ex unit, cont, prim_ex;
+       poly.unitcontprim(x, unit, cont, prim_ex);
+       upoly prim;
+       upoly_from_ex(prim, prim_ex, x);
 
-       // determine proper prime
-       unsigned int p = 3;
-       cl_modint_ring R = find_modint_ring(p);
-       while ( true ) {
-               if ( irem(ex_to<numeric>(prim.lcoeff(x)), p) != 0 ) {
-                       UniPoly modpoly(R, prim, x);
-                       UniFactorVec sqrfree_ufv;
-                       squarefree(modpoly, sqrfree_ufv);
-                       if ( sqrfree_ufv.factors.size() == 1 && sqrfree_ufv.factors.front().exp == 1 ) break;
-               }
-               p = next_prime(p);
-               R = find_modint_ring(p);
-       }
-
-       // do modular factorization
-       UniPoly modpoly(R, prim, x);
-       UniPolyVec factors;
-       factor_modular(modpoly, factors);
-       if ( factors.size() <= 1 ) {
-               // irreducible for sure
-               return poly;
+       // determine proper prime and minimize number of modular factors
+       unsigned int p = 3, lastp = 3;
+       cl_modint_ring R;
+       unsigned int trials = 0;
+       unsigned int minfactors = 0;
+       cl_I lc = lcoeff(prim);
+       upvec factors;
+       while ( trials < 2 ) {
+               umodpoly modpoly;
+               while ( true ) {
+                       p = next_prime(p);
+                       if ( !zerop(rem(lc, p)) ) {
+                               R = find_modint_ring(p);
+                               umodpoly_from_upoly(modpoly, prim, R);
+                               if ( squarefree(modpoly) ) break;
+                       }
+               }
+
+               // do modular factorization
+               upvec trialfactors;
+               factor_modular(modpoly, trialfactors);
+               if ( trialfactors.size() <= 1 ) {
+                       // irreducible for sure
+                       return poly;
+               }
+
+               if ( minfactors == 0 || trialfactors.size() < minfactors ) {
+                       factors = trialfactors;
+                       minfactors = factors.size();
+                       lastp = p;
+                       trials = 1;
+               }
+               else {
+                       ++trials;
+               }
        }
+       p = lastp;
+       R = find_modint_ring(p);
 
        // lift all factor combinations
        stack<ModFactors> tocheck;
@@ -1234,24 +1341,22 @@ static ex factor_univariate(const ex& poly, const ex& x)
        mf.poly = prim;
        mf.factors = factors;
        tocheck.push(mf);
+       upoly f1, f2;
        ex result = 1;
        while ( tocheck.size() ) {
                const size_t n = tocheck.top().factors.size();
-               Partition part(n);
+               factor_partition part(tocheck.top().factors);
                while ( true ) {
-                       UniPoly a(R), b(R);
-                       split(tocheck.top().factors, part, a, b);
-
-                       ex answer = hensel_univar(tocheck.top().poly, x, p, a, b);
-                       if ( answer != lst() ) {
+                       hensel_univar(tocheck.top().poly, p, part.left, part.right, f1, f2);
+                       if ( !f1.empty() ) {
                                if ( part.size_first() == 1 ) {
                                        if ( part.size_second() == 1 ) {
-                                               result *= answer.op(0) * answer.op(1);
+                                               result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
                                                tocheck.pop();
                                                break;
                                        }
-                                       result *= answer.op(0);
-                                       tocheck.top().poly = answer.op(1);
+                                       result *= upoly_to_ex(f1, x);
+                                       tocheck.top().poly = f2;
                                        for ( size_t i=0; i<n; ++i ) {
                                                if ( part[i] == 0 ) {
                                                        tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
@@ -1262,12 +1367,12 @@ static ex factor_univariate(const ex& poly, const ex& x)
                                }
                                else if ( part.size_second() == 1 ) {
                                        if ( part.size_first() == 1 ) {
-                                               result *= answer.op(0) * answer.op(1);
+                                               result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
                                                tocheck.pop();
                                                break;
                                        }
-                                       result *= answer.op(1);
-                                       tocheck.top().poly = answer.op(0);
+                                       result *= upoly_to_ex(f2, x);
+                                       tocheck.top().poly = f1;
                                        for ( size_t i=0; i<n; ++i ) {
                                                if ( part[i] == 1 ) {
                                                        tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
@@ -1277,8 +1382,8 @@ static ex factor_univariate(const ex& poly, const ex& x)
                                        break;
                                }
                                else {
-                                       UniPolyVec newfactors1(part.size_first(), R), newfactors2(part.size_second(), R);
-                                       UniPolyVec::iterator i1 = newfactors1.begin(), i2 = newfactors2.begin();
+                                       upvec newfactors1(part.size_first()), newfactors2(part.size_second());
+                                       upvec::iterator i1 = newfactors1.begin(), i2 = newfactors2.begin();
                                        for ( size_t i=0; i<n; ++i ) {
                                                if ( part[i] ) {
                                                        *i2++ = tocheck.top().factors[i];
@@ -1288,17 +1393,17 @@ static ex factor_univariate(const ex& poly, const ex& x)
                                                }
                                        }
                                        tocheck.top().factors = newfactors1;
-                                       tocheck.top().poly = answer.op(0);
+                                       tocheck.top().poly = f1;
                                        ModFactors mf;
                                        mf.factors = newfactors2;
-                                       mf.poly = answer.op(1);
+                                       mf.poly = f2;
                                        tocheck.push(mf);
                                        break;
                                }
                        }
                        else {
                                if ( !part.next() ) {
-                                       result *= tocheck.top().poly;
+                                       result *= upoly_to_ex(tocheck.top().poly, x);
                                        tocheck.pop();
                                        break;
                                }
@@ -1309,18 +1414,6 @@ static ex factor_univariate(const ex& poly, const ex& x)
        return unit * cont * result;
 }
 
-struct FindSymbolsMap : public map_function {
-       exset syms;
-       ex operator()(const ex& e)
-       {
-               if ( is_a<symbol>(e) ) {
-                       syms.insert(e);
-                       return e;
-               }
-               return e.map(*this);
-       }
-};
-
 struct EvalPoint
 {
        ex x;
@@ -1330,149 +1423,118 @@ struct EvalPoint
 // forward declaration
 vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, const vector<EvalPoint>& I, unsigned int d, unsigned int p, unsigned int k);
 
-UniPolyVec multiterm_eea_lift(const UniPolyVec& a, const ex& x, unsigned int p, unsigned int k)
+upvec multiterm_eea_lift(const upvec& a, const ex& x, unsigned int p, unsigned int k)
 {
-       DCOUT(multiterm_eea_lift);
-       DCOUTVAR(a);
-       DCOUTVAR(p);
-       DCOUTVAR(k);
-
        const size_t r = a.size();
-       DCOUTVAR(r);
        cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
-       UniPoly fill(R);
-       UniPolyVec q(r-1, fill);
+       upvec q(r-1);
        q[r-2] = a[r-1];
        for ( size_t j=r-2; j>=1; --j ) {
                q[j-1] = a[j] * q[j];
        }
-       DCOUTVAR(q);
-       UniPoly beta(R);
-       beta.set(0, R->one());
-       UniPolyVec s;
+       umodpoly beta(1, R->one());
+       upvec s;
        for ( size_t j=1; j<r; ++j ) {
-               DCOUTVAR(j);
-               DCOUTVAR(beta);
                vector<ex> mdarg(2);
-               mdarg[0] = q[j-1].to_ex(x);
-               mdarg[1] = a[j-1].to_ex(x);
+               mdarg[0] = umodpoly_to_ex(q[j-1], x);
+               mdarg[1] = umodpoly_to_ex(a[j-1], x);
                vector<EvalPoint> empty;
-               vector<ex> exsigma = multivar_diophant(mdarg, x, beta.to_ex(x), empty, 0, p, k);
-               UniPoly sigma1(R, exsigma[0], x);
-               UniPoly sigma2(R, exsigma[1], x);
+               vector<ex> exsigma = multivar_diophant(mdarg, x, umodpoly_to_ex(beta, x), empty, 0, p, k);
+               umodpoly sigma1;
+               umodpoly_from_ex(sigma1, exsigma[0], x, R);
+               umodpoly sigma2;
+               umodpoly_from_ex(sigma2, exsigma[1], x, R);
                beta = sigma1;
                s.push_back(sigma2);
        }
        s.push_back(beta);
-
-       DCOUTVAR(s);
-       DCOUT(END multiterm_eea_lift);
        return s;
 }
 
-void eea_lift(const UniPoly& a, const UniPoly& b, const ex& x, unsigned int p, unsigned int k, UniPoly& s_, UniPoly& t_)
+/**
+ *  Assert: a not empty.
+ */
+void change_modulus(const cl_modint_ring& R, umodpoly& a)
 {
-       DCOUT(eea_lift);
-       DCOUTVAR(a);
-       DCOUTVAR(b);
-       DCOUTVAR(x);
-       DCOUTVAR(p);
-       DCOUTVAR(k);
+       if ( a.empty() ) return;
+       cl_modint_ring oldR = a[0].ring();
+       umodpoly::iterator i = a.begin(), end = a.end();
+       for ( ; i!=end; ++i ) {
+               *i = R->canonhom(oldR->retract(*i));
+       }
+       canonicalize(a);
+}
 
+void eea_lift(const umodpoly& a, const umodpoly& b, const ex& x, unsigned int p, unsigned int k, umodpoly& s_, umodpoly& t_)
+{
        cl_modint_ring R = find_modint_ring(p);
-       UniPoly amod(R, a);
-       UniPoly bmod(R, b);
-       DCOUTVAR(amod);
-       DCOUTVAR(bmod);
-
-       UniPoly smod(R), tmod(R), g(R);
-       exteuclid(amod, bmod, g, smod, tmod);
-       
-       DCOUTVAR(smod);
-       DCOUTVAR(tmod);
-       DCOUTVAR(g);
+       umodpoly amod = a;
+       change_modulus(R, amod);
+       umodpoly bmod = b;
+       change_modulus(R, bmod);
+
+       umodpoly smod;
+       umodpoly tmod;
+       exteuclid(amod, bmod, smod, tmod);
 
        cl_modint_ring Rpk = find_modint_ring(expt_pos(cl_I(p),k));
-       UniPoly s(Rpk, smod);
-       UniPoly t(Rpk, tmod);
-       DCOUTVAR(s);
-       DCOUTVAR(t);
+       umodpoly s = smod;
+       change_modulus(Rpk, s);
+       umodpoly t = tmod;
+       change_modulus(Rpk, t);
 
        cl_I modulus(p);
-
-       UniPoly one(Rpk);
-       one.set(0, Rpk->one());
+       umodpoly one(1, Rpk->one());
        for ( size_t j=1; j<k; ++j ) {
-               UniPoly e = one - a * s - b * t;
-               e.divide(modulus);
-               UniPoly c(R, e);
-               UniPoly sigmabar(R);
-               sigmabar = smod * c;
-               UniPoly taubar(R);
-               taubar = tmod * c;
-               UniPoly q(R);
-               div(sigmabar, bmod, q);
-               UniPoly sigma(R);
-               rem(sigmabar, bmod, sigma);
-               UniPoly tau(R);
-               tau = taubar + q * amod;
-               UniPoly sadd(Rpk, sigma);
+               umodpoly e = one - a * s - b * t;
+               reduce_coeff(e, modulus);
+               umodpoly c = e;
+               change_modulus(R, c);
+               umodpoly sigmabar = smod * c;
+               umodpoly taubar = tmod * c;
+               umodpoly sigma, q;
+               remdiv(sigmabar, bmod, sigma, q);
+               umodpoly tau = taubar + q * amod;
+               umodpoly sadd = sigma;
+               change_modulus(Rpk, sadd);
                cl_MI modmodulus(Rpk, modulus);
                s = s + sadd * modmodulus;
-               UniPoly tadd(Rpk, tau);
+               umodpoly tadd = tau;
+               change_modulus(Rpk, tadd);
                t = t + tadd * modmodulus;
                modulus = modulus * p;
        }
 
        s_ = s; t_ = t;
-
-       DCOUTVAR(s);
-       DCOUTVAR(t);
-       DCOUT2(check, a*s + b*t);
-       DCOUT(END eea_lift);
 }
 
-UniPolyVec univar_diophant(const UniPolyVec& a, const ex& x, unsigned int m, unsigned int p, unsigned int k)
+upvec univar_diophant(const upvec& a, const ex& x, unsigned int m, unsigned int p, unsigned int k)
 {
-       DCOUT(univar_diophant);
-       DCOUTVAR(a);
-       DCOUTVAR(x);
-       DCOUTVAR(m);
-       DCOUTVAR(p);
-       DCOUTVAR(k);
-
        cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
 
        const size_t r = a.size();
-       UniPolyVec result;
+       upvec result;
        if ( r > 2 ) {
-               UniPolyVec s = multiterm_eea_lift(a, x, p, k);
+               upvec s = multiterm_eea_lift(a, x, p, k);
                for ( size_t j=0; j<r; ++j ) {
-                       ex phi = expand(pow(x,m)*s[j].to_ex(x));
-                       UniPoly bmod(R, phi, x);
-                       UniPoly buf(R);
+                       umodpoly bmod = umodpoly_to_umodpoly(s[j], R, m);
+                       umodpoly buf;
                        rem(bmod, a[j], buf);
                        result.push_back(buf);
                }
        }
        else {
-               UniPoly s(R), t(R);
+               umodpoly s, t;
                eea_lift(a[1], a[0], x, p, k, s, t);
-               ex phi = expand(pow(x,m)*s.to_ex(x));
-               UniPoly bmod(R, phi, x);
-               UniPoly buf(R);
-               rem(bmod, a[0], buf);
+               umodpoly bmod = umodpoly_to_umodpoly(s, R, m);
+               umodpoly buf, q;
+               remdiv(bmod, a[0], buf, q);
                result.push_back(buf);
-               UniPoly q(R);
-               div(bmod, a[0], q);
-               phi = expand(pow(x,m)*t.to_ex(x));
-               UniPoly t1mod(R, phi, x);
+               umodpoly t1mod = umodpoly_to_umodpoly(t, R, m);
                buf = t1mod + q * a[1];
                result.push_back(buf);
        }
 
-       DCOUTVAR(result);
-       DCOUT(END univar_diophant);
        return result;
 }
 
@@ -1503,39 +1565,16 @@ struct make_modular_map : public map_function {
 static ex make_modular(const ex& e, const cl_modint_ring& R)
 {
        make_modular_map map(R);
-       return map(e);
+       return map(e.expand());
 }
 
 vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, const vector<EvalPoint>& I, unsigned int d, unsigned int p, unsigned int k)
 {
        vector<ex> a = a_;
 
-       DCOUT(multivar_diophant);
-#ifdef DEBUGFACTOR
-       cout << "a ";
-       for ( size_t i=0; i<a.size(); ++i ) {
-               cout << a[i] << " ";
-       }
-       cout << endl;
-#endif
-       DCOUTVAR(x);
-       DCOUTVAR(c);
-#ifdef DEBUGFACTOR
-       cout << "I ";
-       for ( size_t i=0; i<I.size(); ++i ) {
-               cout << I[i].x << "=" << I[i].evalpoint << " ";
-       }
-       cout << endl;
-#endif
-       DCOUTVAR(d);
-       DCOUTVAR(p);
-       DCOUTVAR(k);
-
        const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
        const size_t r = a.size();
        const size_t nu = I.size() + 1;
-       DCOUTVAR(r);
-       DCOUTVAR(nu);
 
        vector<ex> sigma;
        if ( nu > 1 ) {
@@ -1553,26 +1592,26 @@ vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, con
 
                vector<ex> anew = a;
                for ( size_t i=0; i<r; ++i ) {
-                       a[i] = a[i].subs(xnu == alphanu);
+                       anew[i] = anew[i].subs(xnu == alphanu);
                }
                ex cnew = c.subs(xnu == alphanu);
                vector<EvalPoint> Inew = I;
                Inew.pop_back();
-               vector<ex> sigma = multivar_diophant(anew, x, cnew, Inew, d, p, k);
+               sigma = multivar_diophant(anew, x, cnew, Inew, d, p, k);
 
                ex buf = c;
                for ( size_t i=0; i<r; ++i ) {
                        buf -= sigma[i] * b[i];
                }
-               ex e = buf;
-               e = make_modular(e, R);
+               ex e = make_modular(buf, R);
 
                ex monomial = 1;
                for ( size_t m=1; m<=d; ++m ) {
-                       while ( !e.is_zero() ) {
+                       while ( !e.is_zero() && e.has(xnu) ) {
                                monomial *= (xnu - alphanu);
                                monomial = expand(monomial);
                                ex cm = e.diff(ex_to<symbol>(xnu), m).subs(xnu==alphanu) / factorial(m);
+                               cm = make_modular(cm, R);
                                if ( !cm.is_zero() ) {
                                        vector<ex> delta_s = multivar_diophant(anew, x, cm, Inew, d, p, k);
                                        ex buf = e;
@@ -1581,16 +1620,16 @@ vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, con
                                                sigma[j] += delta_s[j];
                                                buf -= delta_s[j] * b[j];
                                        }
-                                       e = buf;
-                                       e = make_modular(e, R);
+                                       e = make_modular(buf, R);
                                }
                        }
                }
        }
        else {
-               UniPolyVec amod;
+               upvec amod;
                for ( size_t i=0; i<a.size(); ++i ) {
-                       UniPoly up(R, a[i], x);
+                       umodpoly up;
+                       umodpoly_from_ex(up, a[i], x, R);
                        amod.push_back(up);
                }
 
@@ -1605,74 +1644,48 @@ vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, con
                        nterms = 1;
                        z = c;
                }
-               DCOUTVAR(nterms);
                for ( size_t i=0; i<nterms; ++i ) {
-                       DCOUTVAR(z);
                        int m = z.degree(x);
-                       DCOUTVAR(m);
                        cl_I cm = the<cl_I>(ex_to<numeric>(z.lcoeff(x)).to_cl_N());
-                       DCOUTVAR(cm);
-                       UniPolyVec delta_s = univar_diophant(amod, x, m, p, k);
+                       upvec delta_s = univar_diophant(amod, x, m, p, k);
                        cl_MI modcm;
                        cl_I poscm = cm;
                        while ( poscm < 0 ) {
                                poscm = poscm + expt_pos(cl_I(p),k);
                        }
                        modcm = cl_MI(R, poscm);
-                       DCOUTVAR(modcm);
                        for ( size_t j=0; j<delta_s.size(); ++j ) {
                                delta_s[j] = delta_s[j] * modcm;
-                               sigma[j] = sigma[j] + delta_s[j].to_ex(x);
-                       }
-                       DCOUTVAR(delta_s);
-#ifdef DEBUGFACTOR
-                       cout << "STEP " << i << " sigma ";
-                       for ( size_t p=0; p<sigma.size(); ++p ) {
-                               cout << sigma[p] << " ";
+                               sigma[j] = sigma[j] + umodpoly_to_ex(delta_s[j], x);
                        }
-                       cout << endl;
-#endif
                        if ( nterms > 1 ) {
                                z = c.op(i+1);
                        }
                }
        }
-#ifdef DEBUGFACTOR
-       cout << "sigma ";
-       for ( size_t i=0; i<sigma.size(); ++i ) {
-               cout << sigma[i] << " ";
-       }
-       cout << endl;
-#endif
 
        for ( size_t i=0; i<sigma.size(); ++i ) {
                sigma[i] = make_modular(sigma[i], R);
        }
 
+       return sigma;
+}
+
 #ifdef DEBUGFACTOR
-       cout << "sigma ";
-       for ( size_t i=0; i<sigma.size(); ++i ) {
-               cout << sigma[i] << " ";
+ostream& operator<<(ostream& o, const vector<EvalPoint>& v)
+{
+       for ( size_t i=0; i<v.size(); ++i ) {
+               o << "(" << v[i].x << "==" << v[i].evalpoint << ") ";
        }
-       cout << endl;
-#endif
-       DCOUT(END multivar_diophant);
-       return sigma;
+       return o;
 }
+#endif // def DEBUGFACTOR
 
-ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigned int p, const cl_I& l, const UniPolyVec& u, const vector<ex>& lcU)
+ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigned int p, const cl_I& l, const upvec& u, const vector<ex>& lcU)
 {
-       DCOUT(hensel_multivar);
-       DCOUTVAR(a);
-       DCOUTVAR(x);
-       DCOUTVAR(p);
-       DCOUTVAR(l);
-       DCOUTVAR(u);
        const size_t nu = I.size() + 1;
        const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),l));
 
-       DCOUTVAR(nu);
-       
        vector<ex> A(nu);
        A[nu-1] = a;
 
@@ -1683,33 +1696,19 @@ ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigne
                A[j-2] = make_modular(A[j-2], R);
        }
 
-#ifdef DEBUGFACTOR
-       cout << "A ";
-       for ( size_t i=0; i<A.size(); ++i) cout << A[i] << " ";
-       cout << endl;
-#endif
-
        int maxdeg = a.degree(I.front().x);
        for ( size_t i=1; i<I.size(); ++i ) {
                int maxdeg2 = a.degree(I[i].x);
                if ( maxdeg2 > maxdeg ) maxdeg = maxdeg2;
        }
-       DCOUTVAR(maxdeg);
 
        const size_t n = u.size();
-       DCOUTVAR(n);
        vector<ex> U(n);
        for ( size_t i=0; i<n; ++i ) {
-               U[i] = u[i].to_ex(x);
+               U[i] = umodpoly_to_ex(u[i], x);
        }
-#ifdef DEBUGFACTOR
-       cout << "U ";
-       for ( size_t i=0; i<U.size(); ++i) cout << U[i] << " ";
-       cout << endl;
-#endif
 
        for ( size_t j=2; j<=nu; ++j ) {
-               DCOUTVAR(j);
                vector<ex> U1 = U;
                ex monomial = 1;
                for ( size_t m=0; m<n; ++m) {
@@ -1718,7 +1717,6 @@ ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigne
                                for ( size_t i=j-1; i<nu-1; ++i ) {
                                        coef = coef.subs(I[i].x == I[i].evalpoint);
                                }
-                               coef = expand(coef);
                                coef = make_modular(coef, R);
                                int deg = U[m].degree(x);
                                U[m] = U[m] - U[m].lcoeff(x) * pow(x,deg) + coef * pow(x,deg);
@@ -1729,31 +1727,24 @@ ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigne
                        Uprod *= U[i];
                }
                ex e = expand(A[j-1] - Uprod);
-               DCOUTVAR(e);
+
+               vector<EvalPoint> newI;
+               for ( size_t i=1; i<=j-2; ++i ) {
+                       newI.push_back(I[i-1]);
+               }
 
                ex xj = I[j-2].x;
                int alphaj = I[j-2].evalpoint;
                size_t deg = A[j-1].degree(xj);
-               DCOUTVAR(deg);
                for ( size_t k=1; k<=deg; ++k ) {
-                       DCOUTVAR(k);
                        if ( !e.is_zero() ) {
-                               DCOUTVAR(xj);
-                               DCOUTVAR(alphaj);
                                monomial *= (xj - alphaj);
                                monomial = expand(monomial);
-                               DCOUTVAR(monomial);
                                ex dif = e.diff(ex_to<symbol>(xj), k);
-                               DCOUTVAR(dif);
                                ex c = dif.subs(xj==alphaj) / factorial(k);
-                               DCOUTVAR(c);
                                if ( !c.is_zero() ) {
-                                       vector<EvalPoint> newI = I;
-                                       newI.pop_back();
                                        vector<ex> deltaU = multivar_diophant(U1, x, c, newI, maxdeg, p, cl_I_to_uint(l));
                                        for ( size_t i=0; i<n; ++i ) {
-                                               DCOUTVAR(i);
-                                               DCOUTVAR(deltaU[i]);
                                                deltaU[i] *= monomial;
                                                U[i] += deltaU[i];
                                                U[i] = make_modular(U[i], R);
@@ -1762,12 +1753,8 @@ ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigne
                                        for ( size_t i=0; i<n; ++i ) {
                                                Uprod *= U[i];
                                        }
-                                       e = expand(A[j-1] - Uprod);
+                                       e = A[j-1] - Uprod;
                                        e = make_modular(e, R);
-                                       DCOUTVAR(e);
-                               }
-                               else {
-                                       break;
                                }
                        }
                }
@@ -1777,7 +1764,6 @@ ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigne
        for ( size_t i=0; i<U.size(); ++i ) {
                acand *= U[i];
        }
-       DCOUTVAR(acand);
        if ( expand(a-acand).is_zero() ) {
                lst res;
                for ( size_t i=0; i<U.size(); ++i ) {
@@ -1786,26 +1772,444 @@ ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigne
                return res;
        }
        else {
+               lst res;
                return lst();
        }
 }
 
-static ex factor_multivariate(const ex& poly, const ex& x)
+static ex put_factors_into_lst(const ex& e)
+{
+       lst result;
+
+       if ( is_a<numeric>(e) ) {
+               result.append(e);
+               return result;
+       }
+       if ( is_a<power>(e) ) {
+               result.append(1);
+               result.append(e.op(0));
+               result.append(e.op(1));
+               return result;
+       }
+       if ( is_a<symbol>(e) || is_a<add>(e) ) {
+               result.append(1);
+               result.append(e);
+               result.append(1);
+               return result;
+       }
+       if ( is_a<mul>(e) ) {
+               ex nfac = 1;
+               for ( size_t i=0; i<e.nops(); ++i ) {
+                       ex op = e.op(i);
+                       if ( is_a<numeric>(op) ) {
+                               nfac = op;
+                       }
+                       if ( is_a<power>(op) ) {
+                               result.append(op.op(0));
+                               result.append(op.op(1));
+                       }
+                       if ( is_a<symbol>(op) || is_a<add>(op) ) {
+                               result.append(op);
+                               result.append(1);
+                       }
+               }
+               result.prepend(nfac);
+               return result;
+       }
+       throw runtime_error("put_factors_into_lst: bad term.");
+}
+
+#ifdef DEBUGFACTOR
+ostream& operator<<(ostream& o, const vector<numeric>& v)
+{
+       for ( size_t i=0; i<v.size(); ++i ) {
+               o << v[i] << " ";
+       }
+       return o;
+}
+#endif // def DEBUGFACTOR
+
+static bool checkdivisors(const lst& f, vector<numeric>& d)
+{
+       const int k = f.nops()-2;
+       numeric q, r;
+       d[0] = ex_to<numeric>(f.op(0) * f.op(f.nops()-1));
+       if ( d[0] == 1 && k == 1 && abs(f.op(1)) != 1 ) {
+               return false;
+       }
+       for ( int i=1; i<=k; ++i ) {
+               q = ex_to<numeric>(abs(f.op(i)));
+               for ( int j=i-1; j>=0; --j ) {
+                       r = d[j];
+                       do {
+                               r = gcd(r, q);
+                               q = q/r;
+                       } while ( r != 1 );
+                       if ( q == 1 ) {
+                               return true;
+                       }
+               }
+               d[i] = q;
+       }
+       return false;
+}
+
+static bool generate_set(const ex& u, const ex& vn, const exset& syms, const ex& f, const numeric& modulus, vector<numeric>& a, vector<numeric>& d)
+{
+       // computation of d is actually not necessary
+       const ex& x = *syms.begin();
+       bool trying = true;
+       do {
+               ex u0 = u;
+               ex vna = vn;
+               ex vnatry;
+               exset::const_iterator s = syms.begin();
+               ++s;
+               for ( size_t i=0; i<a.size(); ++i ) {
+                       do {
+                               a[i] = mod(numeric(rand()), 2*modulus) - modulus;
+                               vnatry = vna.subs(*s == a[i]);
+                       } while ( vnatry == 0 );
+                       vna = vnatry;
+                       u0 = u0.subs(*s == a[i]);
+                       ++s;
+               }
+               if ( gcd(u0,u0.diff(ex_to<symbol>(x))) != 1 ) {
+                       continue;
+               }
+               if ( is_a<numeric>(vn) ) {
+                       trying = false;
+               }
+               else {
+                       lst fnum;
+                       lst::const_iterator i = ex_to<lst>(f).begin();
+                       fnum.append(*i++);
+                       bool problem = false;
+                       while ( i!=ex_to<lst>(f).end() ) {
+                               ex fs = *i;
+                               if ( !is_a<numeric>(fs) ) {
+                                       s = syms.begin();
+                                       ++s;
+                                       for ( size_t j=0; j<a.size(); ++j ) {
+                                               fs = fs.subs(*s == a[j]);
+                                               ++s;
+                                       }
+                                       if ( abs(fs) == 1 ) {
+                                               problem = true;
+                                               break;
+                                       }
+                               }
+                               fnum.append(fs);
+                               ++i; ++i;
+                       }
+                       if ( problem ) {
+                               return true;
+                       }
+                       ex con = u0.content(x);
+                       fnum.append(con);
+                       trying = checkdivisors(fnum, d);
+               }
+       } while ( trying );
+       return false;
+}
+
+static ex factor_multivariate(const ex& poly, const exset& syms)
 {
-       // TODO
-       return 666;
+       exset::const_iterator s;
+       const ex& x = *syms.begin();
+
+       /* make polynomial primitive */
+       ex p = poly.expand().collect(x);
+       ex cont = p.lcoeff(x);
+       for ( numeric i=p.degree(x)-1; i>=p.ldegree(x); --i ) {
+               cont = gcd(cont, p.coeff(x,ex_to<numeric>(i).to_int()));
+               if ( cont == 1 ) break;
+       }
+       ex pp = expand(normal(p / cont));
+       if ( !is_a<numeric>(cont) ) {
+               return factor(cont) * factor(pp);
+       }
+
+       /* factor leading coefficient */
+       pp = pp.collect(x);
+       ex vn = pp.lcoeff(x);
+       pp = pp.expand();
+       ex vnlst;
+       if ( is_a<numeric>(vn) ) {
+               vnlst = lst(vn);
+       }
+       else {
+               ex vnfactors = factor(vn);
+               vnlst = put_factors_into_lst(vnfactors);
+       }
+
+       const numeric maxtrials = 3;
+       numeric modulus = (vnlst.nops()-1 > 3) ? vnlst.nops()-1 : 3;
+       numeric minimalr = -1;
+       vector<numeric> a(syms.size()-1, 0);
+       vector<numeric> d((vnlst.nops()-1)/2+1, 0);
+
+       while ( true ) {
+               numeric trialcount = 0;
+               ex u, delta;
+               unsigned int prime = 3;
+               size_t factor_count = 0;
+               ex ufac;
+               ex ufaclst;
+               while ( trialcount < maxtrials ) {
+                       bool problem = generate_set(pp, vn, syms, vnlst, modulus, a, d);
+                       if ( problem ) {
+                               ++modulus;
+                               continue;
+                       }
+                       u = pp;
+                       s = syms.begin();
+                       ++s;
+                       for ( size_t i=0; i<a.size(); ++i ) {
+                               u = u.subs(*s == a[i]);
+                               ++s;
+                       }
+                       delta = u.content(x);
+
+                       // determine proper prime
+                       prime = 3;
+                       cl_modint_ring R = find_modint_ring(prime);
+                       while ( true ) {
+                               if ( irem(ex_to<numeric>(u.lcoeff(x)), prime) != 0 ) {
+                                       umodpoly modpoly;
+                                       umodpoly_from_ex(modpoly, u, x, R);
+                                       if ( squarefree(modpoly) ) break;
+                               }
+                               prime = next_prime(prime);
+                               R = find_modint_ring(prime);
+                       }
+
+                       ufac = factor(u);
+                       ufaclst = put_factors_into_lst(ufac);
+                       factor_count = (ufaclst.nops()-1)/2;
+
+                       // veto factorization for which gcd(u_i, u_j) != 1 for all i,j
+                       upvec tryu;
+                       for ( size_t i=0; i<(ufaclst.nops()-1)/2; ++i ) {
+                               umodpoly newu;
+                               umodpoly_from_ex(newu, ufaclst.op(i*2+1), x, R);
+                               tryu.push_back(newu);
+                       }
+                       bool veto = false;
+                       for ( size_t i=0; i<tryu.size()-1; ++i ) {
+                               for ( size_t j=i+1; j<tryu.size(); ++j ) {
+                                       umodpoly tryg;
+                                       gcd(tryu[i], tryu[j], tryg);
+                                       if ( unequal_one(tryg) ) {
+                                               veto = true;
+                                               goto escape_quickly;
+                                       }
+                               }
+                       }
+                       escape_quickly: ;
+                       if ( veto ) {
+                               continue;
+                       }
+
+                       if ( factor_count <= 1 ) {
+                               return poly;
+                       }
+
+                       if ( minimalr < 0 ) {
+                               minimalr = factor_count;
+                       }
+                       else if ( minimalr == factor_count ) {
+                               ++trialcount;
+                               ++modulus;
+                       }
+                       else if ( minimalr > factor_count ) {
+                               minimalr = factor_count;
+                               trialcount = 0;
+                       }
+                       if ( minimalr <= 1 ) {
+                               return poly;
+                       }
+               }
+
+               vector<numeric> ftilde((vnlst.nops()-1)/2+1);
+               ftilde[0] = ex_to<numeric>(vnlst.op(0));
+               for ( size_t i=1; i<ftilde.size(); ++i ) {
+                       ex ft = vnlst.op((i-1)*2+1);
+                       s = syms.begin();
+                       ++s;
+                       for ( size_t j=0; j<a.size(); ++j ) {
+                               ft = ft.subs(*s == a[j]);
+                               ++s;
+                       }
+                       ftilde[i] = ex_to<numeric>(ft);
+               }
+
+               vector<bool> used_flag((vnlst.nops()-1)/2+1, false);
+               vector<ex> D(factor_count, 1);
+               for ( size_t i=0; i<=factor_count; ++i ) {
+                       numeric prefac;
+                       if ( i == 0 ) {
+                               prefac = ex_to<numeric>(ufaclst.op(0));
+                               ftilde[0] = ftilde[0] / prefac;
+                               vnlst.let_op(0) = vnlst.op(0) / prefac;
+                               continue;
+                       }
+                       else {
+                               prefac = ex_to<numeric>(ufaclst.op(2*(i-1)+1).lcoeff(x));
+                       }
+                       for ( size_t j=(vnlst.nops()-1)/2+1; j>0; --j ) {
+                               if ( abs(ftilde[j-1]) == 1 ) {
+                                       used_flag[j-1] = true;
+                                       continue;
+                               }
+                               numeric g = gcd(prefac, ftilde[j-1]);
+                               if ( g != 1 ) {
+                                       prefac = prefac / g;
+                                       numeric count = abs(iquo(g, ftilde[j-1]));
+                                       used_flag[j-1] = true;
+                                       if ( i > 0 ) {
+                                               if ( j == 1 ) {
+                                                       D[i-1] = D[i-1] * pow(vnlst.op(0), count);
+                                               }
+                                               else {
+                                                       D[i-1] = D[i-1] * pow(vnlst.op(2*(j-2)+1), count);
+                                               }
+                                       }
+                                       else {
+                                               ftilde[j-1] = ftilde[j-1] / prefac;
+                                               break;
+                                       }
+                                       ++j;
+                               }
+                       }
+               }
+
+               bool some_factor_unused = false;
+               for ( size_t i=0; i<used_flag.size(); ++i ) {
+                       if ( !used_flag[i] ) {
+                               some_factor_unused = true;
+                               break;
+                       }
+               }
+               if ( some_factor_unused ) {
+                       continue;
+               }
+
+               vector<ex> C(factor_count);
+               if ( delta == 1 ) {
+                       for ( size_t i=0; i<D.size(); ++i ) {
+                               ex Dtilde = D[i];
+                               s = syms.begin();
+                               ++s;
+                               for ( size_t j=0; j<a.size(); ++j ) {
+                                       Dtilde = Dtilde.subs(*s == a[j]);
+                                       ++s;
+                               }
+                               C[i] = D[i] * (ufaclst.op(2*i+1).lcoeff(x) / Dtilde);
+                       }
+               }
+               else {
+                       for ( size_t i=0; i<D.size(); ++i ) {
+                               ex Dtilde = D[i];
+                               s = syms.begin();
+                               ++s;
+                               for ( size_t j=0; j<a.size(); ++j ) {
+                                       Dtilde = Dtilde.subs(*s == a[j]);
+                                       ++s;
+                               }
+                               ex ui;
+                               if ( i == 0 ) {
+                                       ui = ufaclst.op(0);
+                               }
+                               else {
+                                       ui = ufaclst.op(2*(i-1)+1);
+                               }
+                               while ( true ) {
+                                       ex d = gcd(ui.lcoeff(x), Dtilde);
+                                       C[i] = D[i] * ( ui.lcoeff(x) / d );
+                                       ui = ui * ( Dtilde[i] / d );
+                                       delta = delta / ( Dtilde[i] / d );
+                                       if ( delta == 1 ) break;
+                                       ui = delta * ui;
+                                       C[i] = delta * C[i];
+                                       pp = pp * pow(delta, D.size()-1);
+                               }
+                       }
+               }
+
+               EvalPoint ep;
+               vector<EvalPoint> epv;
+               s = syms.begin();
+               ++s;
+               for ( size_t i=0; i<a.size(); ++i ) {
+                       ep.x = *s++;
+                       ep.evalpoint = a[i].to_int();
+                       epv.push_back(ep);
+               }
+
+               // calc bound B
+               ex maxcoeff;
+               for ( int i=u.degree(x); i>=u.ldegree(x); --i ) {
+                       maxcoeff += pow(abs(u.coeff(x, i)),2);
+               }
+               cl_I normmc = ceiling1(the<cl_R>(cln::sqrt(ex_to<numeric>(maxcoeff).to_cl_N())));
+               unsigned int maxdegree = 0;
+               for ( size_t i=0; i<factor_count; ++i ) {
+                       if ( ufaclst[2*i+1].degree(x) > (int)maxdegree ) {
+                               maxdegree = ufaclst[2*i+1].degree(x);
+                       }
+               }
+               cl_I B = normmc * expt_pos(cl_I(2), maxdegree);
+               cl_I l = 1;
+               cl_I pl = prime;
+               while ( pl < B ) {
+                       l = l + 1;
+                       pl = pl * prime;
+               }
+
+               upvec uvec;
+               cl_modint_ring R = find_modint_ring(expt_pos(cl_I(prime),l));
+               for ( size_t i=0; i<(ufaclst.nops()-1)/2; ++i ) {
+                       umodpoly newu;
+                       umodpoly_from_ex(newu, ufaclst.op(i*2+1), x, R);
+                       uvec.push_back(newu);
+               }
+
+               ex res = hensel_multivar(ufaclst.op(0)*pp, x, epv, prime, l, uvec, C);
+               if ( res != lst() ) {
+                       ex result = cont * ufaclst.op(0);
+                       for ( size_t i=0; i<res.nops(); ++i ) {
+                               result *= res.op(i).content(x) * res.op(i).unit(x);
+                               result *= res.op(i).primpart(x);
+                       }
+                       return result;
+               }
+       }
 }
 
+struct find_symbols_map : public map_function {
+       exset syms;
+       ex operator()(const ex& e)
+       {
+               if ( is_a<symbol>(e) ) {
+                       syms.insert(e);
+                       return e;
+               }
+               return e.map(*this);
+       }
+};
+
 static ex factor_sqrfree(const ex& poly)
 {
        // determine all symbols in poly
-       FindSymbolsMap findsymbols;
+       find_symbols_map findsymbols;
        findsymbols(poly);
        if ( findsymbols.syms.size() == 0 ) {
                return poly;
        }
 
        if ( findsymbols.syms.size() == 1 ) {
+               // univariate case
                const ex& x = *(findsymbols.syms.begin());
                if ( poly.ldegree(x) > 0 ) {
                        int ld = poly.ldegree(x);
@@ -1818,16 +2222,53 @@ static ex factor_sqrfree(const ex& poly)
                }
        }
 
-       // multivariate case not yet implemented!
-       throw runtime_error("multivariate case not yet implemented!");
+       // multivariate case
+       ex res = factor_multivariate(poly, findsymbols.syms);
+       return res;
 }
 
+struct apply_factor_map : public map_function {
+       unsigned options;
+       apply_factor_map(unsigned options_) : options(options_) { }
+       ex operator()(const ex& e)
+       {
+               if ( e.info(info_flags::polynomial) ) {
+                       return factor(e, options);
+               }
+               if ( is_a<add>(e) ) {
+                       ex s1, s2;
+                       for ( size_t i=0; i<e.nops(); ++i ) {
+                               if ( e.op(i).info(info_flags::polynomial) ) {
+                                       s1 += e.op(i);
+                               }
+                               else {
+                                       s2 += e.op(i);
+                               }
+                       }
+                       s1 = s1.eval();
+                       s2 = s2.eval();
+                       return factor(s1, options) + s2.map(*this);
+               }
+               return e.map(*this);
+       }
+};
+
 } // anonymous namespace
 
-ex factor(const ex& poly)
+ex factor(const ex& poly, unsigned options)
 {
+       // check arguments
+       if ( !poly.info(info_flags::polynomial) ) {
+               if ( options & factor_options::all ) {
+                       options &= ~factor_options::all;
+                       apply_factor_map factor_map(options);
+                       return factor_map(poly);
+               }
+               return poly;
+       }
+
        // determine all symbols in poly
-       FindSymbolsMap findsymbols;
+       find_symbols_map findsymbols;
        findsymbols(poly);
        if ( findsymbols.syms.size() == 0 ) {
                return poly;
@@ -1853,6 +2294,7 @@ ex factor(const ex& poly)
                return pow(f, sfpoly.op(1));
        }
        if ( is_a<mul>(sfpoly) ) {
+               // case: multiple factors
                ex res = 1;
                for ( size_t i=0; i<sfpoly.nops(); ++i ) {
                        const ex& t = sfpoly.op(i);
@@ -1885,3 +2327,7 @@ ex factor(const ex& poly)
 }
 
 } // namespace GiNaC
+
+#ifdef DEBUGFACTOR
+#include "test.h"
+#endif