source: git/libpolys/polys/monomials/ring.cc @ 172d852

spielwiese
Last change on this file since 172d852 was 172d852, checked in by Hans Schoenemann <hannes@…>, 5 years ago
Merge pull request #906 from rbehrends/prelim-thread-rewrite Singular changes for multi-threading support.
  • Property mode set to 100644
File size: 145.5 KB
Line 
1/****************************************
2*  Computer Algebra System SINGULAR     *
3****************************************/
4/*
5* ABSTRACT - the interpreter related ring operations
6*/
7
8/* includes */
9#include <cmath>
10
11#include "misc/auxiliary.h"
12#include "misc/mylimits.h"
13#include "misc/options.h"
14#include "misc/int64vec.h"
15
16#include "coeffs/numbers.h"
17#include "coeffs/coeffs.h"
18
19#include "polys/monomials/p_polys.h"
20#include "polys/simpleideals.h"
21#include "polys/monomials/ring.h"
22#include "polys/monomials/maps.h"
23#include "polys/prCopy.h"
24#include "polys/templates/p_Procs.h"
25
26#include "polys/matpol.h"
27
28#include "polys/monomials/ring.h"
29
30#ifdef HAVE_PLURAL
31#include "polys/nc/nc.h"
32#include "polys/nc/sca.h"
33#endif
34
35
36#include "ext_fields/algext.h"
37#include "ext_fields/transext.h"
38
39
40#define BITS_PER_LONG 8*SIZEOF_LONG
41
42typedef char *             char_ptr;
43VAR omBin sip_sring_bin = omGetSpecBin(sizeof(ip_sring));
44VAR omBin char_ptr_bin =  omGetSpecBin(sizeof(char_ptr));
45
46
47static const char * const ringorder_name[] =
48{
49  " ?", ///< ringorder_no = 0,
50  "a", ///< ringorder_a,
51  "A", ///< ringorder_a64,
52  "c", ///< ringorder_c,
53  "C", ///< ringorder_C,
54  "M", ///< ringorder_M,
55  "S", ///< ringorder_S,
56  "s", ///< ringorder_s,
57  "lp", ///< ringorder_lp,
58  "dp", ///< ringorder_dp,
59  "rp", ///< ringorder_rp,
60  "Dp", ///< ringorder_Dp,
61  "wp", ///< ringorder_wp,
62  "Wp", ///< ringorder_Wp,
63  "ls", ///< ringorder_ls,
64  "ds", ///< ringorder_ds,
65  "Ds", ///< ringorder_Ds,
66  "ws", ///< ringorder_ws,
67  "Ws", ///< ringorder_Ws,
68  "am",  ///< ringorder_am,
69  "L", ///< ringorder_L,
70  "aa", ///< ringorder_aa
71  "rs", ///< ringorder_rs,
72  "IS", ///<  ringorder_IS
73  " _" ///< ringorder_unspec
74};
75
76
77const char * rSimpleOrdStr(int ord)
78{
79  return ringorder_name[ord];
80}
81
82/// unconditionally deletes fields in r
83void rDelete(ring r);
84/// set r->VarL_Size, r->VarL_Offset, r->VarL_LowIndex
85static void rSetVarL(ring r);
86/// get r->divmask depending on bits per exponent
87static unsigned long rGetDivMask(int bits);
88/// right-adjust r->VarOffset
89static void rRightAdjustVarOffset(ring r);
90static void rOptimizeLDeg(ring r);
91
92/*0 implementation*/
93//BOOLEAN rField_is_R(ring r)
94//{
95//  if (r->cf->ch== -1)
96//  {
97//    if (r->float_len==(short)0) return TRUE;
98//  }
99//  return FALSE;
100//}
101
102ring rDefault(const coeffs cf, int N, char **n,int ord_size, rRingOrder_t *ord, int *block0, int *block1, int** wvhdl, unsigned long bitmask)
103{
104  assume( cf != NULL);
105  ring r=(ring) omAlloc0Bin(sip_sring_bin);
106  r->N     = N;
107  r->cf = cf;
108  /*rPar(r)  = 0; Alloc0 */
109  /*names*/
110  r->names = (char **) omAlloc0(N * sizeof(char *));
111  int i;
112  for(i=0;i<N;i++)
113  {
114    r->names[i]  = omStrDup(n[i]);
115  }
116  /*weights: entries for 2 blocks: NULL*/
117  if (wvhdl==NULL)
118    r->wvhdl = (int **)omAlloc0((ord_size+1) * sizeof(int *));
119  else
120    r->wvhdl=wvhdl;
121  r->order = ord;
122  r->block0 = block0;
123  r->block1 = block1;
124  r->bitmask = bitmask;
125
126  /* complete ring intializations */
127  rComplete(r);
128  return r;
129}
130ring rDefault(int ch, int N, char **n,int ord_size, rRingOrder_t *ord, int *block0, int *block1,int ** wvhdl)
131{
132  coeffs cf;
133  if (ch==0) cf=nInitChar(n_Q,NULL);
134  else       cf=nInitChar(n_Zp,(void*)(long)ch);
135  assume( cf != NULL);
136  return rDefault(cf,N,n,ord_size,ord,block0,block1,wvhdl);
137}
138ring rDefault(const coeffs cf, int N, char **n,  const rRingOrder_t o)
139{
140  assume( cf != NULL);
141  /*order: o=lp,0*/
142  rRingOrder_t *order = (rRingOrder_t *) omAlloc(2* sizeof(rRingOrder_t));
143  int *block0 = (int *)omAlloc0(2 * sizeof(int));
144  int *block1 = (int *)omAlloc0(2 * sizeof(int));
145  /* ringorder o=lp for the first block: var 1..N */
146  order[0]  = o;
147  block0[0] = 1;
148  block1[0] = N;
149  /* the last block: everything is 0 */
150  order[1]  = (rRingOrder_t)0;
151
152  return rDefault(cf,N,n,2,order,block0,block1);
153}
154
155ring rDefault(int ch, int N, char **n)
156{
157  coeffs cf;
158  if (ch==0) cf=nInitChar(n_Q,NULL);
159  else       cf=nInitChar(n_Zp,(void*)(long)ch);
160  assume( cf != NULL);
161  return rDefault(cf,N,n);
162}
163
164///////////////////////////////////////////////////////////////////////////
165//
166// rInit: define a new ring from sleftv's
167//
168//-> ipshell.cc
169
170/////////////////////////////
171// Auxillary functions
172//
173
174// check intvec, describing the ordering
175BOOLEAN rCheckIV(const intvec *iv)
176{
177  if ((iv->length()!=2)&&(iv->length()!=3))
178  {
179    WerrorS("weights only for orderings wp,ws,Wp,Ws,a,M");
180    return TRUE;
181  }
182  return FALSE;
183}
184
185int rTypeOfMatrixOrder(const intvec* order)
186{
187  int i=0,j,typ=1;
188  int sz = (int)sqrt((double)(order->length()-2));
189  if ((sz*sz)!=(order->length()-2))
190  {
191    WerrorS("Matrix order is not a square matrix");
192    typ=0;
193  }
194  while ((i<sz) && (typ==1))
195  {
196    j=0;
197    while ((j<sz) && ((*order)[j*sz+i+2]==0)) j++;
198    if (j>=sz)
199    {
200      typ = 0;
201      WerrorS("Matrix order not complete");
202    }
203    else if ((*order)[j*sz+i+2]<0)
204      typ = -1;
205    else
206      i++;
207  }
208  return typ;
209}
210
211
212int r_IsRingVar(const char *n, char**names,int N)
213{
214  if (names!=NULL)
215  {
216    for (int i=0; i<N; i++)
217    {
218      if (names[i]==NULL) return -1;
219      if (strcmp(n,names[i]) == 0) return (int)i;
220    }
221  }
222  return -1;
223}
224
225
226void   rWrite(ring r, BOOLEAN details)
227{
228  if ((r==NULL)||(r->order==NULL))
229    return; /*to avoid printing after errors....*/
230
231  assume(r != NULL);
232  const coeffs C = r->cf;
233  assume(C != NULL);
234
235  int nblocks=rBlocks(r);
236
237  // omCheckAddrSize(r,sizeof(ip_sring));
238  omCheckAddrSize(r->order,nblocks*sizeof(int));
239  omCheckAddrSize(r->block0,nblocks*sizeof(int));
240  omCheckAddrSize(r->block1,nblocks*sizeof(int));
241  omCheckAddrSize(r->wvhdl,nblocks*sizeof(int *));
242  omCheckAddrSize(r->names,r->N*sizeof(char *));
243
244  nblocks--;
245
246
247  PrintS("// coefficients: ");
248  if( nCoeff_is_algExt(C) )
249  {
250    // NOTE: the following (non-thread-safe!) UGLYNESS
251    // (changing naRing->ShortOut for a while) is due to Hans!
252    // Just think of other ring using the VERY SAME naRing and possible
253    // side-effects...
254    ring R = C->extRing;
255    const BOOLEAN bSaveShortOut = rShortOut(R); R->ShortOut = rShortOut(r) & rCanShortOut(R);
256
257    n_CoeffWrite(C, details); // for correct printing of minpoly... WHAT AN UGLYNESS!!!
258
259    R->ShortOut = bSaveShortOut;
260  }
261  else
262    n_CoeffWrite(C, details);
263  PrintLn();
264//   {
265//     PrintS("//   characteristic : ");
266//
267//     char const * const * const params = rParameter(r);
268//
269//     if (params!=NULL)
270//     {
271//       Print ("//   %d parameter    : ",rPar(r));
272//
273//       char const * const * sp= params;
274//       int nop=0;
275//       while (nop<rPar(r))
276//       {
277//         PrintS(*sp);
278//         PrintS(" ");
279//         sp++; nop++;
280//       }
281//       PrintS("\n//   minpoly        : ");
282//       if ( rField_is_long_C(r) )
283//       {
284//         // i^2+1:
285//         Print("(%s^2+1)\n", params[0]);
286//       }
287//       else if (rMinpolyIsNULL(r))
288//       {
289//         PrintS("0\n");
290//       }
291//       else
292//       {
293//         StringSetS(""); n_Write(r->cf->minpoly, r); PrintS(StringEndS("\n")); // NOTE/TODO: use StringAppendS("\n"); omFree(s);
294//       }
295//       //if (r->qideal!=NULL)
296//       //{
297//       //  iiWriteMatrix((matrix)r->qideal,"//   minpolys",1,r,0);
298//       //  PrintLn();
299//       //}
300//     }
301//   }
302  Print("// number of vars : %d",r->N);
303
304  //for (nblocks=0; r->order[nblocks]; nblocks++);
305  nblocks=rBlocks(r)-1;
306
307  for (int l=0, nlen=0 ; l<nblocks; l++)
308  {
309    int i;
310    Print("\n//        block %3d : ",l+1);
311
312    Print("ordering %s", rSimpleOrdStr(r->order[l]));
313
314
315    if (r->order[l] == ringorder_IS)
316    {
317      assume( r->block0[l] == r->block1[l] );
318      const int s = r->block0[l];
319      assume( (-2 < s) && (s < 2) );
320      Print("(%d)", s); // 0 => prefix! +/-1 => suffix!
321      continue;
322    }
323    else if (r->order[l]==ringorder_s)
324    {
325      assume( l == 0 );
326      Print(" syz_comp: %d",r->block0[l]);
327      continue;
328    }
329    else if (
330    (  (r->order[l] >= ringorder_lp)
331    ||(r->order[l] == ringorder_M)
332    ||(r->order[l] == ringorder_a)
333    ||(r->order[l] == ringorder_am)
334    ||(r->order[l] == ringorder_a64)
335    ||(r->order[l] == ringorder_aa) ) && (r->order[l] < ringorder_IS) )
336    {
337      PrintS("\n//                  : names   ");
338      for (i = r->block0[l]-1; i<r->block1[l]; i++)
339      {
340        nlen = strlen(r->names[i]);
341        Print(" %s",r->names[i]);
342      }
343    }
344
345    if (r->wvhdl[l]!=NULL)
346    {
347      #ifndef SING_NDEBUG
348      if((r->order[l] != ringorder_wp)
349      &&(r->order[l] != ringorder_Wp)
350      &&(r->order[l] != ringorder_ws)
351      &&(r->order[l] != ringorder_Ws)
352      &&(r->order[l] != ringorder_a)
353      &&(r->order[l] != ringorder_am)
354      &&(r->order[l] != ringorder_M))
355      {
356        Warn("should not have wvhdl entry at pos. %d",l);
357      }
358      #endif
359      for (int j= 0;
360           j<(r->block1[l]-r->block0[l]+1)*(r->block1[l]-r->block0[l]+1);
361           j+=i)
362      {
363        PrintS("\n//                  : weights ");
364        for (i = 0; i<=r->block1[l]-r->block0[l]; i++)
365        {
366          if (r->order[l] == ringorder_a64)
367          {
368            int64 *w=(int64 *)r->wvhdl[l];
369            #if SIZEOF_LONG == 4
370            Print("%*lld " ,nlen,w[i+j]);
371            #else
372            Print(" %*ld"  ,nlen,w[i+j]);
373            #endif
374          }
375          else
376            Print(" %*d" ,nlen,r->wvhdl[l][i+j]);
377        }
378        if (r->order[l]!=ringorder_M) break;
379      }
380      if (r->order[l]==ringorder_am)
381      {
382        int m=r->wvhdl[l][i];
383        Print("\n//                  : %d module weights ",m);
384        m+=i;i++;
385        for(;i<=m;i++) Print(" %*d" ,nlen,r->wvhdl[l][i]);
386      }
387    }
388  }
389#ifdef HAVE_PLURAL
390  if(rIsPluralRing(r))
391  {
392    PrintS("\n// noncommutative relations:");
393    if( details )
394    {
395      poly pl=NULL;
396      int nl;
397      int i,j;
398      for (i = 1; i<r->N; i++)
399      {
400        for (j = i+1; j<=r->N; j++)
401        {
402          nl = n_IsOne(p_GetCoeff(MATELEM(r->GetNC()->C,i,j),r), r->cf);
403          if ( (MATELEM(r->GetNC()->D,i,j)!=NULL) || (!nl) )
404          {
405            Print("\n//    %s%s=",r->names[j-1],r->names[i-1]);
406            pl = MATELEM(r->GetNC()->MT[UPMATELEM(i,j,r->N)],1,1);
407            p_Write0(pl, r, r);
408          }
409        }
410      }
411    } else
412      PrintS(" ...");
413
414#if MYTEST  /*Singularg should not differ from Singular except in error case*/
415    Print("\n// noncommutative type:%d", (int)ncRingType(r));
416    Print("\n//    is skew constant:%d",r->GetNC()->IsSkewConstant);
417    if( rIsSCA(r) )
418    {
419      Print("\n//   alternating variables: [%d, %d]", scaFirstAltVar(r), scaLastAltVar(r));
420      const ideal Q = SCAQuotient(r); // resides within r!
421      PrintS("\n//   quotient of sca by ideal");
422
423      if (Q!=NULL)
424      {
425          iiWriteMatrix((matrix)Q,"scaQ",1,r,0);
426      }
427      else
428        PrintS(" (NULL)");
429    }
430#endif
431  }
432  if (rIsLPRing(r))
433  {
434    Print("\n// letterplace ring (block size %d)",r->isLPring);
435  }
436#endif
437  if (r->qideal!=NULL)
438  {
439    PrintS("\n// quotient ring from ideal");
440    if( details )
441    {
442      PrintLn();
443      iiWriteMatrix((matrix)r->qideal,"_",1,r,0);
444    } else PrintS(" ...");
445  }
446}
447
448void rDelete(ring r)
449{
450  int i, j;
451
452  if (r == NULL) return;
453
454  assume( r->ref <= 0 );
455
456  if( r->ref > 0 ) // ->ref means the number of Interpreter objects referring to the ring...
457    return;       // this should never happen.
458
459  if( r->qideal != NULL )
460  {
461    ideal q = r->qideal;
462    r->qideal = NULL;
463    id_Delete(&q, r);
464  }
465
466#ifdef HAVE_PLURAL
467  if (rIsPluralRing(r))
468    nc_rKill(r);
469#endif
470
471  rUnComplete(r); // may need r->cf for p_Delete
472  nKillChar(r->cf); r->cf = NULL;
473  // delete order stuff
474  if (r->order != NULL)
475  {
476    i=rBlocks(r);
477    assume(r->block0 != NULL && r->block1 != NULL && r->wvhdl != NULL);
478    // delete order
479    omFreeSize((ADDRESS)r->order,i*sizeof(rRingOrder_t));
480    omFreeSize((ADDRESS)r->block0,i*sizeof(int));
481    omFreeSize((ADDRESS)r->block1,i*sizeof(int));
482    // delete weights
483    for (j=0; j<i; j++)
484    {
485      if (r->wvhdl[j]!=NULL)
486        omFree(r->wvhdl[j]);
487    }
488    omFreeSize((ADDRESS)r->wvhdl,i*sizeof(int *));
489  }
490  else
491  {
492    assume(r->block0 == NULL && r->block1 == NULL && r->wvhdl == NULL);
493  }
494
495  // delete varnames
496  if(r->names!=NULL)
497  {
498    for (i=0; i<r->N; i++)
499    {
500      if (r->names[i] != NULL) omFree((ADDRESS)r->names[i]);
501    }
502    omFreeSize((ADDRESS)r->names,r->N*sizeof(char *));
503  }
504
505  omFreeBin(r, sip_sring_bin);
506}
507
508rRingOrder_t rOrderName(char * ordername)
509{
510  int order=ringorder_unspec;
511  while (order!= 0)
512  {
513    if (strcmp(ordername,rSimpleOrdStr(order))==0)
514      break;
515    order--;
516  }
517  if (order==0) Werror("wrong ring order `%s`",ordername);
518  omFree((ADDRESS)ordername);
519  return (rRingOrder_t)order;
520}
521
522char * rOrdStr(ring r)
523{
524  if ((r==NULL)||(r->order==NULL)) return omStrDup("");
525  int nblocks,l,i;
526
527  for (nblocks=0; r->order[nblocks]; nblocks++);
528  nblocks--;
529
530  StringSetS("");
531  for (l=0; ; l++)
532  {
533    StringAppendS((char *)rSimpleOrdStr(r->order[l]));
534    if (r->order[l] == ringorder_s)
535    {
536      StringAppend("(%d)",r->block0[l]);
537    }
538    else if (
539           (r->order[l] != ringorder_c)
540        && (r->order[l] != ringorder_C)
541        && (r->order[l] != ringorder_s)
542        && (r->order[l] != ringorder_S)
543        && (r->order[l] != ringorder_IS)
544       )
545    {
546      if (r->wvhdl[l]!=NULL)
547      {
548        #ifndef SING_NDEBUG
549        if((r->order[l] != ringorder_wp)
550        &&(r->order[l] != ringorder_Wp)
551        &&(r->order[l] != ringorder_ws)
552        &&(r->order[l] != ringorder_Ws)
553        &&(r->order[l] != ringorder_a)
554        &&(r->order[l] != ringorder_am)
555        &&(r->order[l] != ringorder_M))
556        {
557          Warn("should not have wvhdl entry at pos. %d",l);
558          StringAppend("(%d)",r->block1[l]-r->block0[l]+1);
559        }
560        else
561        #endif
562        {
563          StringAppendS("(");
564          for (int j= 0;
565               j<(r->block1[l]-r->block0[l]+1)*(r->block1[l]-r->block0[l]+1);
566               j+=i+1)
567          {
568            char c=',';
569            if(r->order[l]==ringorder_a64)
570            {
571              int64 * w=(int64 *)r->wvhdl[l];
572              for (i = 0; i<r->block1[l]-r->block0[l]; i++)
573              {
574                StringAppend("%lld," ,w[i]);
575              }
576              StringAppend("%lld)" ,w[i]);
577              break;
578            }
579            else
580            {
581              for (i = 0; i<r->block1[l]-r->block0[l]; i++)
582              {
583                StringAppend("%d," ,r->wvhdl[l][i+j]);
584              }
585            }
586            if (r->order[l]!=ringorder_M)
587            {
588              StringAppend("%d)" ,r->wvhdl[l][i+j]);
589              break;
590            }
591            if (j+i+1==(r->block1[l]-r->block0[l]+1)*(r->block1[l]-r->block0[l]+1))
592              c=')';
593            StringAppend("%d%c" ,r->wvhdl[l][i+j],c);
594          }
595        }
596      }
597      else
598        StringAppend("(%d)",r->block1[l]-r->block0[l]+1);
599    }
600    else if (r->order[l] == ringorder_IS)
601    {
602      assume( r->block0[l] == r->block1[l] );
603      const int s = r->block0[l];
604      assume( (-2 < s) && (s < 2) );
605
606      StringAppend("(%d)", s);
607    }
608
609    if (l==nblocks)
610    {
611      if (r->bitmask!=0xffff)
612      {
613        long mm=r->bitmask;
614        if (mm>MAX_INT_VAL) mm=MAX_INT_VAL;
615        StringAppend(",L(%ld)",mm);
616      }
617      return StringEndS();
618    }
619    StringAppendS(",");
620  }
621}
622
623char * rVarStr(ring r)
624{
625  if ((r==NULL)||(r->names==NULL)) return omStrDup("");
626  int i;
627  int l=2;
628  char *s;
629
630  for (i=0; i<r->N; i++)
631  {
632    l+=strlen(r->names[i])+1;
633  }
634  s=(char *)omAlloc((long)l);
635  s[0]='\0';
636  for (i=0; i<r->N-1; i++)
637  {
638    strcat(s,r->names[i]);
639    strcat(s,",");
640  }
641  strcat(s,r->names[i]);
642  return s;
643}
644
645/// TODO: make it a virtual method of coeffs, together with:
646/// Decompose & Compose, rParameter & rPar
647char * rCharStr(const ring r){ assume( r != NULL ); return nCoeffString(r->cf); }
648
649char * rParStr(ring r)
650{
651  if ((r==NULL)||(rParameter(r)==NULL)) return omStrDup("");
652
653  char const * const * const params = rParameter(r);
654
655  int i;
656  int l=2;
657
658  for (i=0; i<rPar(r); i++)
659  {
660    l+=strlen(params[i])+1;
661  }
662  char *s=(char *)omAlloc((long)l);
663  s[0]='\0';
664  for (i=0; i<rPar(r)-1; i++)
665  {
666    strcat(s, params[i]);
667    strcat(s,",");
668  }
669  strcat(s, params[i]);
670  return s;
671}
672
673char * rString(ring r)
674{
675  if ((r!=NULL)&&(r->cf!=NULL))
676  {
677    char *ch=rCharStr(r);
678    char *var=rVarStr(r);
679    char *ord=rOrdStr(r);
680    char *res=(char *)omAlloc(strlen(ch)+strlen(var)+strlen(ord)+9);
681    sprintf(res,"(%s),(%s),(%s)",ch,var,ord);
682    omFree((ADDRESS)ch);
683    omFree((ADDRESS)var);
684    omFree((ADDRESS)ord);
685    return res;
686  }
687  else
688    return omStrDup("undefined");
689}
690
691
692/*
693// The fowolling function seems to be never used. Remove?
694static int binaryPower (const int a, const int b)
695{
696  // computes a^b according to the binary representation of b,
697  //   i.e., a^7 = a^4 * a^2 * a^1. This saves some multiplications.
698  int result = 1;
699  int factor = a;
700  int bb = b;
701  while (bb != 0)
702  {
703    if (bb % 2 != 0) result = result * factor;
704    bb = bb / 2;
705    factor = factor * factor;
706  }
707  return result;
708}
709*/
710
711/* we keep this otherwise superfluous method for compatibility reasons
712   towards the SINGULAR svn trunk */
713int rChar(ring r) { return r->cf->ch; }
714
715
716
717// creates a commutative nc extension; "converts" comm.ring to a Plural ring
718#ifdef HAVE_PLURAL
719ring nc_rCreateNCcomm_rCopy(ring r)
720{
721  r = rCopy(r);
722  if (rIsPluralRing(r))
723    return r;
724
725  matrix C = mpNew(r->N,r->N); // ring-independent!?!
726  matrix D = mpNew(r->N,r->N);
727
728  for(int i=1; i<r->N; i++)
729    for(int j=i+1; j<=r->N; j++)
730      MATELEM(C,i,j) = p_One( r);
731
732  if (nc_CallPlural(C, D, NULL, NULL, r, false, true, false, r/*??currRing??*/, TRUE)) // TODO: what about quotient ideal?
733    WarnS("Error initializing multiplication!"); // No reaction!???
734
735  return r;
736}
737#endif
738
739
740/*2
741 *returns -1 for not compatible, (sum is undefined)
742 *         1 for compatible (and sum)
743 */
744/* vartest: test for variable/paramter names
745* dp_dp: 0:block ordering
746*        1:for comm. rings: use block order dp + dp/ds/wp
747*        2:order aa(..),dp
748*/
749int rSumInternal(ring r1, ring r2, ring &sum, BOOLEAN vartest, BOOLEAN dp_dp)
750{
751
752  ip_sring tmpR;
753  memset(&tmpR,0,sizeof(tmpR));
754  /* check coeff. field =====================================================*/
755
756  if (r1->cf==r2->cf)
757  {
758    tmpR.cf=nCopyCoeff(r1->cf);
759  }
760  else /* different type */
761  {
762    if (getCoeffType(r1->cf)==n_Zp)
763    {
764      if (getCoeffType(r2->cf)==n_Q)
765      {
766        tmpR.cf=nCopyCoeff(r1->cf);
767      }
768      else if (nCoeff_is_Extension(r2->cf) && rChar(r2) == rChar(r1))
769      {
770        /*AlgExtInfo extParam;
771        extParam.r = r2->cf->extRing;
772        extParam.i = r2->cf->extRing->qideal;*/
773        tmpR.cf=nCopyCoeff(r2->cf);
774      }
775      else
776      {
777        WerrorS("Z/p+...");
778        return -1;
779      }
780    }
781    else if ((getCoeffType(r1->cf)==n_Zn)||(getCoeffType(r1->cf)==n_Znm))
782    {
783      if (getCoeffType(r2->cf)==n_Q)
784      {
785        tmpR.cf=nCopyCoeff(r1->cf);
786      }
787      else if (nCoeff_is_Extension(r2->cf)
788      && (mpz_cmp(r1->cf->modNumber,r2->cf->extRing->cf->modNumber)==0))
789      { // covers transext.cc and algext.cc
790        tmpR.cf=nCopyCoeff(r2->cf);
791      }
792      else
793      {
794        WerrorS("Z/n+...");
795        return -1;
796      }
797    }
798    else if (getCoeffType(r1->cf)==n_R)
799    {
800      WerrorS("R+..");
801      return -1;
802    }
803    else if (getCoeffType(r1->cf)==n_Q)
804    {
805      if (getCoeffType(r2->cf)==n_Zp)
806      {
807        tmpR.cf=nCopyCoeff(r2->cf);
808      }
809      else if (nCoeff_is_Extension(r2->cf))
810      {
811        tmpR.cf=nCopyCoeff(r2->cf);
812      }
813      else
814      {
815        WerrorS("Q+...");
816        return -1;
817      }
818    }
819    else if (nCoeff_is_Extension(r1->cf))
820    {
821      if (r1->cf->extRing->cf==r2->cf)
822      {
823        tmpR.cf=nCopyCoeff(r1->cf);
824      }
825      else if (getCoeffType(r1->cf->extRing->cf)==n_Zp && getCoeffType(r2->cf)==n_Q) //r2->cf == n_Zp should have been handled above
826      {
827        tmpR.cf=nCopyCoeff(r1->cf);
828      }
829      else
830      {
831        WerrorS ("coeff sum of two extension fields not implemented");
832        return -1;
833      }
834    }
835    else
836    {
837      WerrorS("coeff sum not yet implemented");
838      return -1;
839    }
840  }
841  /* variable names ========================================================*/
842  int i,j,k;
843  int l=r1->N+r2->N;
844  char **names=(char **)omAlloc0(l*sizeof(char *));
845  k=0;
846
847  // collect all varnames from r1, except those which are parameters
848  // of r2, or those which are the empty string
849  for (i=0;i<r1->N;i++)
850  {
851    BOOLEAN b=TRUE;
852
853    if (*(r1->names[i]) == '\0')
854      b = FALSE;
855    else if ((rParameter(r2)!=NULL) && (strlen(r1->names[i])==1))
856    {
857      if (vartest)
858      {
859        for(j=0;j<rPar(r2);j++)
860        {
861          if (strcmp(r1->names[i],rParameter(r2)[j])==0)
862          {
863            b=FALSE;
864            break;
865          }
866        }
867      }
868    }
869
870    if (b)
871    {
872      //Print("name : %d: %s\n",k,r1->names[i]);
873      names[k]=omStrDup(r1->names[i]);
874      k++;
875    }
876    //else
877    //  Print("no name (par1) %s\n",r1->names[i]);
878  }
879  // Add variables from r2, except those which are parameters of r1
880  // those which are empty strings, and those which equal a var of r1
881  for(i=0;i<r2->N;i++)
882  {
883    BOOLEAN b=TRUE;
884
885    if (*(r2->names[i]) == '\0')
886      b = FALSE;
887    else if ((rParameter(r1)!=NULL) && (strlen(r2->names[i])==1))
888    {
889      if (vartest)
890      {
891        for(j=0;j<rPar(r1);j++)
892        {
893          if (strcmp(r2->names[i],rParameter(r1)[j])==0)
894          {
895            b=FALSE;
896            break;
897          }
898        }
899      }
900    }
901
902    if (b)
903    {
904      if (vartest)
905      {
906        for(j=0;j<r1->N;j++)
907        {
908          if (strcmp(r1->names[j],r2->names[i])==0)
909          {
910            b=FALSE;
911            break;
912          }
913        }
914      }
915      if (b)
916      {
917        //Print("name : %d : %s\n",k,r2->names[i]);
918        names[k]=omStrDup(r2->names[i]);
919        k++;
920      }
921      //else
922      //  Print("no name (var): %s\n",r2->names[i]);
923    }
924    //else
925    //  Print("no name (par): %s\n",r2->names[i]);
926  }
927  // check whether we found any vars at all
928  if (k == 0)
929  {
930    names[k]=omStrDup("");
931    k=1;
932  }
933  tmpR.N=k;
934  tmpR.names=names;
935  /* ordering *======================================================== */
936  tmpR.OrdSgn=0;
937  if ((dp_dp==2)
938  && (r1->OrdSgn==1)
939  && (r2->OrdSgn==1)
940#ifdef HAVE_PLURAL
941      && !rIsPluralRing(r1) && !rIsPluralRing(r2)
942#endif
943     )
944  {
945    tmpR.order=(rRingOrder_t*)omAlloc0(4*sizeof(rRingOrder_t));
946    tmpR.block0=(int*)omAlloc0(4*sizeof(int));
947    tmpR.block1=(int*)omAlloc0(4*sizeof(int));
948    tmpR.wvhdl=(int**) omAlloc0(4*sizeof(int**));
949    // ----
950    tmpR.block0[0] = 1;
951    tmpR.block1[0] = rVar(r1)+rVar(r2);
952    tmpR.order[0] = ringorder_aa;
953    tmpR.wvhdl[0]=(int*)omAlloc0((rVar(r1)+rVar(r2) + 1)*sizeof(int));
954    for(int i=0;i<rVar(r1);i++) tmpR.wvhdl[0][i]=1;
955    // ----
956    tmpR.block0[1] = 1;
957    tmpR.block1[1] = rVar(r1)+rVar(r2);
958    tmpR.order[1] = ringorder_dp;
959    // ----
960    tmpR.order[2] = ringorder_C;
961  }
962  else if (dp_dp
963#ifdef HAVE_PLURAL
964      && !rIsPluralRing(r1) && !rIsPluralRing(r2)
965#endif
966     )
967  {
968    tmpR.order=(rRingOrder_t*)omAlloc(4*sizeof(rRingOrder_t));
969    tmpR.block0=(int*)omAlloc0(4*sizeof(int));
970    tmpR.block1=(int*)omAlloc0(4*sizeof(int));
971    tmpR.wvhdl=(int**)omAlloc0(4*sizeof(int *));
972    tmpR.order[0]=ringorder_dp;
973    tmpR.block0[0]=1;
974    tmpR.block1[0]=rVar(r1);
975    if (r2->OrdSgn==1)
976    {
977      if ((r2->block0[0]==1)
978      && (r2->block1[0]==rVar(r2))
979      && ((r2->order[0]==ringorder_wp)
980        || (r2->order[0]==ringorder_Wp)
981        || (r2->order[0]==ringorder_Dp))
982      )
983      {
984        tmpR.order[1]=r2->order[0];
985        if (r2->wvhdl[0]!=NULL)
986          tmpR.wvhdl[1]=(int *)omMemDup(r2->wvhdl[0]);
987      }
988      else
989        tmpR.order[1]=ringorder_dp;
990    }
991    else
992    {
993      tmpR.order[1]=ringorder_ds;
994      tmpR.OrdSgn=-1;
995    }
996    tmpR.block0[1]=rVar(r1)+1;
997    tmpR.block1[1]=rVar(r1)+rVar(r2);
998    tmpR.order[2]=ringorder_C;
999    tmpR.order[3]=(rRingOrder_t)0;
1000  }
1001  else
1002  {
1003    if ((r1->order[0]==ringorder_unspec)
1004        && (r2->order[0]==ringorder_unspec))
1005    {
1006      tmpR.order=(rRingOrder_t*)omAlloc(3*sizeof(rRingOrder_t));
1007      tmpR.block0=(int*)omAlloc(3*sizeof(int));
1008      tmpR.block1=(int*)omAlloc(3*sizeof(int));
1009      tmpR.wvhdl=(int**)omAlloc0(3*sizeof(int *));
1010      tmpR.order[0]=ringorder_unspec;
1011      tmpR.order[1]=ringorder_C;
1012      tmpR.order[2]=(rRingOrder_t)0;
1013      tmpR.block0[0]=1;
1014      tmpR.block1[0]=tmpR.N;
1015    }
1016    else if (l==k) /* r3=r1+r2 */
1017    {
1018      int b;
1019      ring rb;
1020      if (r1->order[0]==ringorder_unspec)
1021      {
1022        /* extend order of r2 to r3 */
1023        b=rBlocks(r2);
1024        rb=r2;
1025        tmpR.OrdSgn=r2->OrdSgn;
1026      }
1027      else if (r2->order[0]==ringorder_unspec)
1028      {
1029        /* extend order of r1 to r3 */
1030        b=rBlocks(r1);
1031        rb=r1;
1032        tmpR.OrdSgn=r1->OrdSgn;
1033      }
1034      else
1035      {
1036        b=rBlocks(r1)+rBlocks(r2)-2; /* for only one order C, only one 0 */
1037        rb=NULL;
1038      }
1039      tmpR.order=(rRingOrder_t*)omAlloc0(b*sizeof(rRingOrder_t));
1040      tmpR.block0=(int*)omAlloc0(b*sizeof(int));
1041      tmpR.block1=(int*)omAlloc0(b*sizeof(int));
1042      tmpR.wvhdl=(int**)omAlloc0(b*sizeof(int *));
1043      /* weights not implemented yet ...*/
1044      if (rb!=NULL)
1045      {
1046        for (i=0;i<b;i++)
1047        {
1048          tmpR.order[i]=rb->order[i];
1049          tmpR.block0[i]=rb->block0[i];
1050          tmpR.block1[i]=rb->block1[i];
1051          if (rb->wvhdl[i]!=NULL)
1052            WarnS("rSum: weights not implemented");
1053        }
1054        tmpR.block0[0]=1;
1055      }
1056      else /* ring sum for complete rings */
1057      {
1058        for (i=0;r1->order[i]!=0;i++)
1059        {
1060          tmpR.order[i]=r1->order[i];
1061          tmpR.block0[i]=r1->block0[i];
1062          tmpR.block1[i]=r1->block1[i];
1063          if (r1->wvhdl[i]!=NULL)
1064            tmpR.wvhdl[i] = (int*) omMemDup(r1->wvhdl[i]);
1065        }
1066        j=i;
1067        i--;
1068        if ((r1->order[i]==ringorder_c)
1069            ||(r1->order[i]==ringorder_C))
1070        {
1071          j--;
1072          tmpR.order[b-2]=r1->order[i];
1073        }
1074        for (i=0;r2->order[i]!=0;i++)
1075        {
1076          if ((r2->order[i]!=ringorder_c)
1077              &&(r2->order[i]!=ringorder_C))
1078          {
1079            tmpR.order[j]=r2->order[i];
1080            tmpR.block0[j]=r2->block0[i]+rVar(r1);
1081            tmpR.block1[j]=r2->block1[i]+rVar(r1);
1082            if (r2->wvhdl[i]!=NULL)
1083            {
1084              tmpR.wvhdl[j] = (int*) omMemDup(r2->wvhdl[i]);
1085            }
1086            j++;
1087          }
1088        }
1089        if((r1->OrdSgn==-1)||(r2->OrdSgn==-1))
1090          tmpR.OrdSgn=-1;
1091      }
1092    }
1093    else if ((k==rVar(r1)) && (k==rVar(r2))) /* r1 and r2 are "quite"
1094                                                the same ring */
1095      /* copy r1, because we have the variables from r1 */
1096    {
1097      int b=rBlocks(r1);
1098
1099      tmpR.order=(rRingOrder_t*)omAlloc0(b*sizeof(rRingOrder_t));
1100      tmpR.block0=(int*)omAlloc0(b*sizeof(int));
1101      tmpR.block1=(int*)omAlloc0(b*sizeof(int));
1102      tmpR.wvhdl=(int**)omAlloc0(b*sizeof(int *));
1103      /* weights not implemented yet ...*/
1104      for (i=0;i<b;i++)
1105      {
1106        tmpR.order[i]=r1->order[i];
1107        tmpR.block0[i]=r1->block0[i];
1108        tmpR.block1[i]=r1->block1[i];
1109        if (r1->wvhdl[i]!=NULL)
1110        {
1111          tmpR.wvhdl[i] = (int*) omMemDup(r1->wvhdl[i]);
1112        }
1113      }
1114      tmpR.OrdSgn=r1->OrdSgn;
1115    }
1116    else
1117    {
1118      for(i=0;i<k;i++) omFree((ADDRESS)tmpR.names[i]);
1119      omFreeSize((ADDRESS)names,tmpR.N*sizeof(char *));
1120      Werror("variables must not overlap (# of vars: %d,%d -> %d)",rVar(r1),rVar(r2),k);
1121      return -1;
1122    }
1123  }
1124  tmpR.bitmask=si_max(r1->bitmask,r2->bitmask);
1125  sum=(ring)omAllocBin(sip_sring_bin);
1126  memcpy(sum,&tmpR,sizeof(ip_sring));
1127  rComplete(sum);
1128
1129//#ifdef RDEBUG
1130//  rDebugPrint(sum);
1131//#endif
1132
1133
1134
1135#ifdef HAVE_PLURAL
1136  if(1)
1137  {
1138//    ring old_ring = currRing;
1139
1140    BOOLEAN R1_is_nc = rIsPluralRing(r1);
1141    BOOLEAN R2_is_nc = rIsPluralRing(r2);
1142
1143    if ( (R1_is_nc) || (R2_is_nc))
1144    {
1145      ring R1 = nc_rCreateNCcomm_rCopy(r1);
1146      assume( rIsPluralRing(R1) );
1147
1148#if 0
1149#ifdef RDEBUG
1150      rWrite(R1);
1151      rDebugPrint(R1);
1152#endif
1153#endif
1154      ring R2 = nc_rCreateNCcomm_rCopy(r2);
1155#if 0
1156#ifdef RDEBUG
1157      rWrite(R2);
1158      rDebugPrint(R2);
1159#endif
1160#endif
1161
1162//      rChangeCurrRing(sum); // ?
1163
1164      // Projections from R_i into Sum:
1165      /* multiplication matrices business: */
1166      /* find permutations of vars and pars */
1167      int *perm1 = (int *)omAlloc0((rVar(R1)+1)*sizeof(int));
1168      int *par_perm1 = NULL;
1169      if (rPar(R1)!=0) par_perm1=(int *)omAlloc0((rPar(R1)+1)*sizeof(int));
1170
1171      int *perm2 = (int *)omAlloc0((rVar(R2)+1)*sizeof(int));
1172      int *par_perm2 = NULL;
1173      if (rPar(R2)!=0) par_perm2=(int *)omAlloc0((rPar(R2)+1)*sizeof(int));
1174
1175      maFindPerm(R1->names,  rVar(R1),  rParameter(R1),  rPar(R1),
1176                 sum->names, rVar(sum), rParameter(sum), rPar(sum),
1177                 perm1, par_perm1, sum->cf->type);
1178
1179      maFindPerm(R2->names,  rVar(R2),  rParameter(R2),  rPar(R2),
1180                 sum->names, rVar(sum), rParameter(sum), rPar(sum),
1181                 perm2, par_perm2, sum->cf->type);
1182
1183
1184      matrix C1 = R1->GetNC()->C, C2 = R2->GetNC()->C;
1185      matrix D1 = R1->GetNC()->D, D2 = R2->GetNC()->D;
1186
1187      // !!!! BUG? C1 and C2 might live in different baserings!!!
1188
1189      int l = rVar(R1) + rVar(R2);
1190
1191      matrix C  = mpNew(l,l);
1192      matrix D  = mpNew(l,l);
1193
1194      for (i = 1; i <= rVar(R1); i++)
1195        for (j= rVar(R1)+1; j <= l; j++)
1196          MATELEM(C,i,j) = p_One(sum); // in 'sum'
1197
1198      id_Test((ideal)C, sum);
1199
1200      nMapFunc nMap1 = n_SetMap(R1->cf,sum->cf); /* can change something global: not usable
1201                                                    after the next nSetMap call :( */
1202      // Create blocked C and D matrices:
1203      for (i=1; i<= rVar(R1); i++)
1204        for (j=i+1; j<=rVar(R1); j++)
1205        {
1206          assume(MATELEM(C1,i,j) != NULL);
1207          MATELEM(C,i,j) = p_PermPoly(MATELEM(C1,i,j), perm1, R1, sum, nMap1, par_perm1, rPar(R1)); // need ADD + CMP ops.
1208
1209          if (MATELEM(D1,i,j) != NULL)
1210            MATELEM(D,i,j) = p_PermPoly(MATELEM(D1,i,j), perm1, R1, sum, nMap1, par_perm1, rPar(R1));
1211        }
1212
1213      id_Test((ideal)C, sum);
1214      id_Test((ideal)D, sum);
1215
1216
1217      nMapFunc nMap2 = n_SetMap(R2->cf,sum->cf); /* can change something global: not usable
1218                                                    after the next nSetMap call :( */
1219      for (i=1; i<= rVar(R2); i++)
1220        for (j=i+1; j<=rVar(R2); j++)
1221        {
1222          assume(MATELEM(C2,i,j) != NULL);
1223          MATELEM(C,rVar(R1)+i,rVar(R1)+j) = p_PermPoly(MATELEM(C2,i,j),perm2,R2,sum, nMap2,par_perm2,rPar(R2));
1224
1225          if (MATELEM(D2,i,j) != NULL)
1226            MATELEM(D,rVar(R1)+i,rVar(R1)+j) = p_PermPoly(MATELEM(D2,i,j),perm2,R2,sum, nMap2,par_perm2,rPar(R2));
1227        }
1228
1229      id_Test((ideal)C, sum);
1230      id_Test((ideal)D, sum);
1231
1232      // Now sum is non-commutative with blocked structure constants!
1233      if (nc_CallPlural(C, D, NULL, NULL, sum, false, false, true, sum))
1234        WarnS("Error initializing non-commutative multiplication!");
1235
1236      /* delete R1, R2*/
1237
1238#if 0
1239#ifdef RDEBUG
1240      rWrite(sum);
1241      rDebugPrint(sum);
1242
1243      Print("\nRefs: R1: %d, R2: %d\n", R1->GetNC()->ref, R2->GetNC()->ref);
1244
1245#endif
1246#endif
1247
1248
1249      rDelete(R1);
1250      rDelete(R2);
1251
1252      /* delete perm arrays */
1253      if (perm1!=NULL) omFree((ADDRESS)perm1);
1254      if (perm2!=NULL) omFree((ADDRESS)perm2);
1255      if (par_perm1!=NULL) omFree((ADDRESS)par_perm1);
1256      if (par_perm2!=NULL) omFree((ADDRESS)par_perm2);
1257
1258//      rChangeCurrRing(old_ring);
1259    }
1260
1261  }
1262#endif
1263
1264  ideal Q=NULL;
1265  ideal Q1=NULL, Q2=NULL;
1266  if (r1->qideal!=NULL)
1267  {
1268//    rChangeCurrRing(sum);
1269//     if (r2->qideal!=NULL)
1270//     {
1271//       WerrorS("todo: qring+qring");
1272//       return -1;
1273//     }
1274//     else
1275//     {}
1276    /* these were defined in the Plural Part above... */
1277    int *perm1 = (int *)omAlloc0((rVar(r1)+1)*sizeof(int));
1278    int *par_perm1 = NULL;
1279    if (rPar(r1)!=0) par_perm1=(int *)omAlloc0((rPar(r1)+1)*sizeof(int));
1280    maFindPerm(r1->names,  rVar(r1),  rParameter(r1),  rPar(r1),
1281               sum->names, rVar(sum), rParameter(sum), rPar(sum),
1282               perm1, par_perm1, sum->cf->type);
1283    nMapFunc nMap1 = n_SetMap(r1->cf,sum->cf);
1284    Q1 = idInit(IDELEMS(r1->qideal),1);
1285
1286    for (int for_i=0;for_i<IDELEMS(r1->qideal);for_i++)
1287      Q1->m[for_i] = p_PermPoly(
1288                                r1->qideal->m[for_i], perm1,
1289                                r1, sum,
1290                                nMap1,
1291                                par_perm1, rPar(r1));
1292
1293    omFree((ADDRESS)perm1);
1294  }
1295
1296  if (r2->qideal!=NULL)
1297  {
1298    //if (currRing!=sum)
1299    //  rChangeCurrRing(sum);
1300    int *perm2 = (int *)omAlloc0((rVar(r2)+1)*sizeof(int));
1301    int *par_perm2 = NULL;
1302    if (rPar(r2)!=0) par_perm2=(int *)omAlloc0((rPar(r2)+1)*sizeof(int));
1303    maFindPerm(r2->names,  rVar(r2),  rParameter(r2),  rPar(r2),
1304               sum->names, rVar(sum), rParameter(sum), rPar(sum),
1305               perm2, par_perm2, sum->cf->type);
1306    nMapFunc nMap2 = n_SetMap(r2->cf,sum->cf);
1307    Q2 = idInit(IDELEMS(r2->qideal),1);
1308
1309    for (int for_i=0;for_i<IDELEMS(r2->qideal);for_i++)
1310      Q2->m[for_i] = p_PermPoly(
1311                  r2->qideal->m[for_i], perm2,
1312                  r2, sum,
1313                  nMap2,
1314                  par_perm2, rPar(r2));
1315
1316    omFree((ADDRESS)perm2);
1317  }
1318  if (Q1!=NULL)
1319  {
1320    if ( Q2!=NULL)
1321      Q = id_SimpleAdd(Q1,Q2,sum);
1322    else
1323      Q=id_Copy(Q1,sum);
1324  }
1325  else
1326  {
1327    if ( Q2!=NULL)
1328      Q = id_Copy(Q2,sum);
1329    else
1330      Q=NULL;
1331  }
1332  sum->qideal = Q;
1333
1334#ifdef HAVE_PLURAL
1335  if( rIsPluralRing(sum) )
1336    nc_SetupQuotient( sum );
1337#endif
1338  return 1;
1339}
1340
1341/*2
1342 *returns -1 for not compatible, (sum is undefined)
1343 *         0 for equal, (and sum)
1344 *         1 for compatible (and sum)
1345 */
1346int rSum(ring r1, ring r2, ring &sum)
1347{
1348  if ((r1==NULL)||(r2==NULL)
1349  ||(r1->cf==NULL)||(r2->cf==NULL))
1350    return -1;
1351  if (r1==r2)
1352  {
1353    sum=r1;
1354    r1->ref++;
1355    return 0;
1356  }
1357  return rSumInternal(r1,r2,sum,TRUE,FALSE);
1358}
1359
1360/*2
1361 * create a copy of the ring r
1362 * used for qring definition,..
1363 * DOES NOT CALL rComplete
1364 */
1365ring rCopy0(const ring r, BOOLEAN copy_qideal, BOOLEAN copy_ordering)
1366{
1367  if (r == NULL) return NULL;
1368  int i,j;
1369  ring res=(ring)omAlloc0Bin(sip_sring_bin);
1370  //memset: res->idroot=NULL; /* local objects */
1371  //ideal      minideal;
1372  res->options=r->options; /* ring dependent options */
1373
1374  //memset: res->ordsgn=NULL;
1375  //memset: res->typ=NULL;
1376  //memset: res->VarOffset=NULL;
1377  //memset: res->firstwv=NULL;
1378
1379  //struct omBin   PolyBin; /* Bin from where monoms are allocated */
1380  //memset: res->PolyBin=NULL; // rComplete
1381  res->cf=nCopyCoeff(r->cf);     /* coeffs */
1382
1383  //memset: res->ref=0; /* reference counter to the ring */
1384
1385  res->N=rVar(r);      /* number of vars */
1386
1387  res->firstBlockEnds=r->firstBlockEnds;
1388#ifdef HAVE_PLURAL
1389  res->real_var_start=r->real_var_start;
1390  res->real_var_end=r->real_var_end;
1391#endif
1392
1393#ifdef HAVE_SHIFTBBA
1394  res->isLPring=r->isLPring; /* 0 for non-letterplace rings, otherwise the number of LP blocks, at least 1, known also as lV */
1395#endif
1396
1397  res->VectorOut=r->VectorOut;
1398  res->ShortOut=r->ShortOut;
1399  res->CanShortOut=r->CanShortOut;
1400
1401  //memset: res->ExpL_Size=0;
1402  //memset: res->CmpL_Size=0;
1403  //memset: res->VarL_Size=0;
1404  //memset: res->pCompIndex=0;
1405  //memset: res->pOrdIndex=0;
1406  //memset: res->OrdSize=0;
1407  //memset: res->VarL_LowIndex=0;
1408  //memset: res->NegWeightL_Size=0;
1409  //memset: res->NegWeightL_Offset=NULL;
1410  //memset: res->VarL_Offset=NULL;
1411
1412  // the following are set by rComplete unless predefined
1413  // therefore, we copy these values: maybe they are non-standard
1414  /* mask for getting single exponents */
1415  res->bitmask=r->bitmask;
1416  res->divmask=r->divmask;
1417  res->BitsPerExp = r->BitsPerExp;
1418  res->ExpPerLong =  r->ExpPerLong;
1419
1420  //memset: res->p_Procs=NULL;
1421  //memset: res->pFDeg=NULL;
1422  //memset: res->pLDeg=NULL;
1423  //memset: res->pFDegOrig=NULL;
1424  //memset: res->pLDegOrig=NULL;
1425  //memset: res->p_Setm=NULL;
1426  //memset: res->cf=NULL;
1427
1428/*
1429  if (r->extRing!=NULL)
1430    r->extRing->ref++;
1431
1432  res->extRing=r->extRing;
1433  //memset: res->qideal=NULL;
1434*/
1435
1436
1437  if (copy_ordering == TRUE)
1438  {
1439    res->LexOrder=r->LexOrder; // TRUE if the monomial ordering has polynomial and power series blocks
1440    res->MixedOrder=r->MixedOrder; // TRUE for mixed (global/local) ordering, FALSE otherwise,
1441    i=rBlocks(r);
1442    res->wvhdl   = (int **)omAlloc(i * sizeof(int *));
1443    res->order   = (rRingOrder_t *) omAlloc(i * sizeof(rRingOrder_t));
1444    res->block0  = (int *) omAlloc(i * sizeof(int));
1445    res->block1  = (int *) omAlloc(i * sizeof(int));
1446    for (j=0; j<i; j++)
1447    {
1448      if (r->wvhdl[j]!=NULL)
1449      {
1450        res->wvhdl[j] = (int*) omMemDup(r->wvhdl[j]);
1451      }
1452      else
1453        res->wvhdl[j]=NULL;
1454    }
1455    memcpy(res->order,r->order,i * sizeof(rRingOrder_t));
1456    memcpy(res->block0,r->block0,i * sizeof(int));
1457    memcpy(res->block1,r->block1,i * sizeof(int));
1458  }
1459  //memset: else
1460  //memset: {
1461  //memset:   res->wvhdl = NULL;
1462  //memset:   res->order = NULL;
1463  //memset:   res->block0 = NULL;
1464  //memset:   res->block1 = NULL;
1465  //memset: }
1466
1467  res->names   = (char **)omAlloc0(rVar(r) * sizeof(char *));
1468  for (i=0; i<rVar(res); i++)
1469  {
1470    res->names[i] = omStrDup(r->names[i]);
1471  }
1472  if (r->qideal!=NULL)
1473  {
1474    if (copy_qideal)
1475    {
1476      assume(copy_ordering);
1477      rComplete(res);
1478      res->qideal= idrCopyR_NoSort(r->qideal, r, res);
1479      rUnComplete(res);
1480    }
1481    //memset: else res->qideal = NULL;
1482  }
1483  //memset: else res->qideal = NULL;
1484  //memset: res->GetNC() = NULL; // copy is purely commutative!!!
1485  return res;
1486}
1487
1488/*2
1489 * create a copy of the ring r
1490 * used for qring definition,..
1491 * DOES NOT CALL rComplete
1492 */
1493ring rCopy0AndAddA(const ring r,  int64vec *wv64, BOOLEAN copy_qideal, BOOLEAN copy_ordering)
1494{
1495  if (r == NULL) return NULL;
1496  int i,j;
1497  ring res=(ring)omAlloc0Bin(sip_sring_bin);
1498  //memcpy(res,r,sizeof(ip_sring));
1499  //memset: res->idroot=NULL; /* local objects */
1500  //ideal      minideal;
1501  res->options=r->options; /* ring dependent options */
1502
1503  //memset: res->ordsgn=NULL;
1504  //memset: res->typ=NULL;
1505  //memset: res->VarOffset=NULL;
1506  //memset: res->firstwv=NULL;
1507
1508  //struct omBin   PolyBin; /* Bin from where monoms are allocated */
1509  //memset: res->PolyBin=NULL; // rComplete
1510  res->cf=nCopyCoeff(r->cf);     /* coeffs */
1511
1512  //memset: res->ref=0; /* reference counter to the ring */
1513
1514  res->N=rVar(r);      /* number of vars */
1515
1516  res->firstBlockEnds=r->firstBlockEnds;
1517#ifdef HAVE_PLURAL
1518  res->real_var_start=r->real_var_start;
1519  res->real_var_end=r->real_var_end;
1520#endif
1521
1522#ifdef HAVE_SHIFTBBA
1523  res->isLPring=r->isLPring; /* 0 for non-letterplace rings, otherwise the number of LP blocks, at least 1, known also as lV */
1524#endif
1525
1526  res->VectorOut=r->VectorOut;
1527  res->ShortOut=r->ShortOut;
1528  res->CanShortOut=r->CanShortOut;
1529  res->LexOrder=r->LexOrder; // TRUE if the monomial ordering has polynomial and power series blocks
1530  res->MixedOrder=r->MixedOrder; // TRUE for mixed (global/local) ordering, FALSE otherwise,
1531
1532  //memset: res->ExpL_Size=0;
1533  //memset: res->CmpL_Size=0;
1534  //memset: res->VarL_Size=0;
1535  //memset: res->pCompIndex=0;
1536  //memset: res->pOrdIndex=0;
1537  //memset: res->OrdSize=0;
1538  //memset: res->VarL_LowIndex=0;
1539  //memset: res->NegWeightL_Size=0;
1540  //memset: res->NegWeightL_Offset=NULL;
1541  //memset: res->VarL_Offset=NULL;
1542
1543  // the following are set by rComplete unless predefined
1544  // therefore, we copy these values: maybe they are non-standard
1545  /* mask for getting single exponents */
1546  res->bitmask=r->bitmask;
1547  res->divmask=r->divmask;
1548  res->BitsPerExp = r->BitsPerExp;
1549  res->ExpPerLong =  r->ExpPerLong;
1550
1551  //memset: res->p_Procs=NULL;
1552  //memset: res->pFDeg=NULL;
1553  //memset: res->pLDeg=NULL;
1554  //memset: res->pFDegOrig=NULL;
1555  //memset: res->pLDegOrig=NULL;
1556  //memset: res->p_Setm=NULL;
1557  //memset: res->cf=NULL;
1558
1559/*
1560  if (r->extRing!=NULL)
1561    r->extRing->ref++;
1562
1563  res->extRing=r->extRing;
1564  //memset: res->qideal=NULL;
1565*/
1566
1567
1568  if (copy_ordering == TRUE)
1569  {
1570    i=rBlocks(r)+1; // DIFF to rCopy0
1571    res->wvhdl   = (int **)omAlloc(i * sizeof(int *));
1572    res->order   = (rRingOrder_t *) omAlloc(i * sizeof(rRingOrder_t));
1573    res->block0  = (int *) omAlloc(i * sizeof(int));
1574    res->block1  = (int *) omAlloc(i * sizeof(int));
1575    for (j=0; j<i-1; j++)
1576    {
1577      if (r->wvhdl[j]!=NULL)
1578      {
1579        res->wvhdl[j+1] = (int*) omMemDup(r->wvhdl[j]); //DIFF
1580      }
1581      else
1582        res->wvhdl[j+1]=NULL; //DIFF
1583    }
1584    memcpy(&(res->order[1]),r->order,(i-1) * sizeof(rRingOrder_t)); //DIFF
1585    memcpy(&(res->block0[1]),r->block0,(i-1) * sizeof(int)); //DIFF
1586    memcpy(&(res->block1[1]),r->block1,(i-1) * sizeof(int)); //DIFF
1587  }
1588  //memset: else
1589  //memset: {
1590  //memset:   res->wvhdl = NULL;
1591  //memset:   res->order = NULL;
1592  //memset:   res->block0 = NULL;
1593  //memset:   res->block1 = NULL;
1594  //memset: }
1595
1596  //the added A
1597  res->order[0]=ringorder_a64;
1598  int length=wv64->rows();
1599  int64 *A=(int64 *)omAlloc(length*sizeof(int64));
1600  for(j=length-1;j>=0;j--)
1601  {
1602     A[j]=(*wv64)[j];
1603  }
1604  res->wvhdl[0]=(int *)A;
1605  res->block0[0]=1;
1606  res->block1[0]=length;
1607  //
1608
1609  res->names   = (char **)omAlloc0(rVar(r) * sizeof(char *));
1610  for (i=0; i<rVar(res); i++)
1611  {
1612    res->names[i] = omStrDup(r->names[i]);
1613  }
1614  if (r->qideal!=NULL)
1615  {
1616    if (copy_qideal)
1617    {
1618      #ifndef SING_NDEBUG
1619      if (!copy_ordering)
1620        WerrorS("internal error: rCopy0(Q,TRUE,FALSE)");
1621      else
1622      #endif
1623      {
1624      #ifndef SING_NDEBUG
1625        WarnS("internal bad stuff: rCopy0(Q,TRUE,TRUE)");
1626      #endif
1627        rComplete(res);
1628        res->qideal= idrCopyR_NoSort(r->qideal, r, res);
1629        rUnComplete(res);
1630      }
1631    }
1632    //memset: else res->qideal = NULL;
1633  }
1634  //memset: else res->qideal = NULL;
1635  //memset: res->GetNC() = NULL; // copy is purely commutative!!!
1636  return res;
1637}
1638
1639/*2
1640 * create a copy of the ring r, which must be equivalent to currRing
1641 * used for qring definition,..
1642 * (i.e.: normal rings: same nCopy as currRing;
1643 *        qring:        same nCopy, same idCopy as currRing)
1644 */
1645ring rCopy(ring r)
1646{
1647  if (r == NULL) return NULL;
1648  ring res=rCopy0(r,FALSE,TRUE);
1649  rComplete(res, 1); // res is purely commutative so far
1650  if (r->qideal!=NULL) res->qideal=idrCopyR_NoSort(r->qideal, r, res);
1651
1652#ifdef HAVE_PLURAL
1653  if (rIsPluralRing(r))
1654    if( nc_rCopy(res, r, true) ) {}
1655#endif
1656
1657  return res;
1658}
1659
1660BOOLEAN rEqual(ring r1, ring r2, BOOLEAN qr)
1661{
1662  if (r1 == r2) return TRUE;
1663  if (r1 == NULL || r2 == NULL) return FALSE;
1664  if (r1->cf!=r2->cf) return FALSE;
1665  if (rVar(r1)!=rVar(r2)) return FALSE;
1666
1667  if( !rSamePolyRep(r1, r2) )
1668    return FALSE;
1669
1670  int i/*, j*/;
1671
1672  for (i=0; i<rVar(r1); i++)
1673  {
1674    if ((r1->names[i] != NULL) && (r2->names[i] != NULL))
1675    {
1676      if (strcmp(r1->names[i], r2->names[i])) return FALSE;
1677    }
1678    else if ((r1->names[i] != NULL) ^ (r2->names[i] != NULL))
1679    {
1680      return FALSE;
1681    }
1682  }
1683
1684  if (qr)
1685  {
1686    if (r1->qideal != NULL)
1687    {
1688      ideal id1 = r1->qideal, id2 = r2->qideal;
1689      int i, n;
1690      poly *m1, *m2;
1691
1692      if (id2 == NULL) return FALSE;
1693      if ((n = IDELEMS(id1)) != IDELEMS(id2)) return FALSE;
1694
1695      {
1696        m1 = id1->m;
1697        m2 = id2->m;
1698        for (i=0; i<n; i++)
1699          if (! p_EqualPolys(m1[i],m2[i], r1, r2)) return FALSE;
1700      }
1701    }
1702    else if (r2->qideal != NULL) return FALSE;
1703  }
1704
1705  return TRUE;
1706}
1707
1708BOOLEAN rSamePolyRep(ring r1, ring r2)
1709{
1710  int i, j;
1711
1712  if (r1 == r2) return TRUE;
1713
1714  if (r1 == NULL || r2 == NULL) return FALSE;
1715
1716  if ((r1->cf != r2->cf)
1717  || (rVar(r1) != rVar(r2))
1718  || (r1->OrdSgn != r2->OrdSgn))
1719    return FALSE;
1720
1721  i=0;
1722  while (r1->order[i] != 0)
1723  {
1724    if (r2->order[i] == 0) return FALSE;
1725    if ((r1->order[i] != r2->order[i])
1726    || (r1->block0[i] != r2->block0[i])
1727    || (r1->block1[i] != r2->block1[i]))
1728      return FALSE;
1729    if (r1->wvhdl[i] != NULL)
1730    {
1731      if (r2->wvhdl[i] == NULL)
1732        return FALSE;
1733      for (j=0; j<r1->block1[i]-r1->block0[i]+1; j++)
1734        if (r2->wvhdl[i][j] != r1->wvhdl[i][j])
1735          return FALSE;
1736    }
1737    else if (r2->wvhdl[i] != NULL) return FALSE;
1738    i++;
1739  }
1740  if (r2->order[i] != 0) return FALSE;
1741
1742  // we do not check variable names
1743  // we do not check minpoly/minideal
1744  // we do not check qideal
1745
1746  return TRUE;
1747}
1748
1749rOrderType_t rGetOrderType(ring r)
1750{
1751  // check for simple ordering
1752  if (rHasSimpleOrder(r))
1753  {
1754    if ((r->order[1] == ringorder_c)
1755    || (r->order[1] == ringorder_C))
1756    {
1757      switch(r->order[0])
1758      {
1759          case ringorder_dp:
1760          case ringorder_wp:
1761          case ringorder_ds:
1762          case ringorder_ws:
1763          case ringorder_ls:
1764          case ringorder_unspec:
1765            if (r->order[1] == ringorder_C
1766            ||  r->order[0] == ringorder_unspec)
1767              return rOrderType_ExpComp;
1768            return rOrderType_Exp;
1769
1770          default:
1771            assume(r->order[0] == ringorder_lp ||
1772                   r->order[0] == ringorder_rs ||
1773                   r->order[0] == ringorder_Dp ||
1774                   r->order[0] == ringorder_Wp ||
1775                   r->order[0] == ringorder_Ds ||
1776                   r->order[0] == ringorder_Ws);
1777
1778            if (r->order[1] == ringorder_c) return rOrderType_ExpComp;
1779            return rOrderType_Exp;
1780      }
1781    }
1782    else
1783    {
1784      assume((r->order[0]==ringorder_c)||(r->order[0]==ringorder_C));
1785      return rOrderType_CompExp;
1786    }
1787  }
1788  else
1789    return rOrderType_General;
1790}
1791
1792BOOLEAN rHas_c_Ordering(const ring r)
1793{
1794  return (r->order[0] == ringorder_c);
1795}
1796BOOLEAN rHasSimpleOrder(const ring r)
1797{
1798  if (r->order[0] == ringorder_unspec) return TRUE;
1799  int blocks = rBlocks(r) - 1;
1800  assume(blocks >= 1);
1801  if (blocks == 1) return TRUE;
1802
1803  int s = 0;
1804  while( (s < blocks) && (r->order[s] == ringorder_IS) && (r->order[blocks-1] == ringorder_IS) )
1805  {
1806    s++;
1807    blocks--;
1808  }
1809
1810  if ((blocks - s) > 2)  return FALSE;
1811
1812  assume( blocks == s + 2 );
1813
1814  if (
1815     (r->order[s] != ringorder_c)
1816  && (r->order[s] != ringorder_C)
1817  && (r->order[s+1] != ringorder_c)
1818  && (r->order[s+1] != ringorder_C)
1819     )
1820    return FALSE;
1821  if ((r->order[s+1] == ringorder_M)
1822  || (r->order[s] == ringorder_M))
1823    return FALSE;
1824  return TRUE;
1825}
1826
1827// returns TRUE, if simple lp or ls ordering
1828BOOLEAN rHasSimpleLexOrder(const ring r)
1829{
1830  return rHasSimpleOrder(r) &&
1831    (r->order[0] == ringorder_ls ||
1832     r->order[0] == ringorder_lp ||
1833     r->order[1] == ringorder_ls ||
1834     r->order[1] == ringorder_lp);
1835}
1836
1837BOOLEAN rOrder_is_DegOrdering(const rRingOrder_t order)
1838{
1839  switch(order)
1840  {
1841      case ringorder_dp:
1842      case ringorder_Dp:
1843      case ringorder_ds:
1844      case ringorder_Ds:
1845      case ringorder_Ws:
1846      case ringorder_Wp:
1847      case ringorder_ws:
1848      case ringorder_wp:
1849        return TRUE;
1850
1851      default:
1852        return FALSE;
1853  }
1854}
1855
1856BOOLEAN rOrder_is_WeightedOrdering(rRingOrder_t order)
1857{
1858  switch(order)
1859  {
1860      case ringorder_Ws:
1861      case ringorder_Wp:
1862      case ringorder_ws:
1863      case ringorder_wp:
1864        return TRUE;
1865
1866      default:
1867        return FALSE;
1868  }
1869}
1870
1871BOOLEAN rHasSimpleOrderAA(ring r)
1872{
1873  if (r->order[0] == ringorder_unspec) return TRUE;
1874  int blocks = rBlocks(r) - 1;
1875  assume(blocks >= 1);
1876  if (blocks == 1) return TRUE;
1877
1878  int s = 0;
1879  while( (s < blocks) && (r->order[s] == ringorder_IS) && (r->order[blocks-1] == ringorder_IS) )
1880  {
1881    s++;
1882    blocks--;
1883  }
1884
1885  if ((blocks - s) > 3)  return FALSE;
1886
1887//  if ((blocks > 3) || (blocks < 2)) return FALSE;
1888  if ((blocks - s) == 3)
1889  {
1890    return (((r->order[s] == ringorder_aa) && (r->order[s+1] != ringorder_M) &&
1891             ((r->order[s+2] == ringorder_c) || (r->order[s+2] == ringorder_C))) ||
1892            (((r->order[s] == ringorder_c) || (r->order[s] == ringorder_C)) &&
1893             (r->order[s+1] == ringorder_aa) && (r->order[s+2] != ringorder_M)));
1894  }
1895  else
1896  {
1897    return ((r->order[s] == ringorder_aa) && (r->order[s+1] != ringorder_M));
1898  }
1899}
1900
1901// return TRUE if p_SetComp requires p_Setm
1902BOOLEAN rOrd_SetCompRequiresSetm(const ring r)
1903{
1904  if (r->typ != NULL)
1905  {
1906    int pos;
1907    for (pos=0;pos<r->OrdSize;pos++)
1908    {
1909      sro_ord* o=&(r->typ[pos]);
1910      if (   (o->ord_typ == ro_syzcomp)
1911          || (o->ord_typ == ro_syz)
1912          || (o->ord_typ == ro_is)
1913          || (o->ord_typ == ro_am)
1914          || (o->ord_typ == ro_isTemp))
1915        return TRUE;
1916    }
1917  }
1918  return FALSE;
1919}
1920
1921// return TRUE if p->exp[r->pOrdIndex] holds total degree of p */
1922BOOLEAN rOrd_is_Totaldegree_Ordering(const ring r)
1923{
1924  // Hmm.... what about Syz orderings?
1925  return (rVar(r) > 1 &&
1926          ((rHasSimpleOrder(r) &&
1927           (rOrder_is_DegOrdering((rRingOrder_t)r->order[0]) ||
1928            rOrder_is_DegOrdering(( rRingOrder_t)r->order[1]))) ||
1929           (rHasSimpleOrderAA(r) &&
1930            (rOrder_is_DegOrdering((rRingOrder_t)r->order[1]) ||
1931            ((r->order[1]!=0) &&
1932             rOrder_is_DegOrdering((rRingOrder_t)r->order[2]))))));
1933}
1934
1935// return TRUE if p->exp[r->pOrdIndex] holds a weighted degree of p */
1936BOOLEAN rOrd_is_WeightedDegree_Ordering(const ring r )
1937{
1938  // Hmm.... what about Syz orderings?
1939  return ((rVar(r) > 1) &&
1940          rHasSimpleOrder(r) &&
1941          (rOrder_is_WeightedOrdering((rRingOrder_t)r->order[0]) ||
1942           rOrder_is_WeightedOrdering(( rRingOrder_t)r->order[1])));
1943}
1944
1945BOOLEAN rIsPolyVar(int v,const ring r)
1946{
1947  int  i=0;
1948  while(r->order[i]!=0)
1949  {
1950    if((r->block0[i]<=v)
1951    && (r->block1[i]>=v))
1952    {
1953      switch(r->order[i])
1954      {
1955        case ringorder_a:
1956          return (r->wvhdl[i][v-r->block0[i]]>0);
1957        case ringorder_M:
1958          return 2; /*don't know*/
1959        case ringorder_a64: /* assume: all weight are non-negative!*/
1960        case ringorder_lp:
1961        case ringorder_rs:
1962        case ringorder_dp:
1963        case ringorder_Dp:
1964        case ringorder_wp:
1965        case ringorder_Wp:
1966          return TRUE;
1967        case ringorder_ls:
1968        case ringorder_ds:
1969        case ringorder_Ds:
1970        case ringorder_ws:
1971        case ringorder_Ws:
1972          return FALSE;
1973        default:
1974          break;
1975      }
1976    }
1977    i++;
1978  }
1979  return 3; /* could not find var v*/
1980}
1981
1982#ifdef RDEBUG
1983// This should eventually become a full-fledge ring check, like pTest
1984BOOLEAN rDBTest(ring r, const char* fn, const int l)
1985{
1986  int i,j;
1987
1988  if (r == NULL)
1989  {
1990    dReportError("Null ring in %s:%d", fn, l);
1991    return FALSE;
1992  }
1993
1994
1995  if (r->N == 0) return TRUE;
1996
1997  if ((r->OrdSgn!=1) && (r->OrdSgn!= -1))
1998  {
1999    dReportError("missing OrdSgn in %s:%d", fn, l);
2000    return FALSE;
2001  }
2002
2003//  omCheckAddrSize(r,sizeof(ip_sring));
2004#if OM_CHECK > 0
2005  i=rBlocks(r);
2006  omCheckAddrSize(r->order,i*sizeof(int));
2007  omCheckAddrSize(r->block0,i*sizeof(int));
2008  omCheckAddrSize(r->block1,i*sizeof(int));
2009  for(int j=0;j<=i;j++)
2010  {
2011    if((r->order[j]<0)||(r->order[j]>ringorder_unspec))
2012      dError("wrong order in r->order");
2013  }
2014  if (r->wvhdl!=NULL)
2015  {
2016    omCheckAddrSize(r->wvhdl,i*sizeof(int *));
2017    for (j=0;j<i; j++)
2018    {
2019      if (r->wvhdl[j] != NULL) omCheckAddr(r->wvhdl[j]);
2020    }
2021  }
2022#endif
2023  if (r->VarOffset == NULL)
2024  {
2025    dReportError("Null ring VarOffset -- no rComplete (?) in n %s:%d", fn, l);
2026    return FALSE;
2027  }
2028  omCheckAddrSize(r->VarOffset,(r->N+1)*sizeof(int));
2029
2030  if ((r->OrdSize==0)!=(r->typ==NULL))
2031  {
2032    dReportError("mismatch OrdSize and typ-pointer in %s:%d");
2033    return FALSE;
2034  }
2035  omcheckAddrSize(r->typ,r->OrdSize*sizeof(*(r->typ)));
2036  omCheckAddrSize(r->VarOffset,(r->N+1)*sizeof(*(r->VarOffset)));
2037  // test assumptions:
2038  for(i=0;i<=r->N;i++) // for all variables (i = 0..N)
2039  {
2040    if(r->typ!=NULL)
2041    {
2042      for(j=0;j<r->OrdSize;j++) // for all ordering blocks (j =0..OrdSize-1)
2043      {
2044        if(r->typ[j].ord_typ == ro_isTemp)
2045        {
2046          const int p = r->typ[j].data.isTemp.suffixpos;
2047
2048          if(p <= j)
2049            dReportError("ordrec prefix %d is unmatched",j);
2050
2051          assume( p < r->OrdSize );
2052
2053          if(r->typ[p].ord_typ != ro_is)
2054            dReportError("ordrec prefix %d is unmatched (suffix: %d is wrong!!!)",j, p);
2055
2056          // Skip all intermediate blocks for undone variables:
2057          if(r->typ[j].data.isTemp.pVarOffset[i] != -1) // Check i^th variable
2058          {
2059            j = p - 1; // SKIP ALL INTERNAL BLOCKS...???
2060            continue; // To make for check OrdSize bound...
2061          }
2062        }
2063        else if (r->typ[j].ord_typ == ro_is)
2064        {
2065          // Skip all intermediate blocks for undone variables:
2066          if(r->typ[j].data.is.pVarOffset[i] != -1)
2067          {
2068            // TODO???
2069          }
2070
2071        }
2072        else
2073        {
2074          if (r->typ[j].ord_typ==ro_cp)
2075          {
2076            if(((short)r->VarOffset[i]) == r->typ[j].data.cp.place)
2077              dReportError("ordrec %d conflicts with var %d",j,i);
2078          }
2079          else
2080            if ((r->typ[j].ord_typ!=ro_syzcomp)
2081            && (r->VarOffset[i] == r->typ[j].data.dp.place))
2082              dReportError("ordrec %d conflicts with var %d",j,i);
2083        }
2084      }
2085    }
2086    int tmp;
2087      tmp=r->VarOffset[i] & 0xffffff;
2088      #if SIZEOF_LONG == 8
2089        if ((r->VarOffset[i] >> 24) >63)
2090      #else
2091        if ((r->VarOffset[i] >> 24) >31)
2092      #endif
2093          dReportError("bit_start out of range:%d",r->VarOffset[i] >> 24);
2094      if (i > 0 && ((tmp<0) ||(tmp>r->ExpL_Size-1)))
2095      {
2096        dReportError("varoffset out of range for var %d: %d",i,tmp);
2097      }
2098  }
2099  if(r->typ!=NULL)
2100  {
2101    for(j=0;j<r->OrdSize;j++)
2102    {
2103      if ((r->typ[j].ord_typ==ro_dp)
2104      || (r->typ[j].ord_typ==ro_wp)
2105      || (r->typ[j].ord_typ==ro_wp_neg))
2106      {
2107        if (r->typ[j].data.dp.start > r->typ[j].data.dp.end)
2108          dReportError("in ordrec %d: start(%d) > end(%d)",j,
2109            r->typ[j].data.dp.start, r->typ[j].data.dp.end);
2110        if ((r->typ[j].data.dp.start < 1)
2111        || (r->typ[j].data.dp.end > r->N))
2112          dReportError("in ordrec %d: start(%d)<1 or end(%d)>vars(%d)",j,
2113            r->typ[j].data.dp.start, r->typ[j].data.dp.end,r->N);
2114      }
2115    }
2116  }
2117
2118  assume(r != NULL);
2119  assume(r->cf != NULL);
2120
2121  if (nCoeff_is_algExt(r->cf))
2122  {
2123    assume(r->cf->extRing != NULL);
2124    assume(r->cf->extRing->qideal != NULL);
2125    omCheckAddr(r->cf->extRing->qideal->m[0]);
2126  }
2127
2128  //assume(r->cf!=NULL);
2129
2130  return TRUE;
2131}
2132#endif
2133
2134static void rO_Align(int &place, int &bitplace)
2135{
2136  // increment place to the next aligned one
2137  // (count as Exponent_t,align as longs)
2138  if (bitplace!=BITS_PER_LONG)
2139  {
2140    place++;
2141    bitplace=BITS_PER_LONG;
2142  }
2143}
2144
2145static void rO_TDegree(int &place, int &bitplace, int start, int end,
2146    long *o, sro_ord &ord_struct)
2147{
2148  // degree (aligned) of variables v_start..v_end, ordsgn 1
2149  rO_Align(place,bitplace);
2150  ord_struct.ord_typ=ro_dp;
2151  ord_struct.data.dp.start=start;
2152  ord_struct.data.dp.end=end;
2153  ord_struct.data.dp.place=place;
2154  o[place]=1;
2155  place++;
2156  rO_Align(place,bitplace);
2157}
2158
2159static void rO_TDegree_neg(int &place, int &bitplace, int start, int end,
2160    long *o, sro_ord &ord_struct)
2161{
2162  // degree (aligned) of variables v_start..v_end, ordsgn -1
2163  rO_Align(place,bitplace);
2164  ord_struct.ord_typ=ro_dp;
2165  ord_struct.data.dp.start=start;
2166  ord_struct.data.dp.end=end;
2167  ord_struct.data.dp.place=place;
2168  o[place]=-1;
2169  place++;
2170  rO_Align(place,bitplace);
2171}
2172
2173static void rO_WDegree(int &place, int &bitplace, int start, int end,
2174    long *o, sro_ord &ord_struct, int *weights)
2175{
2176  // weighted degree (aligned) of variables v_start..v_end, ordsgn 1
2177  while((start<end) && (weights[0]==0)) { start++; weights++; }
2178  while((start<end) && (weights[end-start]==0)) { end--; }
2179  int i;
2180  int pure_tdeg=1;
2181  for(i=start;i<=end;i++)
2182  {
2183    if(weights[i-start]!=1)
2184    {
2185      pure_tdeg=0;
2186      break;
2187    }
2188  }
2189  if (pure_tdeg)
2190  {
2191    rO_TDegree(place,bitplace,start,end,o,ord_struct);
2192    return;
2193  }
2194  rO_Align(place,bitplace);
2195  ord_struct.ord_typ=ro_wp;
2196  ord_struct.data.wp.start=start;
2197  ord_struct.data.wp.end=end;
2198  ord_struct.data.wp.place=place;
2199  ord_struct.data.wp.weights=weights;
2200  o[place]=1;
2201  place++;
2202  rO_Align(place,bitplace);
2203  for(i=start;i<=end;i++)
2204  {
2205    if(weights[i-start]<0)
2206    {
2207      ord_struct.ord_typ=ro_wp_neg;
2208      break;
2209    }
2210  }
2211}
2212
2213static void rO_WMDegree(int &place, int &bitplace, int start, int end,
2214    long *o, sro_ord &ord_struct, int *weights)
2215{
2216  assume(weights != NULL);
2217
2218  // weighted degree (aligned) of variables v_start..v_end, ordsgn 1
2219//  while((start<end) && (weights[0]==0)) { start++; weights++; }
2220//  while((start<end) && (weights[end-start]==0)) { end--; }
2221  rO_Align(place,bitplace);
2222  ord_struct.ord_typ=ro_am;
2223  ord_struct.data.am.start=start;
2224  ord_struct.data.am.end=end;
2225  ord_struct.data.am.place=place;
2226  ord_struct.data.am.weights=weights;
2227  ord_struct.data.am.weights_m = weights + (end-start+1);
2228  ord_struct.data.am.len_gen=weights[end-start+1];
2229  assume( ord_struct.data.am.weights_m[0] == ord_struct.data.am.len_gen );
2230  o[place]=1;
2231  place++;
2232  rO_Align(place,bitplace);
2233}
2234
2235static void rO_WDegree64(int &place, int &bitplace, int start, int end,
2236    long *o, sro_ord &ord_struct, int64 *weights)
2237{
2238  // weighted degree (aligned) of variables v_start..v_end, ordsgn 1,
2239  // reserved 2 places
2240  rO_Align(place,bitplace);
2241  ord_struct.ord_typ=ro_wp64;
2242  ord_struct.data.wp64.start=start;
2243  ord_struct.data.wp64.end=end;
2244  ord_struct.data.wp64.place=place;
2245  ord_struct.data.wp64.weights64=weights;
2246  o[place]=1;
2247  place++;
2248  o[place]=1;
2249  place++;
2250  rO_Align(place,bitplace);
2251}
2252
2253static void rO_WDegree_neg(int &place, int &bitplace, int start, int end,
2254    long *o, sro_ord &ord_struct, int *weights)
2255{
2256  // weighted degree (aligned) of variables v_start..v_end, ordsgn -1
2257  while((start<end) && (weights[0]==0)) { start++; weights++; }
2258  while((start<end) && (weights[end-start]==0)) { end--; }
2259  rO_Align(place,bitplace);
2260  ord_struct.ord_typ=ro_wp;
2261  ord_struct.data.wp.start=start;
2262  ord_struct.data.wp.end=end;
2263  ord_struct.data.wp.place=place;
2264  ord_struct.data.wp.weights=weights;
2265  o[place]=-1;
2266  place++;
2267  rO_Align(place,bitplace);
2268  int i;
2269  for(i=start;i<=end;i++)
2270  {
2271    if(weights[i-start]<0)
2272    {
2273      ord_struct.ord_typ=ro_wp_neg;
2274      break;
2275    }
2276  }
2277}
2278
2279static void rO_LexVars(int &place, int &bitplace, int start, int end,
2280  int &prev_ord, long *o,int *v, int bits, int opt_var)
2281{
2282  // a block of variables v_start..v_end with lex order, ordsgn 1
2283  int k;
2284  int incr=1;
2285  if(prev_ord==-1) rO_Align(place,bitplace);
2286
2287  if (start>end)
2288  {
2289    incr=-1;
2290  }
2291  for(k=start;;k+=incr)
2292  {
2293    bitplace-=bits;
2294    if (bitplace < 0) { bitplace=BITS_PER_LONG-bits; place++; }
2295    o[place]=1;
2296    v[k]= place | (bitplace << 24);
2297    if (k==end) break;
2298  }
2299  prev_ord=1;
2300  if (opt_var!= -1)
2301  {
2302    assume((opt_var == end+1) ||(opt_var == end-1));
2303    if((opt_var != end+1) &&(opt_var != end-1)) WarnS("hier-2");
2304    int save_bitplace=bitplace;
2305    bitplace-=bits;
2306    if (bitplace < 0)
2307    {
2308      bitplace=save_bitplace;
2309      return;
2310    }
2311    // there is enough space for the optional var
2312    v[opt_var]=place | (bitplace << 24);
2313  }
2314}
2315
2316static void rO_LexVars_neg(int &place, int &bitplace, int start, int end,
2317  int &prev_ord, long *o,int *v, int bits, int opt_var)
2318{
2319  // a block of variables v_start..v_end with lex order, ordsgn -1
2320  int k;
2321  int incr=1;
2322  if(prev_ord==1) rO_Align(place,bitplace);
2323
2324  if (start>end)
2325  {
2326    incr=-1;
2327  }
2328  for(k=start;;k+=incr)
2329  {
2330    bitplace-=bits;
2331    if (bitplace < 0) { bitplace=BITS_PER_LONG-bits; place++; }
2332    o[place]=-1;
2333    v[k]=place | (bitplace << 24);
2334    if (k==end) break;
2335  }
2336  prev_ord=-1;
2337//  #if 0
2338  if (opt_var!= -1)
2339  {
2340    assume((opt_var == end+1) ||(opt_var == end-1));
2341    if((opt_var != end+1) &&(opt_var != end-1)) WarnS("hier-1");
2342    int save_bitplace=bitplace;
2343    bitplace-=bits;
2344    if (bitplace < 0)
2345    {
2346      bitplace=save_bitplace;
2347      return;
2348    }
2349    // there is enough space for the optional var
2350    v[opt_var]=place | (bitplace << 24);
2351  }
2352//  #endif
2353}
2354
2355static void rO_Syzcomp(int &place, int &bitplace, int &prev_ord,
2356    long *o, sro_ord &ord_struct)
2357{
2358  // ordering is derived from component number
2359  rO_Align(place,bitplace);
2360  ord_struct.ord_typ=ro_syzcomp;
2361  ord_struct.data.syzcomp.place=place;
2362  ord_struct.data.syzcomp.Components=NULL;
2363  ord_struct.data.syzcomp.ShiftedComponents=NULL;
2364  o[place]=1;
2365  prev_ord=1;
2366  place++;
2367  rO_Align(place,bitplace);
2368}
2369
2370static void rO_Syz(int &place, int &bitplace, int &prev_ord,
2371    int syz_comp, long *o, sro_ord &ord_struct)
2372{
2373  // ordering is derived from component number
2374  // let's reserve one Exponent_t for it
2375  if ((prev_ord== 1) || (bitplace!=BITS_PER_LONG))
2376    rO_Align(place,bitplace);
2377  ord_struct.ord_typ=ro_syz;
2378  ord_struct.data.syz.place=place;
2379  ord_struct.data.syz.limit=syz_comp;
2380  if (syz_comp>0)
2381    ord_struct.data.syz.syz_index = (int*) omAlloc0((syz_comp+1)*sizeof(int));
2382  else
2383    ord_struct.data.syz.syz_index = NULL;
2384  ord_struct.data.syz.curr_index = 1;
2385  o[place]= -1;
2386  prev_ord=-1;
2387  place++;
2388}
2389
2390#ifndef SING_NDEBUG
2391# define MYTEST 0
2392#else /* ifndef SING_NDEBUG */
2393# define MYTEST 0
2394#endif /* ifndef SING_NDEBUG */
2395
2396static void rO_ISPrefix(int &place, int &bitplace, int &prev_ord,
2397    long *o, int /*N*/, int *v, sro_ord &ord_struct)
2398{
2399  if ((prev_ord== 1) || (bitplace!=BITS_PER_LONG))
2400    rO_Align(place,bitplace);
2401  // since we add something afterwards - it's better to start with anew!?
2402
2403  ord_struct.ord_typ = ro_isTemp;
2404  ord_struct.data.isTemp.start = place;
2405  ord_struct.data.isTemp.pVarOffset = (int *)omMemDup(v);
2406  ord_struct.data.isTemp.suffixpos = -1;
2407
2408  // We will act as rO_Syz on our own!!!
2409  // Here we allocate an exponent as a level placeholder
2410  o[place]= -1;
2411  prev_ord=-1;
2412  place++;
2413}
2414static void rO_ISSuffix(int &place, int &bitplace, int &prev_ord, long *o,
2415  int N, int *v, sro_ord *tmp_typ, int &typ_i, int sgn)
2416{
2417
2418  // Let's find previous prefix:
2419  int typ_j = typ_i - 1;
2420  while(typ_j >= 0)
2421  {
2422    if( tmp_typ[typ_j].ord_typ == ro_isTemp)
2423      break;
2424    typ_j --;
2425  }
2426
2427  assume( typ_j >= 0 );
2428
2429  if( typ_j < 0 ) // Found NO prefix!!! :(
2430    return;
2431
2432  assume( tmp_typ[typ_j].ord_typ == ro_isTemp );
2433
2434  // Get saved state:
2435  const int start = tmp_typ[typ_j].data.isTemp.start;
2436  int *pVarOffset = tmp_typ[typ_j].data.isTemp.pVarOffset;
2437
2438/*
2439  // shift up all blocks
2440  while(typ_j < (typ_i-1))
2441  {
2442    tmp_typ[typ_j] = tmp_typ[typ_j+1];
2443    typ_j++;
2444  }
2445  typ_j = typ_i - 1; // No increment for typ_i
2446*/
2447  tmp_typ[typ_j].data.isTemp.suffixpos = typ_i;
2448
2449  // Let's keep that dummy for now...
2450  typ_j = typ_i; // the typ to change!
2451  typ_i++; // Just for now...
2452
2453
2454  for( int i = 0; i <= N; i++ ) // Note [0] == component !!! No Skip?
2455  {
2456    // Was i-th variable allocated inbetween?
2457    if( v[i] != pVarOffset[i] )
2458    {
2459      pVarOffset[i] = v[i]; // Save for later...
2460      v[i] = -1; // Undo!
2461      assume( pVarOffset[i] != -1 );
2462    }
2463    else
2464      pVarOffset[i] = -1; // No change here...
2465  }
2466
2467  if( pVarOffset[0] != -1 )
2468    pVarOffset[0] &= 0x0fff;
2469
2470  sro_ord &ord_struct = tmp_typ[typ_j];
2471
2472
2473  ord_struct.ord_typ = ro_is;
2474  ord_struct.data.is.start = start;
2475  ord_struct.data.is.end   = place;
2476  ord_struct.data.is.pVarOffset = pVarOffset;
2477
2478
2479  // What about component???
2480//   if( v[0] != -1 ) // There is a component already...???
2481//     if( o[ v[0] & 0x0fff ] == sgn )
2482//     {
2483//       pVarOffset[0] = -1; // NEVER USED Afterwards...
2484//       return;
2485//     }
2486
2487
2488  // Moreover: we need to allocate the module component (v[0]) here!
2489  if( v[0] == -1) // It's possible that there was module component v0 at the begining (before prefix)!
2490  {
2491    // Start with a whole long exponent
2492    if( bitplace != BITS_PER_LONG )
2493      rO_Align(place, bitplace);
2494
2495    assume( bitplace == BITS_PER_LONG );
2496    bitplace -= BITS_PER_LONG;
2497    assume(bitplace == 0);
2498    v[0] = place | (bitplace << 24); // Never mind whether pVarOffset[0] > 0!!!
2499    o[place] = sgn; // Singnum for component ordering
2500    prev_ord = sgn;
2501  }
2502}
2503
2504
2505static unsigned long rGetExpSize(unsigned long bitmask, int & bits)
2506{
2507  if (bitmask == 0)
2508  {
2509    bits=16; bitmask=0xffff;
2510  }
2511  else if (bitmask <= 1L)
2512  {
2513    bits=1; bitmask = 1L;
2514  }
2515  else if (bitmask <= 3L)
2516  {
2517    bits=2; bitmask = 3L;
2518  }
2519  else if (bitmask <= 7L)
2520  {
2521    bits=3; bitmask=7L;
2522  }
2523  else if (bitmask <= 0xfL)
2524  {
2525    bits=4; bitmask=0xfL;
2526  }
2527  else if (bitmask <= 0x1fL)
2528  {
2529    bits=5; bitmask=0x1fL;
2530  }
2531  else if (bitmask <= 0x3fL)
2532  {
2533    bits=6; bitmask=0x3fL;
2534  }
2535#if SIZEOF_LONG == 8
2536  else if (bitmask <= 0x7fL)
2537  {
2538    bits=7; bitmask=0x7fL; /* 64 bit longs only */
2539  }
2540#endif
2541  else if (bitmask <= 0xffL)
2542  {
2543    bits=8; bitmask=0xffL;
2544  }
2545#if SIZEOF_LONG == 8
2546  else if (bitmask <= 0x1ffL)
2547  {
2548    bits=9; bitmask=0x1ffL; /* 64 bit longs only */
2549  }
2550#endif
2551  else if (bitmask <= 0x3ffL)
2552  {
2553    bits=10; bitmask=0x3ffL;
2554  }
2555#if SIZEOF_LONG == 8
2556  else if (bitmask <= 0xfffL)
2557  {
2558    bits=12; bitmask=0xfff; /* 64 bit longs only */
2559  }
2560#endif
2561  else if (bitmask <= 0xffffL)
2562  {
2563    bits=16; bitmask=0xffffL;
2564  }
2565#if SIZEOF_LONG == 8
2566  else if (bitmask <= 0xfffffL)
2567  {
2568    bits=20; bitmask=0xfffffL; /* 64 bit longs only */
2569  }
2570  else if (bitmask <= 0xffffffffL)
2571  {
2572    bits=32; bitmask=0xffffffffL;
2573  }
2574  else if (bitmask <= 0x7fffffffffffffffL)
2575  {
2576    bits=63; bitmask=0x7fffffffffffffffL; /* for overflow tests*/
2577  }
2578  else
2579  {
2580    bits=63; bitmask=0x7fffffffffffffffL; /* for overflow tests*/
2581  }
2582#else
2583  else if (bitmask <= 0x7fffffff)
2584  {
2585    bits=31; bitmask=0x7fffffff; /* for overflow tests*/
2586  }
2587  else
2588  {
2589    bits=31; bitmask=0x7fffffffL; /* for overflow tests*/
2590  }
2591#endif
2592  return bitmask;
2593}
2594
2595/*2
2596* optimize rGetExpSize for a block of N variables, exp <=bitmask
2597*/
2598unsigned long rGetExpSize(unsigned long bitmask, int & bits, int N)
2599{
2600#if SIZEOF_LONG == 8
2601  if (N<4) N=4;
2602#else
2603  if (N<2) N=2;
2604#endif
2605  bitmask =rGetExpSize(bitmask, bits);
2606  int vars_per_long=BIT_SIZEOF_LONG/bits;
2607  int bits1;
2608  loop
2609  {
2610    if (bits == BIT_SIZEOF_LONG-1)
2611    {
2612      bits =  BIT_SIZEOF_LONG - 1;
2613      return LONG_MAX;
2614    }
2615    unsigned long bitmask1 =rGetExpSize(bitmask+1, bits1);
2616    int vars_per_long1=BIT_SIZEOF_LONG/bits1;
2617    if ((((N+vars_per_long-1)/vars_per_long) ==
2618         ((N+vars_per_long1-1)/vars_per_long1)))
2619    {
2620      vars_per_long=vars_per_long1;
2621      bits=bits1;
2622      bitmask=bitmask1;
2623    }
2624    else
2625    {
2626      return bitmask; /* and bits */
2627    }
2628  }
2629}
2630
2631
2632/*2
2633 * create a copy of the ring r, which must be equivalent to currRing
2634 * used for std computations
2635 * may share data structures with currRing
2636 * DOES CALL rComplete
2637 */
2638ring rModifyRing(ring r, BOOLEAN omit_degree,
2639                         BOOLEAN try_omit_comp,
2640                         unsigned long exp_limit)
2641{
2642  assume (r != NULL );
2643  assume (exp_limit > 1);
2644  BOOLEAN need_other_ring;
2645  BOOLEAN omitted_degree = FALSE;
2646
2647  int iNeedInducedOrderingSetup = 0; ///< How many induced ordering block do we have?
2648  int bits;
2649
2650  exp_limit=rGetExpSize(exp_limit, bits, r->N);
2651  need_other_ring = (exp_limit != r->bitmask);
2652
2653  int nblocks=rBlocks(r);
2654  rRingOrder_t *order=(rRingOrder_t*)omAlloc0((nblocks+1)*sizeof(rRingOrder_t));
2655  int *block0=(int*)omAlloc0((nblocks+1)*sizeof(int));
2656  int *block1=(int*)omAlloc0((nblocks+1)*sizeof(int));
2657  int **wvhdl=(int**)omAlloc0((nblocks+1)*sizeof(int *));
2658
2659  int i=0;
2660  int j=0; /*  i index in r, j index in res */
2661
2662  for( rRingOrder_t r_ord=r->order[i]; (r_ord != (rRingOrder_t)0) && (i < nblocks); j++, r_ord=r->order[++i])
2663  {
2664    BOOLEAN copy_block_index=TRUE;
2665
2666    if (r->block0[i]==r->block1[i])
2667    {
2668      switch(r_ord)
2669      {
2670        case ringorder_wp:
2671        case ringorder_dp:
2672        case ringorder_Wp:
2673        case ringorder_Dp:
2674          r_ord=ringorder_lp;
2675          break;
2676        case ringorder_Ws:
2677        case ringorder_Ds:
2678        case ringorder_ws:
2679        case ringorder_ds:
2680          r_ord=ringorder_ls;
2681          break;
2682        default:
2683          break;
2684      }
2685    }
2686    switch(r_ord)
2687    {
2688      case ringorder_S:
2689      {
2690#ifndef SING_NDEBUG
2691        Warn("Error: unhandled ordering in rModifyRing: ringorder_S = [%d]", r_ord);
2692#endif
2693        order[j]=r_ord; /*r->order[i];*/
2694        break;
2695      }
2696      case ringorder_C:
2697      case ringorder_c:
2698        if (!try_omit_comp)
2699        {
2700          order[j]=r_ord; /*r->order[i]*/;
2701        }
2702        else
2703        {
2704          j--;
2705          need_other_ring=TRUE;
2706          try_omit_comp=FALSE;
2707          copy_block_index=FALSE;
2708        }
2709        break;
2710      case ringorder_wp:
2711      case ringorder_dp:
2712      case ringorder_ws:
2713      case ringorder_ds:
2714        if(!omit_degree)
2715        {
2716          order[j]=r_ord; /*r->order[i]*/;
2717        }
2718        else
2719        {
2720          order[j]=ringorder_rs;
2721          need_other_ring=TRUE;
2722          omit_degree=FALSE;
2723          omitted_degree = TRUE;
2724        }
2725        break;
2726      case ringorder_Wp:
2727      case ringorder_Dp:
2728      case ringorder_Ws:
2729      case ringorder_Ds:
2730        if(!omit_degree)
2731        {
2732          order[j]=r_ord; /*r->order[i];*/
2733        }
2734        else
2735        {
2736          order[j]=ringorder_lp;
2737          need_other_ring=TRUE;
2738          omit_degree=FALSE;
2739          omitted_degree = TRUE;
2740        }
2741        break;
2742      case ringorder_IS:
2743      {
2744        if (try_omit_comp)
2745        {
2746          // tried, but cannot omit component due to the ordering block [%d]: %d (ringorder_IS)", i, r_ord
2747          try_omit_comp = FALSE;
2748        }
2749        order[j]=r_ord; /*r->order[i];*/
2750        iNeedInducedOrderingSetup++;
2751        break;
2752      }
2753      case ringorder_s:
2754      {
2755        assume((i == 0) && (j == 0));
2756        if (try_omit_comp)
2757        {
2758          // tried, but cannot omit component due to the ordering block [%d]: %d (ringorder_s)", i, r_ord
2759          try_omit_comp = FALSE;
2760        }
2761        order[j]=r_ord; /*r->order[i];*/
2762        break;
2763      }
2764      default:
2765        order[j]=r_ord; /*r->order[i];*/
2766        break;
2767    }
2768    if (copy_block_index)
2769    {
2770      block0[j]=r->block0[i];
2771      block1[j]=r->block1[i];
2772      wvhdl[j]=r->wvhdl[i];
2773    }
2774
2775    // order[j]=ringorder_no; //  done by omAlloc0
2776  }
2777  if(!need_other_ring)
2778  {
2779    omFreeSize(order,(nblocks+1)*sizeof(rRingOrder_t));
2780    omFreeSize(block0,(nblocks+1)*sizeof(int));
2781    omFreeSize(block1,(nblocks+1)*sizeof(int));
2782    omFreeSize(wvhdl,(nblocks+1)*sizeof(int *));
2783    return r;
2784  }
2785  ring res=(ring)omAlloc0Bin(sip_sring_bin);
2786  *res = *r;
2787
2788#ifdef HAVE_PLURAL
2789  res->GetNC() = NULL;
2790#endif
2791
2792  // res->qideal, res->idroot ???
2793  res->wvhdl=wvhdl;
2794  res->order=order;
2795  res->block0=block0;
2796  res->block1=block1;
2797  res->bitmask=exp_limit;
2798  //int tmpref=r->cf->ref0;
2799  rComplete(res, 1);
2800  //r->cf->ref=tmpref;
2801
2802  // adjust res->pFDeg: if it was changed globally, then
2803  // it must also be changed for new ring
2804  if (r->pFDegOrig != res->pFDegOrig &&
2805           rOrd_is_WeightedDegree_Ordering(r))
2806  {
2807    // still might need adjustment for weighted orderings
2808    // and omit_degree
2809    res->firstwv = r->firstwv;
2810    res->firstBlockEnds = r->firstBlockEnds;
2811    res->pFDeg = res->pFDegOrig = p_WFirstTotalDegree;
2812  }
2813  if (omitted_degree)
2814    res->pLDeg = r->pLDegOrig;
2815
2816  rOptimizeLDeg(res); // also sets res->pLDegOrig
2817
2818  // set syzcomp
2819  if (res->typ != NULL)
2820  {
2821    if( res->typ[0].ord_typ == ro_syz) // "s" Always on [0] place!
2822    {
2823      res->typ[0] = r->typ[0]; // Copy struct!? + setup the same limit!
2824
2825      if (r->typ[0].data.syz.limit > 0)
2826      {
2827        res->typ[0].data.syz.syz_index
2828          = (int*) omAlloc((r->typ[0].data.syz.limit +1)*sizeof(int));
2829        memcpy(res->typ[0].data.syz.syz_index, r->typ[0].data.syz.syz_index,
2830              (r->typ[0].data.syz.limit +1)*sizeof(int));
2831      }
2832    }
2833
2834    if( iNeedInducedOrderingSetup > 0 )
2835    {
2836      for(j = 0, i = 0; (i < nblocks) && (iNeedInducedOrderingSetup > 0); i++)
2837        if( res->typ[i].ord_typ == ro_is ) // Search for suffixes!
2838        {
2839          ideal F = idrHeadR(r->typ[i].data.is.F, r, res); // Copy F from r into res!
2840          assume(
2841            rSetISReference( res,
2842              F,  // WILL BE COPIED!
2843              r->typ[i].data.is.limit,
2844              j++
2845              )
2846            );
2847          id_Delete(&F, res);
2848          iNeedInducedOrderingSetup--;
2849        }
2850    } // Process all induced Ordering blocks! ...
2851  }
2852  // the special case: homog (omit_degree) and 1 block rs: that is global:
2853  // it comes from dp
2854  res->OrdSgn=r->OrdSgn;
2855
2856
2857#ifdef HAVE_PLURAL
2858  if (rIsPluralRing(r))
2859  {
2860    if ( nc_rComplete(r, res, false) ) // no qideal!
2861    {
2862#ifndef SING_NDEBUG
2863      WarnS("error in nc_rComplete");
2864#endif
2865      // cleanup?
2866
2867//      rDelete(res);
2868//      return r;
2869
2870      // just go on..
2871    }
2872
2873    if( rIsSCA(r) )
2874    {
2875      if( !sca_Force(res, scaFirstAltVar(r), scaLastAltVar(r)) )
2876      WarnS("error in sca_Force!");
2877    }
2878  }
2879#endif
2880
2881  return res;
2882}
2883
2884// construct Wp,C ring
2885ring rModifyRing_Wp(ring r, int* weights)
2886{
2887  ring res=(ring)omAlloc0Bin(sip_sring_bin);
2888  *res = *r;
2889#ifdef HAVE_PLURAL
2890  res->GetNC() = NULL;
2891#endif
2892
2893  /*weights: entries for 3 blocks: NULL*/
2894  res->wvhdl = (int **)omAlloc0(3 * sizeof(int *));
2895  /*order: Wp,C,0*/
2896  res->order = (rRingOrder_t *) omAlloc(3 * sizeof(rRingOrder_t *));
2897  res->block0 = (int *)omAlloc0(3 * sizeof(int *));
2898  res->block1 = (int *)omAlloc0(3 * sizeof(int *));
2899  /* ringorder Wp for the first block: var 1..r->N */
2900  res->order[0]  = ringorder_Wp;
2901  res->block0[0] = 1;
2902  res->block1[0] = r->N;
2903  res->wvhdl[0] = weights;
2904  /* ringorder C for the second block: no vars */
2905  res->order[1]  = ringorder_C;
2906  /* the last block: everything is 0 */
2907  res->order[2]  = (rRingOrder_t)0;
2908
2909  //int tmpref=r->cf->ref;
2910  rComplete(res, 1);
2911  //r->cf->ref=tmpref;
2912#ifdef HAVE_PLURAL
2913  if (rIsPluralRing(r))
2914  {
2915    if ( nc_rComplete(r, res, false) ) // no qideal!
2916    {
2917#ifndef SING_NDEBUG
2918      WarnS("error in nc_rComplete");
2919#endif
2920      // cleanup?
2921
2922//      rDelete(res);
2923//      return r;
2924
2925      // just go on..
2926    }
2927  }
2928#endif
2929  return res;
2930}
2931
2932// construct lp, C ring with r->N variables, r->names vars....
2933ring rModifyRing_Simple(ring r, BOOLEAN ommit_degree, BOOLEAN ommit_comp, unsigned long exp_limit, BOOLEAN &simple)
2934{
2935  simple=TRUE;
2936  if (!rHasSimpleOrder(r))
2937  {
2938    simple=FALSE; // sorting needed
2939    assume (r != NULL );
2940    assume (exp_limit > 1);
2941    int bits;
2942
2943    exp_limit=rGetExpSize(exp_limit, bits, r->N);
2944
2945    int nblocks=1+(ommit_comp!=0);
2946    rRingOrder_t *order=(rRingOrder_t*)omAlloc0((nblocks+1)*sizeof(rRingOrder_t));
2947    int *block0=(int*)omAlloc0((nblocks+1)*sizeof(int));
2948    int *block1=(int*)omAlloc0((nblocks+1)*sizeof(int));
2949    int **wvhdl=(int**)omAlloc0((nblocks+1)*sizeof(int *));
2950
2951    order[0]=ringorder_lp;
2952    block0[0]=1;
2953    block1[0]=r->N;
2954    if (!ommit_comp)
2955    {
2956      order[1]=ringorder_C;
2957    }
2958    ring res=(ring)omAlloc0Bin(sip_sring_bin);
2959    *res = *r;
2960#ifdef HAVE_PLURAL
2961    res->GetNC() = NULL;
2962#endif
2963    // res->qideal, res->idroot ???
2964    res->wvhdl=wvhdl;
2965    res->order=order;
2966    res->block0=block0;
2967    res->block1=block1;
2968    res->bitmask=exp_limit;
2969    //int tmpref=r->cf->ref;
2970    rComplete(res, 1);
2971    //r->cf->ref=tmpref;
2972
2973#ifdef HAVE_PLURAL
2974    if (rIsPluralRing(r))
2975    {
2976      if ( nc_rComplete(r, res, false) ) // no qideal!
2977      {
2978#ifndef SING_NDEBUG
2979        WarnS("error in nc_rComplete");
2980#endif
2981        // cleanup?
2982
2983//      rDelete(res);
2984//      return r;
2985
2986      // just go on..
2987      }
2988    }
2989#endif
2990
2991    rOptimizeLDeg(res);
2992
2993    return res;
2994  }
2995  return rModifyRing(r, ommit_degree, ommit_comp, exp_limit);
2996}
2997
2998void rKillModifiedRing(ring r)
2999{
3000  rUnComplete(r);
3001  omFree(r->order);
3002  omFree(r->block0);
3003  omFree(r->block1);
3004  omFree(r->wvhdl);
3005  omFreeBin(r,sip_sring_bin);
3006}
3007
3008void rKillModified_Wp_Ring(ring r)
3009{
3010  rUnComplete(r);
3011  omFree(r->order);
3012  omFree(r->block0);
3013  omFree(r->block1);
3014  omFree(r->wvhdl[0]);
3015  omFree(r->wvhdl);
3016  omFreeBin(r,sip_sring_bin);
3017}
3018
3019static void rSetOutParams(ring r)
3020{
3021  r->VectorOut = (r->order[0] == ringorder_c);
3022  if (rIsNCRing(r))
3023    r->CanShortOut=FALSE;
3024  else
3025  {
3026    r->CanShortOut = TRUE;
3027    int i;
3028    if (rParameter(r)!=NULL)
3029    {
3030      for (i=0;i<rPar(r);i++)
3031      {
3032        if(strlen(rParameter(r)[i])>1)
3033        {
3034          r->CanShortOut=FALSE;
3035          break;
3036        }
3037      }
3038    }
3039    if (r->CanShortOut)
3040    {
3041      // Hmm... sometimes (e.g., from maGetPreimage) new variables
3042      // are introduced, but their names are never set
3043      // hence, we do the following awkward trick
3044      int N = omSizeOfAddr(r->names)/sizeof(char_ptr);
3045      if (r->N < N) N = r->N;
3046
3047      for (i=(N-1);i>=0;i--)
3048      {
3049        if(r->names[i] != NULL && strlen(r->names[i])>1)
3050        {
3051          r->CanShortOut=FALSE;
3052          break;
3053        }
3054      }
3055    }
3056  }
3057  r->ShortOut = r->CanShortOut;
3058
3059  assume( !( !r->CanShortOut && r->ShortOut ) );
3060}
3061
3062static void rSetFirstWv(ring r, int i, rRingOrder_t* order, int* block1, int** wvhdl)
3063{
3064  // cheat for ringorder_aa
3065  if (order[i] == ringorder_aa)
3066    i++;
3067  if(block1[i]!=r->N) r->LexOrder=TRUE;
3068  r->firstBlockEnds=block1[i];
3069  r->firstwv = wvhdl[i];
3070  if ((order[i]== ringorder_ws)
3071  || (order[i]==ringorder_Ws)
3072  || (order[i]== ringorder_wp)
3073  || (order[i]==ringorder_Wp)
3074  || (order[i]== ringorder_a)
3075   /*|| (order[i]==ringorder_A)*/)
3076  {
3077    int j;
3078    for(j=block1[i]-r->block0[i];j>=0;j--)
3079    {
3080      if (r->firstwv[j]==0) r->LexOrder=TRUE;
3081    }
3082  }
3083  else if (order[i]==ringorder_a64)
3084  {
3085    int j;
3086    int64 *w=rGetWeightVec(r);
3087    for(j=block1[i]-r->block0[i];j>=0;j--)
3088    {
3089      if (w[j]==0) r->LexOrder=TRUE;
3090    }
3091  }
3092}
3093
3094static void rOptimizeLDeg(ring r)
3095{
3096  if (r->pFDeg == p_Deg)
3097  {
3098    if (r->pLDeg == pLDeg1)
3099      r->pLDeg = pLDeg1_Deg;
3100    if (r->pLDeg == pLDeg1c)
3101      r->pLDeg = pLDeg1c_Deg;
3102  }
3103  else if (r->pFDeg == p_Totaldegree)
3104  {
3105    if (r->pLDeg == pLDeg1)
3106      r->pLDeg = pLDeg1_Totaldegree;
3107    if (r->pLDeg == pLDeg1c)
3108      r->pLDeg = pLDeg1c_Totaldegree;
3109  }
3110  else if (r->pFDeg == p_WFirstTotalDegree)
3111  {
3112    if (r->pLDeg == pLDeg1)
3113      r->pLDeg = pLDeg1_WFirstTotalDegree;
3114    if (r->pLDeg == pLDeg1c)
3115      r->pLDeg = pLDeg1c_WFirstTotalDegree;
3116  }
3117  r->pLDegOrig = r->pLDeg;
3118}
3119
3120// set pFDeg, pLDeg, requires OrdSgn already set
3121static void rSetDegStuff(ring r)
3122{
3123  rRingOrder_t* order = r->order;
3124  int* block0 = r->block0;
3125  int* block1 = r->block1;
3126  int** wvhdl = r->wvhdl;
3127
3128  if (order[0]==ringorder_S ||order[0]==ringorder_s || order[0]==ringorder_IS)
3129  {
3130    order++;
3131    block0++;
3132    block1++;
3133    wvhdl++;
3134  }
3135  r->LexOrder = FALSE;
3136  r->pFDeg = p_Totaldegree;
3137  r->pLDeg = (r->OrdSgn == 1 ? pLDegb : pLDeg0);
3138
3139  /*======== ordering type is (am,_) ==================*/
3140  if (order[0]==ringorder_am)
3141  {
3142    for(int ii=block0[0];ii<=block1[0];ii++)
3143      if (wvhdl[0][ii-1]<0) { r->MixedOrder=2;break;}
3144    r->LexOrder=FALSE;
3145    for(int ii=block0[0];ii<=block1[0];ii++)
3146      if (wvhdl[0][ii-1]==0) { r->LexOrder=TRUE;break;}
3147    if ((block0[0]==1)&&(block1[0]==r->N))
3148    {
3149      r->pFDeg = p_Deg;
3150      r->pLDeg = pLDeg1c_Deg;
3151    }
3152    else
3153   {
3154      r->pFDeg = p_WTotaldegree;
3155      r->LexOrder=TRUE;
3156      r->pLDeg = pLDeg1c_WFirstTotalDegree;
3157    }
3158    r->firstwv = wvhdl[0];
3159  }
3160  /*======== ordering type is (_,c) =========================*/
3161  else if ((order[0]==ringorder_unspec) || (order[1] == 0)
3162      ||(
3163    ((order[1]==ringorder_c)||(order[1]==ringorder_C)
3164     ||(order[1]==ringorder_S)
3165     ||(order[1]==ringorder_s))
3166    && (order[0]!=ringorder_M)
3167    && (order[2]==0))
3168    )
3169  {
3170    if (r->OrdSgn == -1) r->pLDeg = pLDeg0c;
3171    if ((order[0] == ringorder_lp)
3172    || (order[0] == ringorder_ls)
3173    || (order[0] == ringorder_rp)
3174    || (order[0] == ringorder_rs))
3175    {
3176      r->LexOrder=TRUE;
3177      r->pLDeg = pLDeg1c;
3178      r->pFDeg = p_Totaldegree;
3179    }
3180    else if ((order[0] == ringorder_a)
3181    || (order[0] == ringorder_wp)
3182    || (order[0] == ringorder_Wp))
3183    {
3184      r->pFDeg = p_WFirstTotalDegree;
3185    }
3186    else if ((order[0] == ringorder_ws)
3187    || (order[0] == ringorder_Ws))
3188    {
3189      for(int ii=block0[0];ii<=block1[0];ii++)
3190      {
3191        if (wvhdl[0][ii-1]<0) { r->MixedOrder=2;break;}
3192      }
3193      if (r->MixedOrder==0)
3194      {
3195        if ((block0[0]==1)&&(block1[0]==r->N))
3196          r->pFDeg = p_WTotaldegree;
3197        else
3198          r->pFDeg = p_WFirstTotalDegree;
3199      }
3200      else
3201        r->pFDeg = p_Totaldegree;
3202    }
3203    r->firstBlockEnds=block1[0];
3204    r->firstwv = wvhdl[0];
3205  }
3206  /*======== ordering type is (c,_) =========================*/
3207  else if (((order[0]==ringorder_c)
3208            ||(order[0]==ringorder_C)
3209            ||(order[0]==ringorder_S)
3210            ||(order[0]==ringorder_s))
3211  && (order[1]!=ringorder_M)
3212  &&  (order[2]==0))
3213  {
3214    if ((order[1] == ringorder_lp)
3215    || (order[1] == ringorder_ls)
3216    || (order[1] == ringorder_rp)
3217    || order[1] == ringorder_rs)
3218    {
3219      r->LexOrder=TRUE;
3220      r->pLDeg = pLDeg1c;
3221      r->pFDeg = p_Totaldegree;
3222    }
3223    r->firstBlockEnds=block1[1];
3224    if (wvhdl!=NULL) r->firstwv = wvhdl[1];
3225    if ((order[1] == ringorder_a)
3226    || (order[1] == ringorder_wp)
3227    || (order[1] == ringorder_Wp))
3228      r->pFDeg = p_WFirstTotalDegree;
3229    else if ((order[1] == ringorder_ws)
3230    || (order[1] == ringorder_Ws))
3231    {
3232      for(int ii=block0[1];ii<=block1[1];ii++)
3233        if (wvhdl[1][ii-1]<0) { r->MixedOrder=2;break;}
3234      if (r->MixedOrder==FALSE)
3235        r->pFDeg = p_WFirstTotalDegree;
3236      else
3237        r->pFDeg = p_Totaldegree;
3238    }
3239  }
3240  /*------- more than one block ----------------------*/
3241  else
3242  {
3243    if ((r->VectorOut)||(order[0]==ringorder_C)||(order[0]==ringorder_S)||(order[0]==ringorder_s))
3244    {
3245      rSetFirstWv(r, 1, order, block1, wvhdl);
3246    }
3247    else
3248      rSetFirstWv(r, 0, order, block1, wvhdl);
3249
3250    if ((order[0]!=ringorder_c)
3251        && (order[0]!=ringorder_C)
3252        && (order[0]!=ringorder_S)
3253        && (order[0]!=ringorder_s))
3254    {
3255      r->pLDeg = pLDeg1c;
3256    }
3257    else
3258    {
3259      r->pLDeg = pLDeg1;
3260    }
3261    r->pFDeg = p_WTotaldegree; // may be improved: p_Totaldegree for lp/dp/ls/.. blocks
3262  }
3263
3264  if (rOrd_is_Totaldegree_Ordering(r)
3265  || rOrd_is_WeightedDegree_Ordering(r))
3266  {
3267    if(r->MixedOrder==FALSE)
3268      r->pFDeg = p_Deg;
3269    else
3270      r->pFDeg = p_Totaldegree;
3271  }
3272
3273  if( rGetISPos(0, r) != -1 ) // Are there Schreyer induced blocks?
3274  {
3275#ifndef SING_NDEBUG
3276      assume( r->pFDeg == p_Deg || r->pFDeg == p_WTotaldegree || r->pFDeg == p_Totaldegree);
3277#endif
3278
3279    r->pLDeg = pLDeg1; // ?
3280  }
3281
3282  r->pFDegOrig = r->pFDeg;
3283  // NOTE: this leads to wrong ecart during std
3284  // in Old/sre.tst
3285  rOptimizeLDeg(r); // also sets r->pLDegOrig
3286}
3287
3288/*2
3289* set NegWeightL_Size, NegWeightL_Offset
3290*/
3291static void rSetNegWeight(ring r)
3292{
3293  int i,l;
3294  if (r->typ!=NULL)
3295  {
3296    l=0;
3297    for(i=0;i<r->OrdSize;i++)
3298    {
3299      if((r->typ[i].ord_typ==ro_wp_neg)
3300      ||(r->typ[i].ord_typ==ro_am))
3301        l++;
3302    }
3303    if (l>0)
3304    {
3305      r->NegWeightL_Size=l;
3306      r->NegWeightL_Offset=(int *) omAlloc(l*sizeof(int));
3307      l=0;
3308      for(i=0;i<r->OrdSize;i++)
3309      {
3310        if(r->typ[i].ord_typ==ro_wp_neg)
3311        {
3312          r->NegWeightL_Offset[l]=r->typ[i].data.wp.place;
3313          l++;
3314        }
3315        else if(r->typ[i].ord_typ==ro_am)
3316        {
3317          r->NegWeightL_Offset[l]=r->typ[i].data.am.place;
3318          l++;
3319        }
3320      }
3321      return;
3322    }
3323  }
3324  r->NegWeightL_Size = 0;
3325  r->NegWeightL_Offset = NULL;
3326}
3327
3328static void rSetOption(ring r)
3329{
3330  // set redthrough
3331  if (!TEST_OPT_OLDSTD && r->OrdSgn == 1 && ! r->LexOrder)
3332    r->options |= Sy_bit(OPT_REDTHROUGH);
3333  else
3334    r->options &= ~Sy_bit(OPT_REDTHROUGH);
3335
3336  // set intStrategy
3337  if ( (r->cf->extRing!=NULL)
3338      || rField_is_Q(r)
3339      || rField_is_Ring(r)
3340  )
3341    r->options |= Sy_bit(OPT_INTSTRATEGY);
3342  else
3343    r->options &= ~Sy_bit(OPT_INTSTRATEGY);
3344
3345  // set redTail
3346  if (r->LexOrder || r->OrdSgn == -1 || (r->cf->extRing!=NULL))
3347    r->options &= ~Sy_bit(OPT_REDTAIL);
3348  else
3349    r->options |= Sy_bit(OPT_REDTAIL);
3350}
3351
3352static void rCheckOrdSgn(ring r,int i/*last block*/);
3353
3354/* -------------------------------------------------------- */
3355/*2
3356* change all global variables to fit the description of the new ring
3357*/
3358
3359void p_SetGlobals(const ring r, BOOLEAN complete)
3360{
3361// // //  if (r->ppNoether!=NULL) p_Delete(&r->ppNoether,r); // ???
3362
3363  r->pLexOrder=r->LexOrder;
3364  if (complete)
3365  {
3366    si_opt_1 &= ~ TEST_RINGDEP_OPTS;
3367    si_opt_1 |= r->options;
3368  }
3369}
3370
3371static inline int sign(int x) { return (x > 0) - (x < 0);}
3372BOOLEAN rOrd_is_MixedDegree_Ordering(ring r)
3373{
3374  int i;
3375  poly p=p_One(r);
3376  p_SetExp(p,1,1,r);
3377  p_Setm(p,r);
3378  int vz=sign(p_FDeg(p,r));
3379  for(i=2;i<=rVar(r);i++)
3380  {
3381    p_SetExp(p,i-1,0,r);
3382    p_SetExp(p,i,1,r);
3383    p_Setm(p,r);
3384    if (sign(p_FDeg(p,r))!=vz)
3385    {
3386      p_Delete(&p,r);
3387      return TRUE;
3388    }
3389  }
3390  p_Delete(&p,r);
3391  return FALSE;
3392}
3393
3394BOOLEAN rComplete(ring r, int force)
3395{
3396  if (r->VarOffset!=NULL && force == 0) return FALSE;
3397  rSetOutParams(r);
3398  int n=rBlocks(r)-1;
3399  int i;
3400  int bits;
3401  r->bitmask=rGetExpSize(r->bitmask,bits,r->N);
3402  r->BitsPerExp = bits;
3403  r->ExpPerLong = BIT_SIZEOF_LONG / bits;
3404  r->divmask=rGetDivMask(bits);
3405
3406  // will be used for ordsgn:
3407  long *tmp_ordsgn=(long *)omAlloc0(3*(n+r->N)*sizeof(long));
3408  // will be used for VarOffset:
3409  int *v=(int *)omAlloc((r->N+1)*sizeof(int));
3410  for(i=r->N; i>=0 ; i--)
3411  {
3412    v[i]=-1;
3413  }
3414  sro_ord *tmp_typ=(sro_ord *)omAlloc0(3*(n+r->N)*sizeof(sro_ord));
3415  int typ_i=0;
3416  int prev_ordsgn=0;
3417
3418  // fill in v, tmp_typ, tmp_ordsgn, determine typ_i (== ordSize)
3419  int j=0;
3420  int j_bits=BITS_PER_LONG;
3421
3422  BOOLEAN need_to_add_comp=FALSE; // Only for ringorder_s and ringorder_S!
3423
3424  for(i=0;i<n;i++)
3425  {
3426    tmp_typ[typ_i].order_index=i;
3427    switch (r->order[i])
3428    {
3429      case ringorder_a:
3430      case ringorder_aa:
3431        rO_WDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,tmp_typ[typ_i],
3432                   r->wvhdl[i]);
3433        typ_i++;
3434        break;
3435
3436      case ringorder_am:
3437        rO_WMDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,tmp_typ[typ_i],
3438                   r->wvhdl[i]);
3439        typ_i++;
3440        break;
3441
3442      case ringorder_a64:
3443        rO_WDegree64(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3444                     tmp_typ[typ_i], (int64 *)(r->wvhdl[i]));
3445        typ_i++;
3446        break;
3447
3448      case ringorder_c:
3449        rO_Align(j, j_bits);
3450        rO_LexVars_neg(j, j_bits, 0,0, prev_ordsgn,tmp_ordsgn,v,BITS_PER_LONG, -1);
3451        r->ComponentOrder=1;
3452        break;
3453
3454      case ringorder_C:
3455        rO_Align(j, j_bits);
3456        rO_LexVars(j, j_bits, 0,0, prev_ordsgn,tmp_ordsgn,v,BITS_PER_LONG, -1);
3457        r->ComponentOrder=-1;
3458        break;
3459
3460      case ringorder_M:
3461        {
3462          int k,l;
3463          k=r->block1[i]-r->block0[i]+1; // number of vars
3464          for(l=0;l<k;l++)
3465          {
3466            rO_WDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3467                       tmp_typ[typ_i],
3468                       r->wvhdl[i]+(r->block1[i]-r->block0[i]+1)*l);
3469            typ_i++;
3470          }
3471          break;
3472        }
3473
3474      case ringorder_lp:
3475        rO_LexVars(j, j_bits, r->block0[i],r->block1[i], prev_ordsgn,
3476                   tmp_ordsgn,v,bits, -1);
3477        break;
3478
3479      case ringorder_ls:
3480        rO_LexVars_neg(j, j_bits, r->block0[i],r->block1[i], prev_ordsgn,
3481                       tmp_ordsgn,v, bits, -1);
3482        break;
3483
3484      case ringorder_rs:
3485        rO_LexVars_neg(j, j_bits, r->block1[i],r->block0[i], prev_ordsgn,
3486                       tmp_ordsgn,v, bits, -1);
3487        break;
3488
3489      case ringorder_rp:
3490        rO_LexVars(j, j_bits, r->block1[i],r->block0[i], prev_ordsgn,
3491                       tmp_ordsgn,v, bits, -1);
3492        break;
3493
3494      case ringorder_dp:
3495        if (r->block0[i]==r->block1[i])
3496        {
3497          rO_LexVars(j, j_bits, r->block0[i],r->block0[i], prev_ordsgn,
3498                     tmp_ordsgn,v, bits, -1);
3499        }
3500        else
3501        {
3502          rO_TDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3503                     tmp_typ[typ_i]);
3504          typ_i++;
3505          rO_LexVars_neg(j, j_bits, r->block1[i],r->block0[i]+1,
3506                         prev_ordsgn,tmp_ordsgn,v,bits, r->block0[i]);
3507        }
3508        break;
3509
3510      case ringorder_Dp:
3511        if (r->block0[i]==r->block1[i])
3512        {
3513          rO_LexVars(j, j_bits, r->block0[i],r->block0[i], prev_ordsgn,
3514                     tmp_ordsgn,v, bits, -1);
3515        }
3516        else
3517        {
3518          rO_TDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3519                     tmp_typ[typ_i]);
3520          typ_i++;
3521          rO_LexVars(j, j_bits, r->block0[i],r->block1[i]-1, prev_ordsgn,
3522                     tmp_ordsgn,v, bits, r->block1[i]);
3523        }
3524        break;
3525
3526      case ringorder_ds:
3527        if (r->block0[i]==r->block1[i])
3528        {
3529          rO_LexVars_neg(j, j_bits,r->block0[i],r->block1[i],prev_ordsgn,
3530                         tmp_ordsgn,v,bits, -1);
3531        }
3532        else
3533        {
3534          rO_TDegree_neg(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3535                         tmp_typ[typ_i]);
3536          typ_i++;
3537          rO_LexVars_neg(j, j_bits, r->block1[i],r->block0[i]+1,
3538                         prev_ordsgn,tmp_ordsgn,v,bits, r->block0[i]);
3539        }
3540        break;
3541
3542      case ringorder_Ds:
3543        if (r->block0[i]==r->block1[i])
3544        {
3545          rO_LexVars_neg(j, j_bits, r->block0[i],r->block0[i],prev_ordsgn,
3546                         tmp_ordsgn,v, bits, -1);
3547        }
3548        else
3549        {
3550          rO_TDegree_neg(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3551                         tmp_typ[typ_i]);
3552          typ_i++;
3553          rO_LexVars(j, j_bits, r->block0[i],r->block1[i]-1, prev_ordsgn,
3554                     tmp_ordsgn,v, bits, r->block1[i]);
3555        }
3556        break;
3557
3558      case ringorder_wp:
3559        rO_WDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3560                   tmp_typ[typ_i], r->wvhdl[i]);
3561        typ_i++;
3562        { // check for weights <=0
3563          int jj;
3564          BOOLEAN have_bad_weights=FALSE;
3565          for(jj=r->block1[i]-r->block0[i];jj>=0; jj--)
3566          {
3567            if (r->wvhdl[i][jj]<=0) have_bad_weights=TRUE;
3568          }
3569          if (have_bad_weights)
3570          {
3571             rO_TDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3572                                     tmp_typ[typ_i]);
3573             typ_i++;
3574          }
3575        }
3576        if (r->block1[i]!=r->block0[i])
3577        {
3578          rO_LexVars_neg(j, j_bits,r->block1[i],r->block0[i]+1, prev_ordsgn,
3579                         tmp_ordsgn, v,bits, r->block0[i]);
3580        }
3581        break;
3582
3583      case ringorder_Wp:
3584        rO_WDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3585                   tmp_typ[typ_i], r->wvhdl[i]);
3586        typ_i++;
3587        { // check for weights <=0
3588          int jj;
3589          BOOLEAN have_bad_weights=FALSE;
3590          for(jj=r->block1[i]-r->block0[i];jj>=0; jj--)
3591          {
3592            if (r->wvhdl[i][jj]<=0) have_bad_weights=TRUE;
3593          }
3594          if (have_bad_weights)
3595          {
3596             rO_TDegree(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3597                                     tmp_typ[typ_i]);
3598             typ_i++;
3599          }
3600        }
3601        if (r->block1[i]!=r->block0[i])
3602        {
3603          rO_LexVars(j, j_bits,r->block0[i],r->block1[i]-1, prev_ordsgn,
3604                     tmp_ordsgn,v, bits, r->block1[i]);
3605        }
3606        break;
3607
3608      case ringorder_ws:
3609        rO_WDegree_neg(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3610                       tmp_typ[typ_i], r->wvhdl[i]);
3611        typ_i++;
3612        if (r->block1[i]!=r->block0[i])
3613        {
3614          rO_LexVars_neg(j, j_bits,r->block1[i],r->block0[i]+1, prev_ordsgn,
3615                         tmp_ordsgn, v,bits, r->block0[i]);
3616        }
3617        break;
3618
3619      case ringorder_Ws:
3620        rO_WDegree_neg(j,j_bits,r->block0[i],r->block1[i],tmp_ordsgn,
3621                       tmp_typ[typ_i], r->wvhdl[i]);
3622        typ_i++;
3623        if (r->block1[i]!=r->block0[i])
3624        {
3625          rO_LexVars(j, j_bits,r->block0[i],r->block1[i]-1, prev_ordsgn,
3626                     tmp_ordsgn,v, bits, r->block1[i]);
3627        }
3628        break;
3629
3630      case ringorder_S:
3631        assume(typ_i == 1); // For LaScala3 only: on the 2nd place ([1])!
3632        // TODO: for K[x]: it is 0...?!
3633        rO_Syzcomp(j, j_bits,prev_ordsgn, tmp_ordsgn,tmp_typ[typ_i]);
3634        need_to_add_comp=TRUE;
3635        r->ComponentOrder=-1;
3636        typ_i++;
3637        break;
3638
3639      case ringorder_s:
3640        assume(typ_i == 0 && j == 0);
3641        rO_Syz(j, j_bits, prev_ordsgn, r->block0[i], tmp_ordsgn, tmp_typ[typ_i]); // set syz-limit?
3642        need_to_add_comp=TRUE;
3643        r->ComponentOrder=-1;
3644        typ_i++;
3645        break;
3646
3647      case ringorder_IS:
3648      {
3649
3650        assume( r->block0[i] == r->block1[i] );
3651        const int s = r->block0[i];
3652        assume( -2 < s && s < 2);
3653
3654        if(s == 0) // Prefix IS
3655          rO_ISPrefix(j, j_bits, prev_ordsgn, tmp_ordsgn, r->N, v, tmp_typ[typ_i++]); // What about prev_ordsgn?
3656        else // s = +1 or -1 // Note: typ_i might be incrimented here inside!
3657        {
3658          rO_ISSuffix(j, j_bits, prev_ordsgn, tmp_ordsgn, r->N, v, tmp_typ, typ_i, s); // Suffix.
3659          need_to_add_comp=FALSE;
3660        }
3661
3662        break;
3663      }
3664      case ringorder_unspec:
3665      case ringorder_no:
3666      default:
3667        dReportError("undef. ringorder used\n");
3668        break;
3669    }
3670  }
3671  rCheckOrdSgn(r,n-1);
3672
3673  int j0=j; // save j
3674  int j_bits0=j_bits; // save jbits
3675  rO_Align(j,j_bits);
3676  r->CmpL_Size = j;
3677
3678  j_bits=j_bits0; j=j0;
3679
3680  // fill in some empty slots with variables not already covered
3681  // v0 is special, is therefore normally already covered
3682  // now we do have rings without comp...
3683  if((need_to_add_comp) && (v[0]== -1))
3684  {
3685    if (prev_ordsgn==1)
3686    {
3687      rO_Align(j, j_bits);
3688      rO_LexVars(j, j_bits, 0,0, prev_ordsgn,tmp_ordsgn,v,BITS_PER_LONG, -1);
3689    }
3690    else
3691    {
3692      rO_Align(j, j_bits);
3693      rO_LexVars_neg(j, j_bits, 0,0, prev_ordsgn,tmp_ordsgn,v,BITS_PER_LONG, -1);
3694    }
3695  }
3696  // the variables
3697  for(i=1 ; i<=r->N ; i++)
3698  {
3699    if(v[i]==(-1))
3700    {
3701      if (prev_ordsgn==1)
3702      {
3703        rO_LexVars(j, j_bits, i,i, prev_ordsgn,tmp_ordsgn,v,bits, -1);
3704      }
3705      else
3706      {
3707        rO_LexVars_neg(j,j_bits,i,i, prev_ordsgn,tmp_ordsgn,v,bits, -1);
3708      }
3709    }
3710  }
3711
3712  rO_Align(j,j_bits);
3713  // ----------------------------
3714  // finished with constructing the monomial, computing sizes:
3715
3716  r->ExpL_Size=j;
3717  r->PolyBin = omGetSpecBin(POLYSIZE + (r->ExpL_Size)*sizeof(long));
3718  assume(r->PolyBin != NULL);
3719
3720  // ----------------------------
3721  // indices and ordsgn vector for comparison
3722  //
3723  // r->pCompHighIndex already set
3724  r->ordsgn=(long *)omAlloc0(r->ExpL_Size*sizeof(long));
3725
3726  for(j=0;j<r->CmpL_Size;j++)
3727  {
3728    r->ordsgn[j] = tmp_ordsgn[j];
3729  }
3730
3731  omFreeSize((ADDRESS)tmp_ordsgn,(3*(n+r->N)*sizeof(long)));
3732
3733  // ----------------------------
3734  // description of orderings for setm:
3735  //
3736  r->OrdSize=typ_i;
3737  if (typ_i==0) r->typ=NULL;
3738  else
3739  {
3740    r->typ=(sro_ord*)omAlloc(typ_i*sizeof(sro_ord));
3741    memcpy(r->typ,tmp_typ,typ_i*sizeof(sro_ord));
3742  }
3743  omFreeSize((ADDRESS)tmp_typ,(3*(n+r->N)*sizeof(sro_ord)));
3744
3745  // ----------------------------
3746  // indices for (first copy of ) variable entries in exp.e vector (VarOffset):
3747  r->VarOffset=v;
3748
3749  // ----------------------------
3750  // other indicies
3751  r->pCompIndex=(r->VarOffset[0] & 0xffff); //r->VarOffset[0];
3752  i=0; // position
3753  j=0; // index in r->typ
3754  if (i==r->pCompIndex) i++; // IS???
3755  while ((j < r->OrdSize)
3756         && ((r->typ[j].ord_typ==ro_syzcomp) ||
3757             (r->typ[j].ord_typ==ro_syz) || (r->typ[j].ord_typ==ro_isTemp) || (r->typ[j].ord_typ==ro_is) ||
3758             (r->order[r->typ[j].order_index] == ringorder_aa)))
3759  {
3760    i++; j++;
3761  }
3762
3763  if (i==r->pCompIndex) i++;
3764  r->pOrdIndex=i;
3765
3766  // ----------------------------
3767  rSetDegStuff(r); // OrdSgn etc already set
3768  rSetOption(r);
3769  // ----------------------------
3770  // r->p_Setm
3771  r->p_Setm = p_GetSetmProc(r);
3772
3773  // ----------------------------
3774  // set VarL_*
3775  rSetVarL(r);
3776
3777  //  ----------------------------
3778  // right-adjust VarOffset
3779  rRightAdjustVarOffset(r);
3780
3781  // ----------------------------
3782  // set NegWeightL*
3783  rSetNegWeight(r);
3784
3785  // ----------------------------
3786  // p_Procs: call AFTER NegWeightL
3787  r->p_Procs = (p_Procs_s*)omAlloc(sizeof(p_Procs_s));
3788  p_ProcsSet(r, r->p_Procs);
3789
3790  // use totaldegree on crazy oderings:
3791  if ((r->pFDeg==p_WTotaldegree) && rOrd_is_MixedDegree_Ordering(r))
3792    r->pFDeg = p_Totaldegree;
3793  return FALSE;
3794}
3795
3796static void rCheckOrdSgn(ring r,int b/*last block*/)
3797{ // set r->OrdSgn, r->MixedOrder
3798  // for each variable:
3799  int nonpos=0;
3800  int nonneg=0;
3801  for(int i=1;i<=r->N;i++)
3802  {
3803    int found=0;
3804    // for all blocks:
3805    for(int j=0;(j<=b) && (found==0);j++)
3806    {
3807      // search the first block containing var(i)
3808      if ((r->block0[j]<=i)&&(r->block1[j]>=i))
3809      {
3810        // what kind if block is it?
3811        if ((r->order[j]==ringorder_ls)
3812        || (r->order[j]==ringorder_ds)
3813        || (r->order[j]==ringorder_Ds)
3814        || (r->order[j]==ringorder_ws)
3815        || (r->order[j]==ringorder_Ws)
3816        || (r->order[j]==ringorder_rs))
3817        {
3818          r->OrdSgn=-1;
3819          nonpos++;
3820          found=1;
3821        }
3822        else if((r->order[j]==ringorder_a)
3823        ||(r->order[j]==ringorder_aa))
3824        {
3825          // <0: local/mixed ordering
3826          // >0: var(i) is okay, look at other vars
3827          // ==0: look at other blocks for var(i)
3828          if(r->wvhdl[j][i-r->block0[j]]<0)
3829          {
3830            r->OrdSgn=-1;
3831            nonpos++;
3832            found=1;
3833          }
3834          else if(r->wvhdl[j][i-r->block0[j]]>0)
3835          {
3836            nonneg++;
3837            found=1;
3838          }
3839        }
3840        else if(r->order[j]==ringorder_M)
3841        {
3842          // <0: local/mixed ordering
3843          // >0: var(i) is okay, look at other vars
3844          // ==0: look at other blocks for var(i)
3845          if(r->wvhdl[j][i-r->block0[j]]<0)
3846          {
3847            r->OrdSgn=-1;
3848            nonpos++;
3849            found=1;
3850          }
3851          else if(r->wvhdl[j][i-r->block0[j]]>0)
3852          {
3853            nonneg++;
3854            found=1;
3855          }
3856          else
3857          {
3858            // very bad:
3859            nonpos++;
3860            nonneg++;
3861            found=1;
3862          }
3863        }
3864        else if ((r->order[j]==ringorder_lp)
3865        || (r->order[j]==ringorder_dp)
3866        || (r->order[j]==ringorder_Dp)
3867        || (r->order[j]==ringorder_wp)
3868        || (r->order[j]==ringorder_Wp)
3869        || (r->order[j]==ringorder_rp))
3870        {
3871          found=1;
3872          nonneg++;
3873        }
3874      }
3875    }
3876  }
3877  if (nonpos>0)
3878  {
3879    r->OrdSgn=-1;
3880    if (nonneg>0) r->MixedOrder=1;
3881  }
3882  else
3883  {
3884    r->OrdSgn=1;
3885    r->MixedOrder=0;
3886  }
3887}
3888
3889void rUnComplete(ring r)
3890{
3891  if (r == NULL) return;
3892  if (r->VarOffset != NULL)
3893  {
3894    if (r->OrdSize!=0 && r->typ != NULL)
3895    {
3896      for(int i = 0; i < r->OrdSize; i++)
3897        if( r->typ[i].ord_typ == ro_is) // Search for suffixes! (prefix have the same VarOffset)
3898        {
3899          id_Delete(&r->typ[i].data.is.F, r);
3900          r->typ[i].data.is.F = NULL; // ?
3901
3902          if( r->typ[i].data.is.pVarOffset != NULL )
3903          {
3904            omFreeSize((ADDRESS)r->typ[i].data.is.pVarOffset, (r->N +1)*sizeof(int));
3905            r->typ[i].data.is.pVarOffset = NULL; // ?
3906          }
3907        }
3908        else if (r->typ[i].ord_typ == ro_syz)
3909        {
3910          if(r->typ[i].data.syz.limit > 0)
3911            omFreeSize(r->typ[i].data.syz.syz_index, ((r->typ[i].data.syz.limit) +1)*sizeof(int));
3912          r->typ[i].data.syz.syz_index = NULL;
3913        }
3914        else if (r->typ[i].ord_typ == ro_syzcomp)
3915        {
3916          assume( r->typ[i].data.syzcomp.ShiftedComponents == NULL );
3917          assume( r->typ[i].data.syzcomp.Components        == NULL );
3918//          WarnS( "rUnComplete : ord_typ == ro_syzcomp was unhandled!!! Possibly memory leak!!!"  );
3919#ifndef SING_NDEBUG
3920//          assume(0);
3921#endif
3922        }
3923
3924      omFreeSize((ADDRESS)r->typ,r->OrdSize*sizeof(sro_ord)); r->typ = NULL;
3925    }
3926
3927    if (r->PolyBin != NULL)
3928      omUnGetSpecBin(&(r->PolyBin));
3929
3930    omFreeSize((ADDRESS)r->VarOffset, (r->N +1)*sizeof(int));
3931
3932    if (r->ordsgn != NULL && r->CmpL_Size != 0)
3933      omFreeSize((ADDRESS)r->ordsgn,r->ExpL_Size*sizeof(long));
3934    if (r->p_Procs != NULL)
3935      omFreeSize(r->p_Procs, sizeof(p_Procs_s));
3936    omfreeSize(r->VarL_Offset, r->VarL_Size*sizeof(int));
3937  }
3938  if (r->NegWeightL_Offset!=NULL)
3939  {
3940    omFreeSize(r->NegWeightL_Offset, r->NegWeightL_Size*sizeof(int));
3941    r->NegWeightL_Offset=NULL;
3942  }
3943}
3944
3945// set r->VarL_Size, r->VarL_Offset, r->VarL_LowIndex
3946static void rSetVarL(ring r)
3947{
3948  int  min = MAX_INT_VAL, min_j = -1;
3949  int* VarL_Number = (int*) omAlloc0(r->ExpL_Size*sizeof(int));
3950
3951  int i,j;
3952
3953  // count how often a var long is occupied by an exponent
3954  for (i=1; i<=r->N; i++)
3955  {
3956    VarL_Number[r->VarOffset[i] & 0xffffff]++;
3957  }
3958
3959  // determine how many and min
3960  for (i=0, j=0; i<r->ExpL_Size; i++)
3961  {
3962    if (VarL_Number[i] != 0)
3963    {
3964      if (min > VarL_Number[i])
3965      {
3966        min = VarL_Number[i];
3967        min_j = j;
3968      }
3969      j++;
3970    }
3971  }
3972
3973  r->VarL_Size = j; // number of long with exp. entries in
3974                    //  in p->exp
3975  r->VarL_Offset = (int*) omAlloc(r->VarL_Size*sizeof(int));
3976  r->VarL_LowIndex = 0;
3977
3978  // set VarL_Offset
3979  for (i=0, j=0; i<r->ExpL_Size; i++)
3980  {
3981    if (VarL_Number[i] != 0)
3982    {
3983      r->VarL_Offset[j] = i;
3984      if (j > 0 && r->VarL_Offset[j-1] != r->VarL_Offset[j] - 1)
3985        r->VarL_LowIndex = -1;
3986      j++;
3987    }
3988  }
3989  if (r->VarL_LowIndex >= 0)
3990    r->VarL_LowIndex = r->VarL_Offset[0];
3991
3992  if (min_j != 0)
3993  {
3994    j = r->VarL_Offset[min_j];
3995    r->VarL_Offset[min_j] = r->VarL_Offset[0];
3996    r->VarL_Offset[0] = j;
3997  }
3998  omFree(VarL_Number);
3999}
4000
4001static void rRightAdjustVarOffset(ring r)
4002{
4003  int* shifts = (int*) omAlloc(r->ExpL_Size*sizeof(int));
4004  int i;
4005  // initialize shifts
4006  for (i=0;i<r->ExpL_Size;i++)
4007    shifts[i] = BIT_SIZEOF_LONG;
4008
4009  // find minimal bit shift in each long exp entry
4010  for (i=1;i<=r->N;i++)
4011  {
4012    if (shifts[r->VarOffset[i] & 0xffffff] > r->VarOffset[i] >> 24)
4013      shifts[r->VarOffset[i] & 0xffffff] = r->VarOffset[i] >> 24;
4014  }
4015  // reset r->VarOffset: set the minimal shift to 0
4016  for (i=1;i<=r->N;i++)
4017  {
4018    if (shifts[r->VarOffset[i] & 0xffffff] != 0)
4019      r->VarOffset[i]
4020        = (r->VarOffset[i] & 0xffffff) |
4021        (((r->VarOffset[i] >> 24) - shifts[r->VarOffset[i] & 0xffffff]) << 24);
4022  }
4023  omFree(shifts);
4024}
4025
4026// get r->divmask depending on bits per exponent
4027static unsigned long rGetDivMask(int bits)
4028{
4029  unsigned long divmask = 1;
4030  int i = bits;
4031
4032  while (i < BIT_SIZEOF_LONG)
4033  {
4034    divmask |= (((unsigned long) 1) << (unsigned long) i);
4035    i += bits;
4036  }
4037  return divmask;
4038}
4039
4040#ifdef RDEBUG
4041void rDebugPrint(const ring r)
4042{
4043  if (r==NULL)
4044  {
4045    PrintS("NULL ?\n");
4046    return;
4047  }
4048  // corresponds to ro_typ from ring.h:
4049  const char *TYP[]={"ro_dp","ro_wp","ro_am","ro_wp64","ro_wp_neg","ro_cp",
4050                     "ro_syzcomp", "ro_syz", "ro_isTemp", "ro_is", "ro_none"};
4051  int i,j;
4052
4053  Print("ExpL_Size:%d ",r->ExpL_Size);
4054  Print("CmpL_Size:%d ",r->CmpL_Size);
4055  Print("VarL_Size:%d\n",r->VarL_Size);
4056  Print("bitmask=0x%lx (expbound=%ld) \n",r->bitmask, r->bitmask);
4057  Print("divmask=%lx\n", r->divmask);
4058  Print("BitsPerExp=%d ExpPerLong=%d at L[%d]\n", r->BitsPerExp, r->ExpPerLong, r->VarL_Offset[0]);
4059
4060  Print("VarL_LowIndex: %d\n", r->VarL_LowIndex);
4061  PrintS("VarL_Offset:\n");
4062  if (r->VarL_Offset==NULL) PrintS(" NULL");
4063  else
4064    for(j = 0; j < r->VarL_Size; j++)
4065      Print("  VarL_Offset[%d]: %d ", j, r->VarL_Offset[j]);
4066  PrintLn();
4067
4068
4069  PrintS("VarOffset:\n");
4070  if (r->VarOffset==NULL) PrintS(" NULL\n");
4071  else
4072    for(j=0;j<=r->N;j++)
4073      Print("  v%d at e-pos %d, bit %d\n",
4074            j,r->VarOffset[j] & 0xffffff, r->VarOffset[j] >>24);
4075  PrintS("ordsgn:\n");
4076  for(j=0;j<r->CmpL_Size;j++)
4077    Print("  ordsgn %ld at pos %d\n",r->ordsgn[j],j);
4078  Print("OrdSgn:%d\n",r->OrdSgn);
4079  PrintS("ordrec:\n");
4080  for(j=0;j<r->OrdSize;j++)
4081  {
4082    Print("  typ %s", TYP[r->typ[j].ord_typ]);
4083    if (r->typ[j].ord_typ==ro_syz)
4084    {
4085      const short place = r->typ[j].data.syz.place;
4086      const int limit = r->typ[j].data.syz.limit;
4087      const int curr_index = r->typ[j].data.syz.curr_index;
4088      const int* syz_index = r->typ[j].data.syz.syz_index;
4089
4090      Print("  limit %d (place: %d, curr_index: %d), syz_index: ", limit, place, curr_index);
4091
4092      if( syz_index == NULL )
4093        PrintS("(NULL)");
4094      else
4095      {
4096        PrintS("{");
4097        for( i=0; i <= limit; i++ )
4098          Print("%d ", syz_index[i]);
4099        PrintS("}");
4100      }
4101
4102    }
4103    else if (r->typ[j].ord_typ==ro_isTemp)
4104    {
4105      Print("  start (level) %d, suffixpos: %d, VO: ",r->typ[j].data.isTemp.start, r->typ[j].data.isTemp.suffixpos);
4106
4107    }
4108    else if (r->typ[j].ord_typ==ro_is)
4109    {
4110      Print("  start %d, end: %d: ",r->typ[j].data.is.start, r->typ[j].data.is.end);
4111
4112//      for( int k = 0; k <= r->N; k++) if (r->typ[j].data.is.pVarOffset[k] != -1) Print("[%2d]: %04x; ", k, r->typ[j].data.is.pVarOffset[k]);
4113
4114      Print("  limit %d",r->typ[j].data.is.limit);
4115#ifndef SING_NDEBUG
4116      //PrintS("  F: ");idShow(r->typ[j].data.is.F, r, r, 1);
4117#endif
4118
4119      PrintLn();
4120    }
4121    else if  (r->typ[j].ord_typ==ro_am)
4122    {
4123      Print("  place %d",r->typ[j].data.am.place);
4124      Print("  start %d",r->typ[j].data.am.start);
4125      Print("  end %d",r->typ[j].data.am.end);
4126      Print("  len_gen %d",r->typ[j].data.am.len_gen);
4127      PrintS(" w:");
4128      int l=0;
4129      for(l=r->typ[j].data.am.start;l<=r->typ[j].data.am.end;l++)
4130            Print(" %d",r->typ[j].data.am.weights[l-r->typ[j].data.am.start]);
4131      l=r->typ[j].data.am.end+1;
4132      int ll=r->typ[j].data.am.weights[l-r->typ[j].data.am.start];
4133      PrintS(" m:");
4134      for(int lll=l+1;lll<l+ll+1;lll++)
4135            Print(" %d",r->typ[j].data.am.weights[lll-r->typ[j].data.am.start]);
4136    }
4137    else
4138    {
4139      Print("  place %d",r->typ[j].data.dp.place);
4140
4141      if (r->typ[j].ord_typ!=ro_syzcomp  && r->typ[j].ord_typ!=ro_syz)
4142      {
4143        Print("  start %d",r->typ[j].data.dp.start);
4144        Print("  end %d",r->typ[j].data.dp.end);
4145        if ((r->typ[j].ord_typ==ro_wp)
4146        || (r->typ[j].ord_typ==ro_wp_neg))
4147        {
4148          PrintS(" w:");
4149          for(int l=r->typ[j].data.wp.start;l<=r->typ[j].data.wp.end;l++)
4150            Print(" %d",r->typ[j].data.wp.weights[l-r->typ[j].data.wp.start]);
4151        }
4152        else if (r->typ[j].ord_typ==ro_wp64)
4153        {
4154          PrintS(" w64:");
4155          int l;
4156          for(l=r->typ[j].data.wp64.start;l<=r->typ[j].data.wp64.end;l++)
4157            Print(" %ld",(long)(((int64*)r->typ[j].data.wp64.weights64)+l-r->typ[j].data.wp64.start));
4158          }
4159        }
4160    }
4161    PrintLn();
4162  }
4163  Print("pOrdIndex:%d pCompIndex:%d\n", r->pOrdIndex, r->pCompIndex);
4164  Print("OrdSize:%d\n",r->OrdSize);
4165  PrintS("--------------------\n");
4166  for(j=0;j<r->ExpL_Size;j++)
4167  {
4168    Print("L[%d]: ",j);
4169    if (j< r->CmpL_Size)
4170      Print("ordsgn %ld ", r->ordsgn[j]);
4171    else
4172      PrintS("no comp ");
4173    i=1;
4174    for(;i<=r->N;i++)
4175    {
4176      if( (r->VarOffset[i] & 0xffffff) == j )
4177      {  Print("v%d at e[%d], bit %d; ", i,r->VarOffset[i] & 0xffffff,
4178                                         r->VarOffset[i] >>24 ); }
4179    }
4180    if( r->pCompIndex==j ) PrintS("v0; ");
4181    for(i=0;i<r->OrdSize;i++)
4182    {
4183      if (r->typ[i].data.dp.place == j)
4184      {
4185        Print("ordrec:%s (start:%d, end:%d) ",TYP[r->typ[i].ord_typ],
4186          r->typ[i].data.dp.start, r->typ[i].data.dp.end);
4187      }
4188    }
4189
4190    if (j==r->pOrdIndex)
4191      PrintS("pOrdIndex\n");
4192    else
4193      PrintLn();
4194  }
4195  Print("LexOrder:%d, MixedOrder:%d\n",r->LexOrder, r->MixedOrder);
4196
4197  Print("NegWeightL_Size: %d, NegWeightL_Offset: ", r->NegWeightL_Size);
4198  if (r->NegWeightL_Offset==NULL) PrintS(" NULL");
4199  else
4200    for(j = 0; j < r->NegWeightL_Size; j++)
4201      Print("  [%d]: %d ", j, r->NegWeightL_Offset[j]);
4202  PrintLn();
4203
4204  // p_Procs stuff
4205  p_Procs_s proc_names;
4206  const char* field;
4207  const char* length;
4208  const char* ord;
4209  p_Debug_GetProcNames(r, &proc_names); // changes p_Procs!!!
4210  p_Debug_GetSpecNames(r, field, length, ord);
4211
4212  Print("p_Spec  : %s, %s, %s\n", field, length, ord);
4213  PrintS("p_Procs :\n");
4214  for (i=0; i<(int) (sizeof(p_Procs_s)/sizeof(void*)); i++)
4215  {
4216    Print(" %s,\n", ((char**) &proc_names)[i]);
4217  }
4218
4219  {
4220      PrintLn();
4221      PrintS("pFDeg   : ");
4222#define pFDeg_CASE(A) if(r->pFDeg == A) PrintS( "" #A "" )
4223      pFDeg_CASE(p_Totaldegree); else
4224      pFDeg_CASE(p_WFirstTotalDegree); else
4225      pFDeg_CASE(p_WTotaldegree); else
4226      pFDeg_CASE(p_Deg); else
4227#undef pFDeg_CASE
4228      Print("(%p)", r->pFDeg); // default case
4229
4230    PrintLn();
4231    Print("pLDeg   : (%p)", r->pLDeg);
4232    PrintLn();
4233  }
4234  PrintS("pSetm:");
4235  void p_Setm_Dummy(poly p, const ring r);
4236  void p_Setm_TotalDegree(poly p, const ring r);
4237  void p_Setm_WFirstTotalDegree(poly p, const ring r);
4238  void p_Setm_General(poly p, const ring r);
4239  if (r->p_Setm==p_Setm_General) PrintS("p_Setm_General\n");
4240  else if (r->p_Setm==p_Setm_Dummy) PrintS("p_Setm_Dummy\n");
4241  else if (r->p_Setm==p_Setm_TotalDegree) PrintS("p_Setm_Totaldegree\n");
4242  else if (r->p_Setm==p_Setm_WFirstTotalDegree) PrintS("p_Setm_WFirstTotalDegree\n");
4243  else Print("%p\n",r->p_Setm);
4244}
4245
4246void p_DebugPrint(poly p, const ring r)
4247{
4248  int i,j;
4249  p_Write(p,r);
4250  j=2;
4251  while(p!=NULL)
4252  {
4253    Print("\nexp[0..%d]\n",r->ExpL_Size-1);
4254    for(i=0;i<r->ExpL_Size;i++)
4255      Print("%ld ",p->exp[i]);
4256    PrintLn();
4257    Print("v0:%ld ",p_GetComp(p, r));
4258    for(i=1;i<=r->N;i++) Print(" v%d:%ld",i,p_GetExp(p,i, r));
4259    PrintLn();
4260    pIter(p);
4261    j--;
4262    if (j==0) { PrintS("...\n"); break; }
4263  }
4264}
4265
4266#endif // RDEBUG
4267
4268/// debug-print monomial poly/vector p, assuming that it lives in the ring R
4269static inline void m_DebugPrint(const poly p, const ring R)
4270{
4271  Print("\nexp[0..%d]\n", R->ExpL_Size - 1);
4272  for(int i = 0; i < R->ExpL_Size; i++)
4273    Print("%09lx ", p->exp[i]);
4274  PrintLn();
4275  Print("v0:%9ld ", p_GetComp(p, R));
4276  for(int i = 1; i <= R->N; i++) Print(" v%d:%5ld",i, p_GetExp(p, i, R));
4277  PrintLn();
4278}
4279
4280
4281//    F = system("ISUpdateComponents", F, V, MIN );
4282//    // replace gen(i) -> gen(MIN + V[i-MIN]) for all i > MIN in all terms from F!
4283void pISUpdateComponents(ideal F, const intvec *const V, const int MIN, const ring r )
4284{
4285  assume( V != NULL );
4286  assume( MIN >= 0 );
4287
4288  if( F == NULL )
4289    return;
4290
4291  for( int j = (F->ncols*F->nrows) - 1; j >= 0; j-- )
4292  {
4293#ifdef PDEBUG
4294    Print("F[%d]:", j);
4295    p_wrp(F->m[j], r);
4296#endif
4297
4298    for( poly p = F->m[j]; p != NULL; pIter(p) )
4299    {
4300      int c = p_GetComp(p, r);
4301
4302      if( c > MIN )
4303      {
4304#ifdef PDEBUG
4305        Print("gen[%d] -> gen(%d)\n", c, MIN + (*V)[ c - MIN - 1 ]);
4306#endif
4307
4308        p_SetComp( p, MIN + (*V)[ c - MIN - 1 ], r );
4309      }
4310    }
4311#ifdef PDEBUG
4312    Print("new F[%d]:", j);
4313    p_Test(F->m[j], r);
4314    p_wrp(F->m[j], r);
4315#endif
4316  }
4317}
4318
4319/*2
4320* asssume that rComplete was called with r
4321* assume that the first block ist ringorder_S
4322* change the block to reflect the sequence given by appending v
4323*/
4324static inline void rNChangeSComps(int* currComponents, long* currShiftedComponents, ring r)
4325{
4326  assume(r->typ[1].ord_typ == ro_syzcomp);
4327
4328  r->typ[1].data.syzcomp.ShiftedComponents = currShiftedComponents;
4329  r->typ[1].data.syzcomp.Components = currComponents;
4330}
4331
4332static inline void rNGetSComps(int** currComponents, long** currShiftedComponents, ring r)
4333{
4334  assume(r->typ[1].ord_typ == ro_syzcomp);
4335
4336  *currShiftedComponents = r->typ[1].data.syzcomp.ShiftedComponents;
4337  *currComponents =   r->typ[1].data.syzcomp.Components;
4338}
4339#ifdef PDEBUG
4340static inline void rDBChangeSComps(int* currComponents,
4341                     long* currShiftedComponents,
4342                     int length,
4343                     ring r)
4344{
4345  assume(r->typ[1].ord_typ == ro_syzcomp);
4346
4347  r->typ[1].data.syzcomp.length = length;
4348  rNChangeSComps( currComponents, currShiftedComponents, r);
4349}
4350static inline void rDBGetSComps(int** currComponents,
4351                 long** currShiftedComponents,
4352                 int *length,
4353                 ring r)
4354{
4355  assume(r->typ[1].ord_typ == ro_syzcomp);
4356
4357  *length = r->typ[1].data.syzcomp.length;
4358  rNGetSComps( currComponents, currShiftedComponents, r);
4359}
4360#endif
4361
4362void rChangeSComps(int* currComponents, long* currShiftedComponents, int length, ring r)
4363{
4364#ifdef PDEBUG
4365   rDBChangeSComps(currComponents, currShiftedComponents, length, r);
4366#else
4367   rNChangeSComps(currComponents, currShiftedComponents, r);
4368#endif
4369}
4370
4371void rGetSComps(int** currComponents, long** currShiftedComponents, int *length, ring r)
4372{
4373#ifdef PDEBUG
4374   rDBGetSComps(currComponents, currShiftedComponents, length, r);
4375#else
4376   rNGetSComps(currComponents, currShiftedComponents, r);
4377#endif
4378}
4379
4380
4381/////////////////////////////////////////////////////////////////////////////
4382//
4383// The following routines all take as input a ring r, and return R
4384// where R has a certain property. R might be equal r in which case r
4385// had already this property
4386//
4387ring rAssure_SyzOrder(const ring r, BOOLEAN complete)
4388{
4389  if ( r->order[0] == ringorder_c ) return r;
4390  return rAssure_SyzComp(r,complete);
4391}
4392ring rAssure_SyzComp(const ring r, BOOLEAN complete)
4393{
4394  if ( r->order[0] == ringorder_s ) return r;
4395
4396  if ( r->order[0] == ringorder_IS )
4397  {
4398#ifndef SING_NDEBUG
4399    WarnS("rAssure_SyzComp: input ring has an IS-ordering!");
4400#endif
4401//    return r;
4402  }
4403  ring res=rCopy0(r, FALSE, FALSE);
4404  int i=rBlocks(r);
4405  int j;
4406
4407  res->order=(rRingOrder_t *)omAlloc((i+1)*sizeof(rRingOrder_t));
4408  res->block0=(int *)omAlloc0((i+1)*sizeof(int));
4409  res->block1=(int *)omAlloc0((i+1)*sizeof(int));
4410  int ** wvhdl =(int **)omAlloc0((i+1)*sizeof(int**));
4411  for(j=i;j>0;j--)
4412  {
4413    res->order[j]=r->order[j-1];
4414    res->block0[j]=r->block0[j-1];
4415    res->block1[j]=r->block1[j-1];
4416    if (r->wvhdl[j-1] != NULL)
4417    {
4418      wvhdl[j] = (int*) omMemDup(r->wvhdl[j-1]);
4419    }
4420  }
4421  res->order[0]=ringorder_s;
4422
4423  res->wvhdl = wvhdl;
4424
4425  if (complete)
4426  {
4427    rComplete(res, 1);
4428#ifdef HAVE_PLURAL
4429    if (rIsPluralRing(r))
4430    {
4431      if ( nc_rComplete(r, res, false) ) // no qideal!
4432      {
4433#ifndef SING_NDEBUG
4434        WarnS("error in nc_rComplete");      // cleanup?//      rDelete(res);//      return r;      // just go on..
4435#endif
4436      }
4437    }
4438    assume(rIsPluralRing(r) == rIsPluralRing(res));
4439#endif
4440
4441#ifdef HAVE_PLURAL
4442    ring old_ring = r;
4443#endif
4444    if (r->qideal!=NULL)
4445    {
4446      res->qideal= idrCopyR_NoSort(r->qideal, r, res);
4447      assume(id_RankFreeModule(res->qideal, res) == 0);
4448#ifdef HAVE_PLURAL
4449      if( rIsPluralRing(res) )
4450      {
4451        if( nc_SetupQuotient(res, r, true) )
4452        {
4453//          WarnS("error in nc_SetupQuotient"); // cleanup?      rDelete(res);       return r;  // just go on...?
4454        }
4455        assume(id_RankFreeModule(res->qideal, res) == 0);
4456      }
4457#endif
4458    }
4459
4460#ifdef HAVE_PLURAL
4461    assume((res->qideal==NULL) == (old_ring->qideal==NULL));
4462    assume(rIsPluralRing(res) == rIsPluralRing(old_ring));
4463    assume(rIsSCA(res) == rIsSCA(old_ring));
4464    assume(ncRingType(res) == ncRingType(old_ring));
4465#endif
4466  }
4467  return res;
4468}
4469
4470ring rAssure_TDeg(ring r, int &pos)
4471{
4472  if (r->N==1) // special: dp(1)==lp(1)== no entry in typ
4473  {
4474    pos=r->VarL_LowIndex;
4475    return r;
4476  }
4477  if (r->typ!=NULL)
4478  {
4479    for(int i=r->OrdSize-1;i>=0;i--)
4480    {
4481      if ((r->typ[i].ord_typ==ro_dp)
4482      && (r->typ[i].data.dp.start==1)
4483      && (r->typ[i].data.dp.end==r->N))
4484      {
4485        pos=r->typ[i].data.dp.place;
4486        //printf("no change, pos=%d\n",pos);
4487        return r;
4488      }
4489    }
4490  }
4491
4492#ifdef HAVE_PLURAL
4493  nc_struct* save=r->GetNC();
4494  r->GetNC()=NULL;
4495#endif
4496  ring res=rCopy(r);
4497  if (res->qideal!=NULL)
4498  {
4499    id_Delete(&res->qideal,r);
4500  }
4501
4502  int i=rBlocks(r);
4503  int j;
4504
4505  res->ExpL_Size=r->ExpL_Size+1; // one word more in each monom
4506  res->PolyBin=omGetSpecBin(POLYSIZE + (res->ExpL_Size)*sizeof(long));
4507  omFree((ADDRESS)res->ordsgn);
4508  res->ordsgn=(long *)omAlloc0(res->ExpL_Size*sizeof(long));
4509  for(j=0;j<r->CmpL_Size;j++)
4510  {
4511    res->ordsgn[j] = r->ordsgn[j];
4512  }
4513  res->OrdSize=r->OrdSize+1;   // one block more for pSetm
4514  if (r->typ!=NULL)
4515    omFree((ADDRESS)res->typ);
4516  res->typ=(sro_ord*)omAlloc0(res->OrdSize*sizeof(sro_ord));
4517  if (r->typ!=NULL)
4518    memcpy(res->typ,r->typ,r->OrdSize*sizeof(sro_ord));
4519  // the additional block for pSetm: total degree at the last word
4520  // but not included in the compare part
4521  res->typ[res->OrdSize-1].ord_typ=ro_dp;
4522  res->typ[res->OrdSize-1].data.dp.start=1;
4523  res->typ[res->OrdSize-1].data.dp.end=res->N;
4524  res->typ[res->OrdSize-1].data.dp.place=res->ExpL_Size-1;
4525  pos=res->ExpL_Size-1;
4526  //res->pOrdIndex=pos; //NO: think of a(1,0),dp !
4527  extern void p_Setm_General(poly p, ring r);
4528  res->p_Setm=p_Setm_General;
4529  // ----------------------------
4530  omFree((ADDRESS)res->p_Procs);
4531  res->p_Procs = (p_Procs_s*)omAlloc(sizeof(p_Procs_s));
4532
4533  p_ProcsSet(res, res->p_Procs);
4534#ifdef HAVE_PLURAL
4535  r->GetNC()=save;
4536  if (rIsPluralRing(r))
4537  {
4538    if ( nc_rComplete(r, res, false) ) // no qideal!
4539    {
4540#ifndef SING_NDEBUG
4541      WarnS("error in nc_rComplete");
4542#endif
4543      // just go on..
4544    }
4545  }
4546#endif
4547  if (r->qideal!=NULL)
4548  {
4549     res->qideal=idrCopyR_NoSort(r->qideal,r, res);
4550#ifdef HAVE_PLURAL
4551     if (rIsPluralRing(res))
4552     {
4553//       nc_SetupQuotient(res, currRing);
4554       nc_SetupQuotient(res, r); // ?
4555     }
4556     assume((res->qideal==NULL) == (r->qideal==NULL));
4557#endif
4558  }
4559
4560#ifdef HAVE_PLURAL
4561  assume(rIsPluralRing(res) == rIsPluralRing(r));
4562  assume(rIsSCA(res) == rIsSCA(r));
4563  assume(ncRingType(res) == ncRingType(r));
4564#endif
4565
4566  return res;
4567}
4568
4569ring rAssure_HasComp(const ring r)
4570{
4571  int last_block;
4572  int i=0;
4573  do
4574  {
4575     if (r->order[i] == ringorder_c ||
4576        r->order[i] == ringorder_C) return r;
4577     if (r->order[i] == 0)
4578        break;
4579     i++;
4580  } while (1);
4581  //WarnS("re-creating ring with comps");
4582  last_block=i-1;
4583
4584  ring new_r = rCopy0(r, FALSE, FALSE);
4585  i+=2;
4586  new_r->wvhdl=(int **)omAlloc0(i * sizeof(int *));
4587  new_r->order   = (rRingOrder_t *) omAlloc0(i * sizeof(rRingOrder_t));
4588  new_r->block0   = (int *) omAlloc0(i * sizeof(int));
4589  new_r->block1   = (int *) omAlloc0(i * sizeof(int));
4590  memcpy(new_r->order,r->order,(i-1) * sizeof(rRingOrder_t));
4591  memcpy(new_r->block0,r->block0,(i-1) * sizeof(int));
4592  memcpy(new_r->block1,r->block1,(i-1) * sizeof(int));
4593  for (int j=0; j<=last_block; j++)
4594  {
4595    if (r->wvhdl[j]!=NULL)
4596    {
4597      new_r->wvhdl[j] = (int*) omMemDup(r->wvhdl[j]);
4598    }
4599  }
4600  last_block++;
4601  new_r->order[last_block]=ringorder_C;
4602  //new_r->block0[last_block]=0;
4603  //new_r->block1[last_block]=0;
4604  //new_r->wvhdl[last_block]=NULL;
4605
4606  rComplete(new_r, 1);
4607
4608#ifdef HAVE_PLURAL
4609  if (rIsPluralRing(r))
4610  {
4611    if ( nc_rComplete(r, new_r, false) ) // no qideal!
4612    {
4613#ifndef SING_NDEBUG
4614      WarnS("error in nc_rComplete");      // cleanup?//      rDelete(res);//      return r;      // just go on..
4615#endif
4616    }
4617  }
4618  assume(rIsPluralRing(r) == rIsPluralRing(new_r));
4619#endif
4620
4621  return new_r;
4622}
4623
4624ring rAssure_CompLastBlock(ring r, BOOLEAN complete)
4625{
4626  int last_block = rBlocks(r) - 2;
4627  if (r->order[last_block] != ringorder_c &&
4628      r->order[last_block] != ringorder_C)
4629  {
4630    int c_pos = 0;
4631    int i;
4632
4633    for (i=0; i< last_block; i++)
4634    {
4635      if (r->order[i] == ringorder_c || r->order[i] == ringorder_C)
4636      {
4637        c_pos = i;
4638        break;
4639      }
4640    }
4641    if (c_pos != -1)
4642    {
4643      ring new_r = rCopy0(r, FALSE, TRUE);
4644      for (i=c_pos+1; i<=last_block; i++)
4645      {
4646        new_r->order[i-1] = new_r->order[i];
4647        new_r->block0[i-1] = new_r->block0[i];
4648        new_r->block1[i-1] = new_r->block1[i];
4649        new_r->wvhdl[i-1] = new_r->wvhdl[i];
4650      }
4651      new_r->order[last_block] = r->order[c_pos];
4652      new_r->block0[last_block] = r->block0[c_pos];
4653      new_r->block1[last_block] = r->block1[c_pos];
4654      new_r->wvhdl[last_block] = r->wvhdl[c_pos];
4655      if (complete)
4656      {
4657        rComplete(new_r, 1);
4658
4659#ifdef HAVE_PLURAL
4660        if (rIsPluralRing(r))
4661        {
4662          if ( nc_rComplete(r, new_r, false) ) // no qideal!
4663          {
4664#ifndef SING_NDEBUG
4665            WarnS("error in nc_rComplete");   // cleanup?//      rDelete(res);//      return r;      // just go on..
4666#endif
4667          }
4668        }
4669        assume(rIsPluralRing(r) == rIsPluralRing(new_r));
4670#endif
4671      }
4672      return new_r;
4673    }
4674  }
4675  return r;
4676}
4677
4678// Moves _c or _C ordering to the last place AND adds _s on the 1st place
4679ring rAssure_SyzComp_CompLastBlock(const ring r)
4680{
4681  rTest(r);
4682
4683  ring new_r_1 = rAssure_CompLastBlock(r, FALSE); // due to this FALSE - no completion!
4684  ring new_r = rAssure_SyzComp(new_r_1, FALSE); // new_r_1 is used only here!!!
4685
4686  if (new_r == r)
4687     return r;
4688
4689  ring old_r = r;
4690  if (new_r_1 != new_r && new_r_1 != old_r) rDelete(new_r_1);
4691
4692  rComplete(new_r, TRUE);
4693#ifdef HAVE_PLURAL
4694  if (rIsPluralRing(old_r))
4695  {
4696    if ( nc_rComplete(old_r, new_r, false) ) // no qideal!
4697    {
4698# ifndef SING_NDEBUG
4699      WarnS("error in nc_rComplete"); // cleanup?      rDelete(res);       return r;  // just go on...?
4700# endif
4701    }
4702  }
4703#endif
4704
4705///?    rChangeCurrRing(new_r);
4706  if (old_r->qideal != NULL)
4707  {
4708    new_r->qideal = idrCopyR(old_r->qideal, old_r, new_r);
4709  }
4710
4711#ifdef HAVE_PLURAL
4712  if( rIsPluralRing(old_r) )
4713    if( nc_SetupQuotient(new_r, old_r, true) )
4714    {
4715#ifndef SING_NDEBUG
4716      WarnS("error in nc_SetupQuotient"); // cleanup?      rDelete(res);       return r;  // just go on...?
4717#endif
4718    }
4719#endif
4720
4721#ifdef HAVE_PLURAL
4722  assume((new_r->qideal==NULL) == (old_r->qideal==NULL));
4723  assume(rIsPluralRing(new_r) == rIsPluralRing(old_r));
4724  assume(rIsSCA(new_r) == rIsSCA(old_r));
4725  assume(ncRingType(new_r) == ncRingType(old_r));
4726#endif
4727
4728  rTest(new_r);
4729  rTest(old_r);
4730  return new_r;
4731}
4732
4733// use this for global orderings consisting of two blocks
4734static ring rAssure_Global(rRingOrder_t b1, rRingOrder_t b2, const ring r)
4735{
4736  int r_blocks = rBlocks(r);
4737
4738  assume(b1 == ringorder_c || b1 == ringorder_C ||
4739         b2 == ringorder_c || b2 == ringorder_C ||
4740         b2 == ringorder_S);
4741  if ((r_blocks == 3) &&
4742      (r->order[0] == b1) &&
4743      (r->order[1] == b2) &&
4744      (r->order[2] == 0))
4745    return r;
4746  ring res = rCopy0(r, FALSE, FALSE);
4747  res->order = (rRingOrder_t*)omAlloc0(3*sizeof(rRingOrder_t));
4748  res->block0 = (int*)omAlloc0(3*sizeof(int));
4749  res->block1 = (int*)omAlloc0(3*sizeof(int));
4750  res->wvhdl = (int**)omAlloc0(3*sizeof(int*));
4751  res->order[0] = b1;
4752  res->order[1] = b2;
4753  if (b1 == ringorder_c || b1 == ringorder_C)
4754  {
4755    res->block0[1] = 1;
4756    res->block1[1] = r->N;
4757  }
4758  else
4759  {
4760    res->block0[0] = 1;
4761    res->block1[0] = r->N;
4762  }
4763  rComplete(res, 1);
4764  if (r->qideal!=NULL) res->qideal= idrCopyR_NoSort(r->qideal, r, res);
4765#ifdef HAVE_PLURAL
4766  if (rIsPluralRing(r))
4767  {
4768    if ( nc_rComplete(r, res, false) ) // no qideal!
4769    {
4770#ifndef SING_NDEBUG
4771      WarnS("error in nc_rComplete");
4772#endif
4773    }
4774  }
4775#endif
4776//  rChangeCurrRing(res);
4777  return res;
4778}
4779
4780ring rAssure_InducedSchreyerOrdering(const ring r, BOOLEAN complete/* = TRUE*/, int sgn/* = 1*/)
4781{ // TODO: ???? Add leading Syz-comp ordering here...????
4782
4783#if MYTEST
4784    Print("rAssure_InducedSchreyerOrdering(r, complete = %d, sgn = %d): r: \n", complete, sgn);
4785    rWrite(r);
4786#ifdef RDEBUG
4787    rDebugPrint(r);
4788#endif
4789    PrintLn();
4790#endif
4791  assume((sgn == 1) || (sgn == -1));
4792
4793  ring res=rCopy0(r, FALSE, FALSE); // No qideal & ordering copy.
4794
4795  int n = rBlocks(r); // Including trailing zero!
4796
4797  // Create 2 more blocks for prefix/suffix:
4798  res->order=(rRingOrder_t *)omAlloc0((n+2)*sizeof(rRingOrder_t)); // 0  ..  n+1
4799  res->block0=(int *)omAlloc0((n+2)*sizeof(int));
4800  res->block1=(int *)omAlloc0((n+2)*sizeof(int));
4801  int ** wvhdl =(int **)omAlloc0((n+2)*sizeof(int**));
4802
4803  // Encapsulate all existing blocks between induced Schreyer ordering markers: prefix and suffix!
4804  // Note that prefix and suffix have the same ringorder marker and only differ in block[] parameters!
4805
4806  // new 1st block
4807  int j = 0;
4808  res->order[j] = ringorder_IS; // Prefix
4809  res->block0[j] = res->block1[j] = 0;
4810  // wvhdl[j] = NULL;
4811  j++;
4812
4813  for(int i = 0; (i <= n) && (r->order[i] != 0); i++, j++) // i = [0 .. n-1] <- non-zero old blocks
4814  {
4815    res->order [j] = r->order [i];
4816    res->block0[j] = r->block0[i];
4817    res->block1[j] = r->block1[i];
4818
4819    if (r->wvhdl[i] != NULL)
4820    {
4821      wvhdl[j] = (int*) omMemDup(r->wvhdl[i]);
4822    } // else wvhdl[j] = NULL;
4823  }
4824
4825  // new last block
4826  res->order [j] = ringorder_IS; // Suffix
4827  res->block0[j] = res->block1[j] = sgn; // Sign of v[o]: 1 for C, -1 for c
4828  // wvhdl[j] = NULL;
4829  j++;
4830
4831  // res->order [j] = 0; // The End!
4832  res->wvhdl = wvhdl;
4833
4834  // j == the last zero block now!
4835  assume(j == (n+1));
4836  assume(res->order[0]==ringorder_IS);
4837  assume(res->order[j-1]==ringorder_IS);
4838  assume(res->order[j]==0);
4839
4840
4841  if (complete)
4842  {
4843    rComplete(res, 1);
4844
4845#ifdef HAVE_PLURAL
4846    if (rIsPluralRing(r))
4847    {
4848      if ( nc_rComplete(r, res, false) ) // no qideal!
4849      {
4850#ifndef SING_NDEBUG
4851        WarnS("error in nc_rComplete");      // cleanup?//      rDelete(res);//      return r;      // just go on..
4852#endif
4853      }
4854    }
4855    assume(rIsPluralRing(r) == rIsPluralRing(res));
4856#endif
4857
4858
4859#ifdef HAVE_PLURAL
4860    ring old_ring = r;
4861#endif
4862
4863    if (r->qideal!=NULL)
4864    {
4865      res->qideal= idrCopyR_NoSort(r->qideal, r, res);
4866
4867      assume(id_RankFreeModule(res->qideal, res) == 0);
4868
4869#ifdef HAVE_PLURAL
4870      if( rIsPluralRing(res) )
4871        if( nc_SetupQuotient(res, r, true) )
4872        {
4873//          WarnS("error in nc_SetupQuotient"); // cleanup?      rDelete(res);       return r;  // just go on...?
4874        }
4875
4876#endif
4877      assume(id_RankFreeModule(res->qideal, res) == 0);
4878    }
4879
4880#ifdef HAVE_PLURAL
4881    assume((res->qideal==NULL) == (old_ring->qideal==NULL));
4882    assume(rIsPluralRing(res) == rIsPluralRing(old_ring));
4883    assume(rIsSCA(res) == rIsSCA(old_ring));
4884    assume(ncRingType(res) == ncRingType(old_ring));
4885#endif
4886  }
4887
4888  return res;
4889}
4890
4891ring rAssure_dp_S(const ring r)
4892{
4893  return rAssure_Global(ringorder_dp, ringorder_S, r);
4894}
4895
4896ring rAssure_dp_C(const ring r)
4897{
4898  return rAssure_Global(ringorder_dp, ringorder_C, r);
4899}
4900
4901ring rAssure_C_dp(const ring r)
4902{
4903  return rAssure_Global(ringorder_C, ringorder_dp, r);
4904}
4905
4906ring rAssure_c_dp(const ring r)
4907{
4908  return rAssure_Global(ringorder_c, ringorder_dp, r);
4909}
4910
4911
4912
4913/// Finds p^th IS ordering, and returns its position in r->typ[]
4914/// returns -1 if something went wrong!
4915/// p - starts with 0!
4916int rGetISPos(const int p, const ring r)
4917{
4918  // Put the reference set F into the ring -ordering -recor
4919#if MYTEST
4920  Print("rIsIS(p: %d)\nF:", p);
4921  PrintLn();
4922#endif
4923
4924  if (r->typ==NULL)
4925  {
4926//    dReportError("'rIsIS:' Error: wrong ring! (typ == NULL)");
4927    return -1;
4928  }
4929
4930  int j = p; // Which IS record to use...
4931  for( int pos = 0; pos < r->OrdSize; pos++ )
4932    if( r->typ[pos].ord_typ == ro_is)
4933      if( j-- == 0 )
4934        return pos;
4935
4936  return -1;
4937}
4938
4939
4940
4941
4942
4943
4944/// Changes r by setting induced ordering parameters: limit and reference leading terms
4945/// F belong to r, we will DO a copy!
4946/// We will use it AS IS!
4947/// returns true is everything was allright!
4948BOOLEAN rSetISReference(const ring r, const ideal F, const int i, const int p)
4949{
4950  // Put the reference set F into the ring -ordering -recor
4951
4952  if (r->typ==NULL)
4953  {
4954    dReportError("Error: WRONG USE of rSetISReference: wrong ring! (typ == NULL)");
4955    return FALSE;
4956  }
4957
4958
4959  int pos = rGetISPos(p, r);
4960
4961  if( pos == -1 )
4962  {
4963    dReportError("Error: WRONG USE of rSetISReference: specified ordering block was not found!!!" );
4964    return FALSE;
4965  }
4966
4967#if MYTEST
4968  if( i != r->typ[pos].data.is.limit )
4969    Print("Changing record on pos: %d\nOld limit: %d --->> New Limit: %d\n", pos, r->typ[pos].data.is.limit, i);
4970#endif
4971
4972  const ideal FF = idrHeadR(F, r, r); // id_Copy(F, r); // ???
4973
4974
4975  if( r->typ[pos].data.is.F != NULL)
4976  {
4977#if MYTEST
4978    PrintS("Deleting old reference set F... \n");        // idShow(r->typ[pos].data.is.F, r);         PrintLn();
4979#endif
4980    id_Delete(&r->typ[pos].data.is.F, r);
4981    r->typ[pos].data.is.F = NULL;
4982  }
4983
4984  assume(r->typ[pos].data.is.F == NULL);
4985
4986  r->typ[pos].data.is.F = FF; // F is owened by ring now! TODO: delete at the end!
4987
4988  r->typ[pos].data.is.limit = i; // First induced component
4989
4990#if MYTEST
4991  PrintS("New reference set FF : \n");        idShow(FF, r, r, 1);         PrintLn();
4992#endif
4993
4994  return TRUE;
4995}
4996
4997#ifdef PDEBUG
4998VAR int pDBsyzComp=0;
4999#endif
5000
5001
5002void rSetSyzComp(int k, const ring r)
5003{
5004  if(k < 0)
5005  {
5006    dReportError("rSetSyzComp with negative limit!");
5007    return;
5008  }
5009
5010  assume( k >= 0 );
5011  if (TEST_OPT_PROT) Print("{%d}", k);
5012  if ((r->typ!=NULL) && (r->typ[0].ord_typ==ro_syz))
5013  {
5014    r->block0[0]=r->block1[0] = k;
5015    if( k == r->typ[0].data.syz.limit )
5016      return; // nothing to do
5017
5018    int i;
5019    if (r->typ[0].data.syz.limit == 0)
5020    {
5021      r->typ[0].data.syz.syz_index = (int*) omAlloc0((k+1)*sizeof(int));
5022      r->typ[0].data.syz.syz_index[0] = 0;
5023      r->typ[0].data.syz.curr_index = 1;
5024    }
5025    else
5026    {
5027      r->typ[0].data.syz.syz_index = (int*)
5028        omReallocSize(r->typ[0].data.syz.syz_index,
5029                (r->typ[0].data.syz.limit+1)*sizeof(int),
5030                (k+1)*sizeof(int));
5031    }
5032    for (i=r->typ[0].data.syz.limit + 1; i<= k; i++)
5033    {
5034      r->typ[0].data.syz.syz_index[i] =
5035        r->typ[0].data.syz.curr_index;
5036    }
5037    if(k < r->typ[0].data.syz.limit) // ?
5038    {
5039#ifndef SING_NDEBUG
5040      Warn("rSetSyzComp called with smaller limit (%d) as before (%d)", k, r->typ[0].data.syz.limit);
5041#endif
5042      r->typ[0].data.syz.curr_index = 1 + r->typ[0].data.syz.syz_index[k];
5043    }
5044
5045
5046    r->typ[0].data.syz.limit = k;
5047    r->typ[0].data.syz.curr_index++;
5048  }
5049  else if(
5050            (r->typ!=NULL) &&
5051            (r->typ[0].ord_typ==ro_isTemp)
5052           )
5053  {
5054//      (r->typ[currRing->typ[0].data.isTemp.suffixpos].data.is.limit == k)
5055#ifndef SING_NDEBUG
5056    Warn("rSetSyzComp(%d) in an IS ring! Be careful!", k);
5057#endif
5058  }
5059  else if (r->order[0]==ringorder_s)
5060  {
5061    r->block0[0] = r->block1[0] = k;
5062  }
5063  else if (r->order[0]!=ringorder_c)
5064  {
5065    dReportError("syzcomp in incompatible ring");
5066  }
5067#ifdef PDEBUG
5068  EXTERN_VAR int pDBsyzComp;
5069  pDBsyzComp=k;
5070#endif
5071}
5072
5073// return the max-comonent wchich has syzIndex i
5074int rGetMaxSyzComp(int i, const ring r)
5075{
5076  if ((r->typ!=NULL) && (r->typ[0].ord_typ==ro_syz) &&
5077      r->typ[0].data.syz.limit > 0 && i > 0)
5078  {
5079    assume(i <= r->typ[0].data.syz.limit);
5080    int j;
5081    for (j=0; j<r->typ[0].data.syz.limit; j++)
5082    {
5083      if (r->typ[0].data.syz.syz_index[j] == i  &&
5084          r->typ[0].data.syz.syz_index[j+1] != i)
5085      {
5086        assume(r->typ[0].data.syz.syz_index[j+1] == i+1);
5087        return j;
5088      }
5089    }
5090    return r->typ[0].data.syz.limit;
5091  }
5092  else
5093  {
5094  #ifndef SING_NDEBUG
5095    WarnS("rGetMaxSyzComp: order c");
5096  #endif
5097    return 0;
5098  }
5099}
5100
5101BOOLEAN rRing_is_Homog(ring r)
5102{
5103  if (r == NULL) return FALSE;
5104  int i, j, nb = rBlocks(r);
5105  for (i=0; i<nb; i++)
5106  {
5107    if (r->wvhdl[i] != NULL)
5108    {
5109      int length = r->block1[i] - r->block0[i];
5110      int* wvhdl = r->wvhdl[i];
5111      if (r->order[i] == ringorder_M) length *= length;
5112      assume(omSizeOfAddr(wvhdl) >= length*sizeof(int));
5113
5114      for (j=0; j< length; j++)
5115      {
5116        if (wvhdl[j] != 0 && wvhdl[j] != 1) return FALSE;
5117      }
5118    }
5119  }
5120  return TRUE;
5121}
5122
5123BOOLEAN rRing_has_CompLastBlock(ring r)
5124{
5125  assume(r != NULL);
5126  int lb = rBlocks(r) - 2;
5127  return (r->order[lb] == ringorder_c || r->order[lb] == ringorder_C);
5128}
5129
5130n_coeffType rFieldType(ring r)
5131{
5132  return (r->cf->type);
5133  if (rField_is_Zp(r))     return n_Zp;
5134  if (rField_is_Q(r))      return n_Q;
5135  if (rField_is_R(r))      return n_R;
5136  if (rField_is_GF(r))     return n_GF;
5137  if (rField_is_long_R(r)) return n_long_R;
5138  if (rField_is_Zp_a(r))   return getCoeffType(r->cf);
5139  if (rField_is_Q_a(r))    return getCoeffType(r->cf);
5140  if (rField_is_long_C(r)) return n_long_C;
5141  if (rField_is_Z(r))         return n_Z;
5142  if (rField_is_Zn(r))        return n_Zn;
5143  if (rField_is_Ring_PtoM(r)) return n_Znm;
5144  if (rField_is_Ring_2toM(r)) return  n_Z2m;
5145
5146  return n_unknown;
5147}
5148
5149int64 * rGetWeightVec(const ring r)
5150{
5151  assume(r!=NULL);
5152  assume(r->OrdSize>0);
5153  int i=0;
5154  while((r->typ[i].ord_typ!=ro_wp64) && (r->typ[i].ord_typ>0)) i++;
5155  assume(r->typ[i].ord_typ==ro_wp64);
5156  return (int64*)(r->typ[i].data.wp64.weights64);
5157}
5158
5159void rSetWeightVec(ring r, int64 *wv)
5160{
5161  assume(r!=NULL);
5162  assume(r->OrdSize>0);
5163  assume(r->typ[0].ord_typ==ro_wp64);
5164  memcpy(r->typ[0].data.wp64.weights64,wv,r->N*sizeof(int64));
5165}
5166
5167#include <ctype.h>
5168
5169static int rRealloc1(ring r, int size, int pos)
5170{
5171  r->order=(rRingOrder_t*)omReallocSize(r->order, size*sizeof(rRingOrder_t), (size+1)*sizeof(rRingOrder_t));
5172  r->block0=(int*)omReallocSize(r->block0, size*sizeof(int), (size+1)*sizeof(int));
5173  r->block1=(int*)omReallocSize(r->block1, size*sizeof(int), (size+1)*sizeof(int));
5174  r->wvhdl=(int **)omReallocSize(r->wvhdl,size*sizeof(int *), (size+1)*sizeof(int *));
5175  for(int k=size; k>pos; k--) r->wvhdl[k]=r->wvhdl[k-1];
5176  r->order[size]=(rRingOrder_t)0;
5177  size++;
5178  return size;
5179}
5180#if 0 // currently unused
5181static int rReallocM1(ring r, int size, int pos)
5182{
5183  r->order=(int*)omReallocSize(r->order, size*sizeof(int), (size-1)*sizeof(int));
5184  r->block0=(int*)omReallocSize(r->block0, size*sizeof(int), (size-1)*sizeof(int));
5185  r->block1=(int*)omReallocSize(r->block1, size*sizeof(int), (size-1)*sizeof(int));
5186  r->wvhdl=(int **)omReallocSize(r->wvhdl,size*sizeof(int *), (size-1)*sizeof(int *));
5187  for(int k=pos+1; k<size; k++) r->wvhdl[k]=r->wvhdl[k+1];
5188  size--;
5189  return size;
5190}
5191#endif
5192static void rOppWeight(int *w, int l)
5193{
5194  int i2=(l+1)/2;
5195  for(int j=0; j<=i2; j++)
5196  {
5197    int t=w[j];
5198    w[j]=w[l-j];
5199    w[l-j]=t;
5200  }
5201}
5202
5203#define rOppVar(R,I) (rVar(R)+1-I)
5204
5205ring rOpposite(ring src)
5206  /* creates an opposite algebra of R */
5207  /* that is R^opp, where f (*^opp) g = g*f  */
5208  /* treats the case of qring */
5209{
5210  if (src == NULL) return(NULL);
5211
5212#ifdef RDEBUG
5213  rTest(src);
5214#endif
5215
5216  //rChangeCurrRing(src);
5217
5218#ifdef RDEBUG
5219  rTest(src);
5220//  rWrite(src);
5221//  rDebugPrint(src);
5222#endif
5223
5224
5225  ring r = rCopy0(src,FALSE); /* qideal will be deleted later on!!! */
5226
5227  // change vars v1..vN -> vN..v1
5228  int i;
5229  int i2 = (rVar(r)-1)/2;
5230  for(i=i2; i>=0; i--)
5231  {
5232    // index: 0..N-1
5233    //Print("ex var names: %d <-> %d\n",i,rOppVar(r,i));
5234    // exchange names
5235    char *p;
5236    p = r->names[rVar(r)-1-i];
5237    r->names[rVar(r)-1-i] = r->names[i];
5238    r->names[i] = p;
5239  }
5240//  i2=(rVar(r)+1)/2;
5241//  for(int i=i2; i>0; i--)
5242//  {
5243//    // index: 1..N
5244//    //Print("ex var places: %d <-> %d\n",i,rVar(r)+1-i);
5245//    // exchange VarOffset
5246//    int t;
5247//    t=r->VarOffset[i];
5248//    r->VarOffset[i]=r->VarOffset[rOppVar(r,i)];
5249//    r->VarOffset[rOppVar(r,i)]=t;
5250//  }
5251  // change names:
5252  for (i=rVar(r)-1; i>=0; i--)
5253  {
5254    char *p=r->names[i];
5255    if(isupper(*p)) *p = tolower(*p);
5256    else            *p = toupper(*p);
5257  }
5258  // change ordering: listing
5259  // change ordering: compare
5260//  for(i=0; i<r->OrdSize; i++)
5261//  {
5262//    int t,tt;
5263//    switch(r->typ[i].ord_typ)
5264//    {
5265//      case ro_dp:
5266//      //
5267//        t=r->typ[i].data.dp.start;
5268//        r->typ[i].data.dp.start=rOppVar(r,r->typ[i].data.dp.end);
5269//        r->typ[i].data.dp.end=rOppVar(r,t);
5270//        break;
5271//      case ro_wp:
5272//      case ro_wp_neg:
5273//      {
5274//        t=r->typ[i].data.wp.start;
5275//        r->typ[i].data.wp.start=rOppVar(r,r->typ[i].data.wp.end);
5276//        r->typ[i].data.wp.end=rOppVar(r,t);
5277//        // invert r->typ[i].data.wp.weights
5278//        rOppWeight(r->typ[i].data.wp.weights,
5279//                   r->typ[i].data.wp.end-r->typ[i].data.wp.start);
5280//        break;
5281//      }
5282//      //case ro_wp64:
5283//      case ro_syzcomp:
5284//      case ro_syz:
5285//         WerrorS("not implemented in rOpposite");
5286//         // should not happen
5287//         break;
5288//
5289//      case ro_cp:
5290//        t=r->typ[i].data.cp.start;
5291//        r->typ[i].data.cp.start=rOppVar(r,r->typ[i].data.cp.end);
5292//        r->typ[i].data.cp.end=rOppVar(r,t);
5293//        break;
5294//      case ro_none:
5295//      default:
5296//       Werror("unknown type in rOpposite(%d)",r->typ[i].ord_typ);
5297//       break;
5298//    }
5299//  }
5300  // Change order/block structures (needed for rPrint, rAdd etc.)
5301  int j=0;
5302  int l=rBlocks(src);
5303  for(i=0; src->order[i]!=0; i++)
5304  {
5305    switch (src->order[i])
5306    {
5307      case ringorder_c: /* c-> c */
5308      case ringorder_C: /* C-> C */
5309      case ringorder_no /*=0*/: /* end-of-block */
5310        r->order[j]=src->order[i];
5311        j++; break;
5312      case ringorder_lp: /* lp -> rp */
5313        r->order[j]=ringorder_rp;
5314        r->block0[j]=rOppVar(r, src->block1[i]);
5315        r->block1[j]=rOppVar(r, src->block0[i]);
5316        break;
5317      case ringorder_rp: /* rp -> lp */
5318        r->order[j]=ringorder_lp;
5319        r->block0[j]=rOppVar(r, src->block1[i]);
5320        r->block1[j]=rOppVar(r, src->block0[i]);
5321        break;
5322      case ringorder_dp: /* dp -> a(1..1),ls */
5323      {
5324        l=rRealloc1(r,l,j);
5325        r->order[j]=ringorder_a;
5326        r->block0[j]=rOppVar(r, src->block1[i]);
5327        r->block1[j]=rOppVar(r, src->block0[i]);
5328        r->wvhdl[j]=(int*)omAlloc((r->block1[j]-r->block0[j]+1)*sizeof(int));
5329        for(int k=r->block0[j]; k<=r->block1[j]; k++)
5330          r->wvhdl[j][k-r->block0[j]]=1;
5331        j++;
5332        r->order[j]=ringorder_ls;
5333        r->block0[j]=rOppVar(r, src->block1[i]);
5334        r->block1[j]=rOppVar(r, src->block0[i]);
5335        j++;
5336        break;
5337      }
5338      case ringorder_Dp: /* Dp -> a(1..1),rp */
5339      {
5340        l=rRealloc1(r,l,j);
5341        r->order[j]=ringorder_a;
5342        r->block0[j]=rOppVar(r, src->block1[i]);
5343        r->block1[j]=rOppVar(r, src->block0[i]);
5344        r->wvhdl[j]=(int*)omAlloc((r->block1[j]-r->block0[j]+1)*sizeof(int));
5345        for(int k=r->block0[j]; k<=r->block1[j]; k++)
5346          r->wvhdl[j][k-r->block0[j]]=1;
5347        j++;
5348        r->order[j]=ringorder_rp;
5349        r->block0[j]=rOppVar(r, src->block1[i]);
5350        r->block1[j]=rOppVar(r, src->block0[i]);
5351        j++;
5352        break;
5353      }
5354      case ringorder_wp: /* wp -> a(...),ls */
5355      {
5356        l=rRealloc1(r,l,j);
5357        r->order[j]=ringorder_a;
5358        r->block0[j]=rOppVar(r, src->block1[i]);
5359        r->block1[j]=rOppVar(r, src->block0[i]);
5360        r->wvhdl[j]=r->wvhdl[j+1]; r->wvhdl[j+1]=NULL;
5361        rOppWeight(r->wvhdl[j], r->block1[j]-r->block0[j]);
5362        j++;
5363        r->order[j]=ringorder_ls;
5364        r->block0[j]=rOppVar(r, src->block1[i]);
5365        r->block1[j]=rOppVar(r, src->block0[i]);
5366        j++;
5367        break;
5368      }
5369      case ringorder_Wp: /* Wp -> a(...),rp */
5370      {
5371        l=rRealloc1(r,l,j);
5372        r->order[j]=ringorder_a;
5373        r->block0[j]=rOppVar(r, src->block1[i]);
5374        r->block1[j]=rOppVar(r, src->block0[i]);
5375        r->wvhdl[j]=r->wvhdl[j+1]; r->wvhdl[j+1]=NULL;
5376        rOppWeight(r->wvhdl[j], r->block1[j]-r->block0[j]);
5377        j++;
5378        r->order[j]=ringorder_rp;
5379        r->block0[j]=rOppVar(r, src->block1[i]);
5380        r->block1[j]=rOppVar(r, src->block0[i]);
5381        j++;
5382        break;
5383      }
5384      case ringorder_M: /* M -> M */
5385      {
5386        r->order[j]=ringorder_M;
5387        r->block0[j]=rOppVar(r, src->block1[i]);
5388        r->block1[j]=rOppVar(r, src->block0[i]);
5389        int n=r->block1[j]-r->block0[j];
5390        /* M is a (n+1)x(n+1) matrix */
5391        for (int nn=0; nn<=n; nn++)
5392        {
5393          rOppWeight(&(r->wvhdl[j][nn*(n+1)]), n /*r->block1[j]-r->block0[j]*/);
5394        }
5395        j++;
5396        break;
5397      }
5398      case ringorder_a: /*  a(...),ls -> wp/dp */
5399      {
5400        r->block0[j]=rOppVar(r, src->block1[i]);
5401        r->block1[j]=rOppVar(r, src->block0[i]);
5402        rOppWeight(r->wvhdl[j], r->block1[j]-r->block0[j]);
5403        if (src->order[i+1]==ringorder_ls)
5404        {
5405          r->order[j]=ringorder_wp;
5406          i++;
5407          //l=rReallocM1(r,l,j);
5408        }
5409        else
5410        {
5411          r->order[j]=ringorder_a;
5412        }
5413        j++;
5414        break;
5415      }
5416      // not yet done:
5417      case ringorder_ls:
5418      case ringorder_rs:
5419      case ringorder_ds:
5420      case ringorder_Ds:
5421      case ringorder_ws:
5422      case ringorder_Ws:
5423      case ringorder_am:
5424      case ringorder_a64:
5425      // should not occur:
5426      case ringorder_S:
5427      case ringorder_IS:
5428      case ringorder_s:
5429      case ringorder_aa:
5430      case ringorder_L:
5431      case ringorder_unspec:
5432        Werror("order %s not (yet) supported", rSimpleOrdStr(src->order[i]));
5433        break;
5434    }
5435  }
5436  rComplete(r);
5437
5438
5439#ifdef RDEBUG
5440  rTest(r);
5441#endif
5442
5443  //rChangeCurrRing(r);
5444
5445#ifdef RDEBUG
5446  rTest(r);
5447//  rWrite(r);
5448//  rDebugPrint(r);
5449#endif
5450
5451
5452#ifdef HAVE_PLURAL
5453  // now, we initialize a non-comm structure on r
5454  if (rIsPluralRing(src))
5455  {
5456//    assume( currRing == r);
5457
5458    int *perm       = (int *)omAlloc0((rVar(r)+1)*sizeof(int));
5459    int *par_perm   = NULL;
5460    nMapFunc nMap   = n_SetMap(src->cf,r->cf);
5461    int ni,nj;
5462    for(i=1; i<=r->N; i++)
5463    {
5464      perm[i] = rOppVar(r,i);
5465    }
5466
5467    matrix C = mpNew(rVar(r),rVar(r));
5468    matrix D = mpNew(rVar(r),rVar(r));
5469
5470    for (i=1; i< rVar(r); i++)
5471    {
5472      for (j=i+1; j<=rVar(r); j++)
5473      {
5474        ni = r->N +1 - i;
5475        nj = r->N +1 - j; /* i<j ==>   nj < ni */
5476
5477        assume(MATELEM(src->GetNC()->C,i,j) != NULL);
5478        MATELEM(C,nj,ni) = p_PermPoly(MATELEM(src->GetNC()->C,i,j),perm,src,r, nMap,par_perm,rPar(src));
5479
5480        if(MATELEM(src->GetNC()->D,i,j) != NULL)
5481          MATELEM(D,nj,ni) = p_PermPoly(MATELEM(src->GetNC()->D,i,j),perm,src,r, nMap,par_perm,rPar(src));
5482      }
5483    }
5484
5485    id_Test((ideal)C, r);
5486    id_Test((ideal)D, r);
5487
5488    if (nc_CallPlural(C, D, NULL, NULL, r, false, false, true, r)) // no qring setup!
5489      WarnS("Error initializing non-commutative multiplication!");
5490
5491#ifdef RDEBUG
5492    rTest(r);
5493//    rWrite(r);
5494//    rDebugPrint(r);
5495#endif
5496
5497    assume( r->GetNC()->IsSkewConstant == src->GetNC()->IsSkewConstant);
5498
5499    omFreeSize((ADDRESS)perm,(rVar(r)+1)*sizeof(int));
5500  }
5501#endif /* HAVE_PLURAL */
5502
5503  /* now oppose the qideal for qrings */
5504  if (src->qideal != NULL)
5505  {
5506    id_Delete(&(r->qideal), r);
5507
5508#ifdef HAVE_PLURAL
5509    r->qideal = idOppose(src, src->qideal, r); // into the currRing: r
5510#else
5511    r->qideal = id_Copy(src->qideal, r); // ?
5512#endif
5513
5514#ifdef HAVE_PLURAL
5515    if( rIsPluralRing(r) )
5516    {
5517      nc_SetupQuotient(r);
5518#ifdef RDEBUG
5519      rTest(r);
5520//      rWrite(r);
5521//      rDebugPrint(r);
5522#endif
5523    }
5524#endif
5525  }
5526#ifdef HAVE_PLURAL
5527  if( rIsPluralRing(r) )
5528    assume( ncRingType(r) == ncRingType(src) );
5529#endif
5530  rTest(r);
5531
5532  return r;
5533}
5534
5535ring rEnvelope(ring R)
5536  /* creates an enveloping algebra of R */
5537  /* that is R^e = R \tensor_K R^opp */
5538{
5539  ring Ropp = rOpposite(R);
5540  ring Renv = NULL;
5541  int stat = rSum(R, Ropp, Renv); /* takes care of qideals */
5542  if ( stat <=0 )
5543    WarnS("Error in rEnvelope at rSum");
5544  rTest(Renv);
5545  return Renv;
5546}
5547
5548#ifdef HAVE_PLURAL
5549BOOLEAN nc_rComplete(const ring src, ring dest, bool bSetupQuotient)
5550/* returns TRUE is there were errors */
5551/* dest is actualy equals src with the different ordering */
5552/* we map src->nc correctly to dest->src */
5553/* to be executed after rComplete, before rChangeCurrRing */
5554{
5555// NOTE: Originally used only by idElimination to transfer NC structure to dest
5556// ring created by dirty hack (without nc_CallPlural)
5557  rTest(src);
5558
5559  assume(!rIsPluralRing(dest)); // destination must be a newly constructed commutative ring
5560
5561  if (!rIsPluralRing(src))
5562  {
5563    return FALSE;
5564  }
5565
5566  const int N = dest->N;
5567
5568  assume(src->N == N);
5569
5570//  ring save = currRing;
5571
5572//  if (dest != save)
5573//    rChangeCurrRing(dest);
5574
5575  const ring srcBase = src;
5576
5577  assume( n_SetMap(srcBase->cf,dest->cf) == n_SetMap(dest->cf,dest->cf) ); // currRing is important here!
5578
5579  matrix C = mpNew(N,N); // ring independent
5580  matrix D = mpNew(N,N);
5581
5582  matrix C0 = src->GetNC()->C;
5583  matrix D0 = src->GetNC()->D;
5584
5585  // map C and D into dest
5586  for (int i = 1; i < N; i++)
5587  {
5588    for (int j = i + 1; j <= N; j++)
5589    {
5590      const number n = n_Copy(p_GetCoeff(MATELEM(C0,i,j), srcBase), srcBase->cf); // src, mapping for coeffs into currRing = dest!
5591      const poly   p = p_NSet(n, dest);
5592      MATELEM(C,i,j) = p;
5593      if (MATELEM(D0,i,j) != NULL)
5594        MATELEM(D,i,j) = prCopyR(MATELEM(D0,i,j), srcBase, dest); // ?
5595    }
5596  }
5597  /* One must test C and D _only_ in r->GetNC()->basering!!! not in r!!! */
5598
5599  id_Test((ideal)C, dest);
5600  id_Test((ideal)D, dest);
5601
5602  if (nc_CallPlural(C, D, NULL, NULL, dest, bSetupQuotient, false, true, dest)) // also takes care about quotient ideal
5603  {
5604    //WarnS("Error transferring non-commutative structure");
5605    // error message should be in the interpreter interface
5606
5607    mp_Delete(&C, dest);
5608    mp_Delete(&D, dest);
5609
5610//    if (currRing != save)
5611//       rChangeCurrRing(save);
5612
5613    return TRUE;
5614  }
5615
5616//  mp_Delete(&C, dest); // used by nc_CallPlural!
5617//  mp_Delete(&D, dest);
5618
5619//  if (dest != save)
5620//    rChangeCurrRing(save);
5621
5622  assume(rIsPluralRing(dest));
5623  return FALSE;
5624}
5625#endif
5626
5627void rModify_a_to_A(ring r)
5628// to be called BEFORE rComplete:
5629// changes every Block with a(...) to A(...)
5630{
5631   int i=0;
5632   int j;
5633   while(r->order[i]!=0)
5634   {
5635      if (r->order[i]==ringorder_a)
5636      {
5637        r->order[i]=ringorder_a64;
5638        int *w=r->wvhdl[i];
5639        int64 *w64=(int64 *)omAlloc((r->block1[i]-r->block0[i]+1)*sizeof(int64));
5640        for(j=r->block1[i]-r->block0[i];j>=0;j--)
5641                w64[j]=(int64)w[j];
5642        r->wvhdl[i]=(int*)w64;
5643        omFreeSize(w,(r->block1[i]-r->block0[i]+1)*sizeof(int));
5644      }
5645      i++;
5646   }
5647}
5648
5649
5650poly rGetVar(const int varIndex, const ring r)
5651{
5652    poly p = p_ISet(1, r);
5653    p_SetExp(p, varIndex, 1, r);
5654    p_Setm(p, r);
5655    return p;
5656}
5657
5658
5659/// TODO: rewrite somehow...
5660int n_IsParam(const number m, const ring r)
5661{
5662  assume(r != NULL);
5663  const coeffs C = r->cf;
5664  assume(C != NULL);
5665
5666  assume( nCoeff_is_Extension(C) );
5667
5668  const n_coeffType _filed_type = getCoeffType(C);
5669
5670  if(( _filed_type == n_algExt )||( _filed_type == n_polyExt ))
5671    return naIsParam(m, C);
5672
5673  if( _filed_type == n_transExt )
5674    return ntIsParam(m, C);
5675
5676  Werror("n_IsParam: IsParam is not to be used for (coeff_type = %d)",getCoeffType(C));
5677
5678  return 0;
5679}
5680
5681ring rPlusVar(const ring r, char *v,int left)
5682{
5683  if (r->order[2]!=0)
5684  {
5685    WerrorS("only for rings with an ordering of one block");
5686    return NULL;
5687  }
5688  int p;
5689  if((r->order[0]==ringorder_C)
5690  ||(r->order[0]==ringorder_c))
5691    p=1;
5692  else
5693    p=0;
5694  if((r->order[p]!=ringorder_dp)
5695  && (r->order[p]!=ringorder_Dp)
5696  && (r->order[p]!=ringorder_lp)
5697  && (r->order[p]!=ringorder_rp)
5698  && (r->order[p]!=ringorder_ds)
5699  && (r->order[p]!=ringorder_Ds)
5700  && (r->order[p]!=ringorder_ls))
5701  {
5702    WerrorS("ordering must be dp,Dp,lp,rp,ds,Ds or ls");
5703    return NULL;
5704  }
5705  for(int i=r->N-1;i>=0;i--)
5706  {
5707    if (strcmp(r->names[i],v)==0)
5708    {
5709      Werror("duplicate variable name >>%s<<",v);
5710      return NULL;
5711    }
5712  }
5713  ring R=rCopy0(r);
5714  char **names;
5715  #ifdef HAVE_SHIFTBBA
5716  if (rIsLPRing(r))
5717  {
5718    R->isLPring=r->isLPring+1;
5719    R->N=