source: git/Singular/ipshell.cc @ 7c5dd1

spielwiese
Last change on this file since 7c5dd1 was 7c5dd1, checked in by Hans Schoenemann <hannes@…>, 14 years ago
rNameCheck ->rRenaveVars git-svn-id: file:///usr/local/Singular/svn/trunk@12953 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100644
File size: 127.7 KB
Line 
1/****************************************
2*  Computer Algebra System SINGULAR     *
3****************************************/
4/* $Id$ */
5/*
6* ABSTRACT:
7*/
8
9//#include <stdlib.h>
10#include <stdio.h>
11#include <string.h>
12#include <ctype.h>
13#include <math.h>
14
15#include "mod2.h"
16#include "tok.h"
17#include "options.h"
18#include "ipid.h"
19#include "intvec.h"
20#include "omalloc.h"
21#include "febase.h"
22#include "polys.h"
23#include "prCopy.h"
24#include "ideals.h"
25#include "matpol.h"
26#include "kstd1.h"
27#include "ring.h"
28#include "subexpr.h"
29#include "maps.h"
30#include "syz.h"
31#include "numbers.h"
32#include "modulop.h"
33#include "longalg.h"
34#include "lists.h"
35#include "attrib.h"
36#include "ipconv.h"
37#include "silink.h"
38#include "stairc.h"
39#include "weight.h"
40#include "semic.h"
41#include "splist.h"
42#include "spectrum.h"
43#include "gnumpfl.h"
44#include "mpr_base.h"
45#include "ffields.h"
46#include "clapsing.h"
47#include "hutil.h"
48#include "gring.h"
49#include "ipshell.h"
50#ifdef HAVE_FACTORY
51#define SI_DONT_HAVE_GLOBAL_VARS
52#include <factory.h>
53#endif
54
55// define this if you want to use the fast_map routine for mapping ideals
56#define FAST_MAP
57
58#ifdef FAST_MAP
59#include "fast_maps.h"
60#endif
61
62leftv iiCurrArgs=NULL;
63idhdl iiCurrProc=NULL;
64int  traceit = 0;
65const char *lastreserved=NULL;
66
67int  myynest = -1;
68
69static BOOLEAN iiNoKeepRing=TRUE;
70
71/*0 implementation*/
72
73const char * iiTwoOps(int t)
74{
75  if (t<127)
76  {
77    static char ch[2];
78    switch (t)
79    {
80      case '&':
81        return "and";
82      case '|':
83        return "or";
84      default:
85        ch[0]=t;
86        ch[1]='\0';
87        return ch;
88    }
89  }
90  switch (t)
91  {
92    case COLONCOLON:  return "::";
93    case DOTDOT:      return "..";
94    //case PLUSEQUAL:   return "+=";
95    //case MINUSEQUAL:  return "-=";
96    case MINUSMINUS:  return "--";
97    case PLUSPLUS:    return "++";
98    case EQUAL_EQUAL: return "==";
99    case LE:          return "<=";
100    case GE:          return ">=";
101    case NOTEQUAL:    return "<>";
102    default:          return Tok2Cmdname(t);
103  }
104}
105
106static void list1(const char* s, idhdl h,BOOLEAN c, BOOLEAN fullname)
107{
108  char buffer[22];
109  int l;
110  char buf2[128];
111
112  if(fullname) sprintf(buf2, "%s::%s", "", IDID(h));
113  else sprintf(buf2, "%s", IDID(h));
114
115  Print("%s%-20.20s [%d]  ",s,buf2,IDLEV(h));
116  if (h == currRingHdl) PrintS("*");
117  PrintS(Tok2Cmdname((int)IDTYP(h)));
118
119  ipListFlag(h);
120  switch(IDTYP(h))
121  {
122    case INT_CMD:   Print(" %d",IDINT(h)); break;
123    case INTVEC_CMD:Print(" (%d)",IDINTVEC(h)->length()); break;
124    case INTMAT_CMD:Print(" %d x %d",IDINTVEC(h)->rows(),IDINTVEC(h)->cols());
125                    break;
126    case POLY_CMD:
127    case VECTOR_CMD:if (c)
128                    {
129                      PrintS(" ");wrp(IDPOLY(h));
130                      if(IDPOLY(h) != NULL)
131                      {
132                        Print(", %d monomial(s)",pLength(IDPOLY(h)));
133                      }
134                    }
135                    break;
136    case MODUL_CMD: Print(", rk %d", (int)(IDIDEAL(h)->rank));
137    case IDEAL_CMD: Print(", %u generator(s)",
138                    IDELEMS(IDIDEAL(h))); break;
139    case MAP_CMD:
140                    Print(" from %s",IDMAP(h)->preimage); break;
141    case MATRIX_CMD:Print(" %u x %u"
142                      ,MATROWS(IDMATRIX(h))
143                      ,MATCOLS(IDMATRIX(h))
144                    );
145                    break;
146    case PACKAGE_CMD:
147                    PrintS(" (");
148                    switch (IDPACKAGE(h)->language)
149                    {
150                        case LANG_SINGULAR: PrintS("S"); break;
151                        case LANG_C:        PrintS("C"); break;
152                        case LANG_TOP:      PrintS("T"); break;
153                        case LANG_NONE:     PrintS("N"); break;
154                        default:            PrintS("U");
155                    }
156                    if(IDPACKAGE(h)->libname!=NULL)
157                      Print(",%s", IDPACKAGE(h)->libname);
158                    PrintS(")");
159                    break;
160    case PROC_CMD: if(strlen(IDPROC(h)->libname)>0)
161                     Print(" from %s",IDPROC(h)->libname);
162                   if(IDPROC(h)->is_static)
163                     PrintS(" (static)");
164                   break;
165    case STRING_CMD:
166                   {
167                     char *s;
168                     l=strlen(IDSTRING(h));
169                     memset(buffer,0,22);
170                     strncpy(buffer,IDSTRING(h),si_min(l,20));
171                     if ((s=strchr(buffer,'\n'))!=NULL)
172                     {
173                       *s='\0';
174                     }
175                     PrintS(" ");
176                     PrintS(buffer);
177                     if((s!=NULL) ||(l>20))
178                     {
179                       Print("..., %d char(s)",l);
180                     }
181                     break;
182                   }
183    case LIST_CMD: Print(", size: %d",IDLIST(h)->nr+1);
184                   break;
185    case QRING_CMD:
186    case RING_CMD:
187                   if ((IDRING(h)==currRing) && (currRingHdl!=h))
188                     PrintS("(*)"); /* this is an alias to currRing */
189#ifdef RDEBUG
190                   if (traceit &TRACE_SHOW_RINGS)
191                     Print(" <%lx>",(long)(IDRING(h)));
192#endif
193                   break;
194    /*default:     break;*/
195  }
196  PrintLn();
197}
198
199void type_cmd(idhdl h)
200{
201  BOOLEAN oldShortOut = FALSE;
202
203  if (currRing != NULL)
204  {
205    oldShortOut = currRing->ShortOut;
206    currRing->ShortOut = 1;
207  }
208  list1("// ",h,FALSE,FALSE);
209  if (IDTYP(h)!=INT_CMD)
210  {
211    sleftv expr;
212    memset(&expr,0,sizeof(expr));
213    expr.rtyp=IDHDL;
214    expr.name=IDID(h);
215    expr.data=(void *)h;
216    expr.Print();
217  }
218  if (currRing != NULL)
219    currRing->ShortOut = oldShortOut;
220}
221
222static void killlocals0(int v, idhdl * localhdl, const ring r)
223{
224  idhdl h = *localhdl;
225  while (h!=NULL)
226  {
227    int vv;
228    //Print("consider %s, lev: %d:",IDID(h),IDLEV(h));
229    if ((vv=IDLEV(h))>0)
230    {
231      if (vv < v)
232      {
233        if (iiNoKeepRing)
234        {
235          //PrintS(" break\n");
236          return;
237        }
238        h = IDNEXT(h);
239        //PrintLn();
240      }
241      else //if (vv >= v)
242      {
243        idhdl nexth = IDNEXT(h);
244        killhdl2(h,localhdl,r);
245        h = nexth;
246        //PrintS("kill\n");
247      }
248    }
249    else
250    {
251      h = IDNEXT(h);
252      //PrintLn();
253    }
254  }
255}
256void killlocals_list(lists l,int v)
257{
258  int i;
259  for(i=l->nr; i>=0; i--)
260  {
261    if (l->m[i].rtyp == LIST_CMD)
262      killlocals_list((lists)l->m[i].data,v);
263    else if ((l->m[i].rtyp == RING_CMD) || (l->m[i].rtyp == QRING_CMD))
264      killlocals0(v,&(((ring)(l->m[i].data))->idroot),currRing);
265  }
266}
267void killlocals_rec(idhdl *root,int v, ring r)
268{
269  idhdl h=*root;
270  while (h!=NULL)
271  {
272    if (IDLEV(h)>=v)
273    {
274//      Print("kill %s, lev %d for lev %d\n",IDID(h),IDLEV(h),v);
275      idhdl n=IDNEXT(h);
276      killhdl2(h,root,r);
277      h=n;
278    }
279    else if (IDTYP(h)==PACKAGE_CMD)
280    {
281 //     Print("into pack %s, lev %d for lev %d\n",IDID(h),IDLEV(h),v);
282      if (IDPACKAGE(h)!=basePack)
283        killlocals_rec(&(IDRING(h)->idroot),v,r);
284      h=IDNEXT(h);
285    }
286    else if ((IDTYP(h)==RING_CMD)
287    ||(IDTYP(h)==QRING_CMD))
288    {
289      if ((IDRING(h)!=NULL) && (IDRING(h)->idroot!=NULL))
290      // we have to test IDRING(h)!=NULL: qring Q=groebner(...): killlocals
291      {
292  //    Print("into ring %s, lev %d for lev %d\n",IDID(h),IDLEV(h),v);
293        killlocals_rec(&(IDRING(h)->idroot),v,IDRING(h));
294      }
295      h=IDNEXT(h);
296    }
297    else
298    {
299//      Print("skip %s lev %d for lev %d\n",IDID(h),IDLEV(h),v);
300      h=IDNEXT(h);
301    }
302  }
303}
304BOOLEAN killlocals_list(int v, lists L)
305{
306  if (L==NULL) return FALSE;
307  BOOLEAN changed=FALSE;
308  int n=L->nr;
309  for(;n>=0;n--)
310  {
311    leftv h=&(L->m[n]);
312    void *d=h->data;
313    if (((h->rtyp==RING_CMD) || (h->rtyp==QRING_CMD))
314    && (((ring)d)->idroot!=NULL))
315    {
316      if (d!=currRing) {changed=TRUE;rChangeCurrRing((ring)d);}
317      killlocals0(v,&(((ring)h->data)->idroot),(ring)h->data);
318    }
319    else if (h->rtyp==LIST_CMD)
320      changed|=killlocals_list(v,(lists)d);
321  }
322  return changed;
323}
324void killlocals(int v)
325{
326  BOOLEAN changed=FALSE;
327  idhdl sh=currRingHdl;
328  ring cr=currRing;
329  if (sh!=NULL) changed=((IDLEV(sh)<v) || (IDRING(sh)->ref>0));
330  //if (changed) Print("currRing=%s(%x), lev=%d,ref=%d\n",IDID(sh),IDRING(sh),IDLEV(sh),IDRING(sh)->ref);
331
332  killlocals_rec(&(basePack->idroot),v,currRing);
333
334  if (iiRETURNEXPR_len > myynest)
335  {
336    int t=iiRETURNEXPR[myynest].Typ();
337    if ((/*iiRETURNEXPR[myynest].Typ()*/ t==RING_CMD)
338    || (/*iiRETURNEXPR[myynest].Typ()*/ t==QRING_CMD))
339    {
340      leftv h=&iiRETURNEXPR[myynest];
341      if (((ring)h->data)->idroot!=NULL)
342        killlocals0(v,&(((ring)h->data)->idroot),(ring)h->data);
343    }
344    else if (/*iiRETURNEXPR[myynest].Typ()*/ t==LIST_CMD)
345    {
346      leftv h=&iiRETURNEXPR[myynest];
347      changed |=killlocals_list(v,(lists)h->data);
348    }
349  }
350  if (changed)
351  {
352    currRingHdl=rFindHdl(cr,NULL,NULL);
353    if (currRingHdl==NULL)
354      currRing=NULL;
355    else
356      rChangeCurrRing(cr);
357  }
358
359  if (myynest<=1) iiNoKeepRing=TRUE;
360  //Print("end killlocals  >= %d\n",v);
361  //listall();
362}
363
364void list_cmd(int typ, const char* what, const char *prefix,BOOLEAN iterate, BOOLEAN fullname)
365{
366  idhdl h,start;
367  BOOLEAN all = typ<0;
368  BOOLEAN really_all=FALSE;
369  BOOLEAN do_packages=FALSE;
370
371  if ( typ == -1 ) do_packages=TRUE;
372  if ( typ==0 )
373  {
374    if (strcmp(what,"all")==0)
375    {
376      really_all=TRUE;
377      h=basePack->idroot;
378    }
379    else
380    {
381      h = ggetid(what);
382      if (h!=NULL)
383      {
384        if (iterate) list1(prefix,h,TRUE,fullname);
385        if (IDTYP(h)==ALIAS_CMD) PrintS("A");
386        if ((IDTYP(h)==RING_CMD)
387            || (IDTYP(h)==QRING_CMD)
388            //|| (IDTYP(h)==PACKE_CMD)
389        )
390        {
391          h=IDRING(h)->idroot;
392        }
393        else if((IDTYP(h)==PACKAGE_CMD) || (IDTYP(h)==POINTER_CMD))
394        {
395          //Print("list_cmd:package or pointer\n");
396          all=TRUE;typ=PROC_CMD;fullname=TRUE;really_all=TRUE;
397          h=IDPACKAGE(h)->idroot;
398        }
399        else
400          return;
401      }
402      else
403      {
404        Werror("%s is undefined",what);
405        return;
406      }
407    }
408    all=TRUE;
409  }
410  else if (RingDependend(typ))
411  {
412    h = currRing->idroot;
413  }
414  else
415    h = IDROOT;
416  start=h;
417  while (h!=NULL)
418  {
419    if ((all && (IDTYP(h)!=PROC_CMD) &&(IDTYP(h)!=PACKAGE_CMD))
420    || (typ == IDTYP(h))
421    || ((IDTYP(h)==QRING_CMD) && (typ==RING_CMD)))
422    {
423      list1(prefix,h,start==currRingHdl, fullname);
424      if (((IDTYP(h)==RING_CMD)||(IDTYP(h)==QRING_CMD))
425        && (really_all || (all && (h==currRingHdl)))
426        && ((IDLEV(h)==0)||(IDLEV(h)==myynest)))
427      {
428        list_cmd(0,IDID(h),"//      ",FALSE);
429      }
430      if (IDTYP(h)==PACKAGE_CMD && really_all)
431      {
432        package save_p=currPack;
433        currPack=IDPACKAGE(h);
434        list_cmd(0,IDID(h),"//      ",FALSE);
435        currPack=save_p;
436      }
437    }
438    h = IDNEXT(h);
439  }
440}
441
442void test_cmd(int i)
443{
444  int ii;
445
446  if (i<0)
447  {
448    ii= -i;
449    if (ii < 32)
450    {
451      test &= ~Sy_bit(ii);
452    }
453    else if (ii < 64)
454    {
455      verbose &= ~Sy_bit(ii-32);
456    }
457    else
458      WerrorS("out of bounds\n");
459  }
460  else if (i<32)
461  {
462    ii=i;
463    if (Sy_bit(ii) & kOptions)
464    {
465      Warn("Gerhard, use the option command");
466      test |= Sy_bit(ii);
467    }
468    else if (Sy_bit(ii) & validOpts)
469      test |= Sy_bit(ii);
470  }
471  else if (i<64)
472  {
473    ii=i-32;
474    verbose |= Sy_bit(ii);
475  }
476  else
477    WerrorS("out of bounds\n");
478}
479
480int exprlist_length(leftv v)
481{
482  int rc = 0;
483  while (v!=NULL)
484  {
485    switch (v->Typ())
486    {
487      case INT_CMD:
488      case POLY_CMD:
489      case VECTOR_CMD:
490      case NUMBER_CMD:
491        rc++;
492        break;
493      case INTVEC_CMD:
494      case INTMAT_CMD:
495        rc += ((intvec *)(v->Data()))->length();
496        break;
497      case MATRIX_CMD:
498      case IDEAL_CMD:
499      case MODUL_CMD:
500        {
501          matrix mm = (matrix)(v->Data());
502          rc += mm->rows() * mm->cols();
503        }
504        break;
505      case LIST_CMD:
506        rc+=((lists)v->Data())->nr+1;
507        break;
508      default:
509        rc++;
510    }
511    v = v->next;
512  }
513  return rc;
514}
515
516int iiIsPrime0(unsigned p)  /* brute force !!!! */
517{
518  unsigned i,j=0 /*only to avoid compiler warnings*/;
519#ifdef HAVE_FACTORY
520  if (p<=32749) // max. small prime in factory
521  {
522    int a=0;
523    int e=cf_getNumSmallPrimes()-1;
524    i=e/2;
525    do
526    {
527      j=cf_getSmallPrime(i);
528      if (p==j) return p;
529      if (p<j) e=i-1;
530      else     a=i+1;
531      i=a+(e-a)/2;
532    } while ( a<= e);
533    if (p>j) return j;
534    else     return cf_getSmallPrime(i-1);
535  }
536#endif
537#ifdef HAVE_FACTORY
538  unsigned end_i=cf_getNumSmallPrimes()-1;
539#else
540  unsigned end_i=p/2;
541#endif
542  unsigned end_p=(unsigned)sqrt((double)p);
543restart:
544  for (i=0; i<end_i; i++)
545  {
546#ifdef HAVE_FACTORY
547    j=cf_getSmallPrime(i);
548#else
549    if (i==0) j=2;
550    else j=2*i-1;
551#endif
552    if ((p%j) == 0)
553    {
554    #ifdef HAVE_FACTORY
555      if (p<=32751) return iiIsPrime0(p-2);
556    #endif
557      p-=2;
558      goto restart;
559    }
560    if (j > end_p) return p;
561  }
562#ifdef HAVE_FACTORY
563  if (i>=end_i)
564  {
565    while(j<=end_p)
566    {
567      j+=2;
568      if ((p%j) == 0)
569      {
570        if (p<=32751) return iiIsPrime0(p-2);
571        p-=2;
572        goto restart;
573      }
574    }
575  }
576#endif
577  return p;
578}
579int IsPrime(int p)  /* brute force !!!! */
580{
581  int i,j;
582  if      (p == 0)    return 0;
583  else if (p == 1)    return 1/*1*/;
584  else if ((p == 2)||(p==3))    return p;
585  else if (p < 0)     return 2; //(iiIsPrime0((unsigned)(-p)));
586  else if ((p & 1)==0) return iiIsPrime0((unsigned)(p-1));
587  return iiIsPrime0((unsigned)(p));
588}
589
590BOOLEAN iiWRITE(leftv res,leftv v)
591{
592  sleftv vf;
593  if (iiConvert(v->Typ(),LINK_CMD,iiTestConvert(v->Typ(),LINK_CMD),v,&vf))
594  {
595    WerrorS("link expected");
596    return TRUE;
597  }
598  si_link l=(si_link)vf.Data();
599  if (vf.next == NULL)
600  {
601    WerrorS("write: need at least two arguments");
602    return TRUE;
603  }
604
605  BOOLEAN b=slWrite(l,vf.next); /* iiConvert preserves next */
606  if (b)
607  {
608    const char *s;
609    if ((l!=NULL)&&(l->name!=NULL)) s=l->name;
610    else                            s=sNoName;
611    Werror("cannot write to %s",s);
612  }
613  vf.CleanUp();
614  return b;
615}
616
617leftv iiMap(map theMap, const char * what)
618{
619  idhdl w,r;
620  leftv v;
621  int i;
622  nMapFunc nMap;
623
624  r=IDROOT->get(theMap->preimage,myynest);
625  if ((currPack!=basePack)
626  &&((r==NULL) || ((r->typ != RING_CMD) && (r->typ != QRING_CMD))))
627    r=basePack->idroot->get(theMap->preimage,myynest);
628  if ((r==NULL) && (currRingHdl!=NULL)
629  && (strcmp(theMap->preimage,IDID(currRingHdl))==0))
630  {
631    r=currRingHdl;
632  }
633  if ((r!=NULL) && ((r->typ == RING_CMD) || (r->typ== QRING_CMD)))
634  {
635    //if ((nMap=nSetMap(rInternalChar(IDRING(r)),
636    //             IDRING(r)->parameter,
637    //             rPar(IDRING(r)),
638    //             IDRING(r)->minpoly)))
639    if ((nMap=nSetMap(IDRING(r)))==NULL)
640    {
641      if (rEqual(IDRING(r),currRing))
642      {
643        nMap=nCopy;
644      }
645      else
646      {
647        Werror("can not map from ground field of %s to current ground field",
648          theMap->preimage);
649        return NULL;
650      }
651    }
652    if (IDELEMS(theMap)<IDRING(r)->N)
653    {
654      theMap->m=(polyset)omReallocSize((ADDRESS)theMap->m,
655                                 IDELEMS(theMap)*sizeof(poly),
656                                 (IDRING(r)->N)*sizeof(poly));
657      for(i=IDELEMS(theMap);i<IDRING(r)->N;i++)
658        theMap->m[i]=NULL;
659      IDELEMS(theMap)=IDRING(r)->N;
660    }
661    if (what==NULL)
662    {
663      WerrorS("argument of a map must have a name");
664    }
665    else if ((w=IDRING(r)->idroot->get(what,myynest))!=NULL)
666    {
667      char *save_r=NULL;
668      v=(leftv)omAlloc0Bin(sleftv_bin);
669      sleftv tmpW;
670      memset(&tmpW,0,sizeof(sleftv));
671      tmpW.rtyp=IDTYP(w);
672      if (tmpW.rtyp==MAP_CMD)
673      {
674        tmpW.rtyp=IDEAL_CMD;
675        save_r=IDMAP(w)->preimage;
676        IDMAP(w)->preimage=0;
677      }
678      tmpW.data=IDDATA(w);
679      #if 0
680      if (((tmpW.rtyp==IDEAL_CMD)||(tmpW.rtyp==MODUL_CMD)) && idIs0(IDIDEAL(w)))
681      {
682        v->rtyp=tmpW.rtyp;
683        v->data=idInit(IDELEMS(IDIDEAL(w)),IDIDEAL(w)->rank);
684      }
685      else
686      #endif
687      {
688        #ifdef FAST_MAP
689        if ((tmpW.rtyp==IDEAL_CMD) && (nMap==nCopy)
690        #ifdef HAVE_PLURAL
691        && (!rIsPluralRing(currRing))
692        #endif
693        )
694        {
695          v->rtyp=IDEAL_CMD;
696          v->data=fast_map(IDIDEAL(w), IDRING(r), (ideal)theMap, currRing);
697        }
698        else
699        #endif
700        if (maApplyFetch(MAP_CMD,theMap,v,&tmpW,IDRING(r),NULL,NULL,0,nMap))
701        {
702          Werror("cannot map %s(%d)",Tok2Cmdname(w->typ),w->typ);
703          omFreeBin((ADDRESS)v, sleftv_bin);
704          if (save_r!=NULL) IDMAP(w)->preimage=save_r;
705          return NULL;
706        }
707      }
708      if (save_r!=NULL)
709      {
710        IDMAP(w)->preimage=save_r;
711        IDMAP((idhdl)v)->preimage=omStrDup(save_r);
712        v->rtyp=MAP_CMD;
713      }
714      return v;
715    }
716    else
717    {
718      Werror("%s undefined in %s",what,theMap->preimage);
719    }
720  }
721  else
722  {
723    Werror("cannot find preimage %s",theMap->preimage);
724  }
725  return NULL;
726}
727
728#ifdef OLD_RES
729void  iiMakeResolv(resolvente r, int length, int rlen, char * name, int typ0,
730                   intvec ** weights)
731{
732  lists L=liMakeResolv(r,length,rlen,typ0,weights);
733  int i=0;
734  idhdl h;
735  char * s=(char *)omAlloc(strlen(name)+5);
736
737  while (i<=L->nr)
738  {
739    sprintf(s,"%s(%d)",name,i+1);
740    if (i==0)
741      h=enterid(s,myynest,typ0,&(currRing->idroot), FALSE);
742    else
743      h=enterid(s,myynest,MODUL_CMD,&(currRing->idroot), FALSE);
744    if (h!=NULL)
745    {
746      h->data.uideal=(ideal)L->m[i].data;
747      h->attribute=L->m[i].attribute;
748      if (BVERBOSE(V_DEF_RES))
749        Print("//defining: %s as %d-th syzygy module\n",s,i+1);
750    }
751    else
752    {
753      idDelete((ideal *)&(L->m[i].data));
754      Warn("cannot define %s",s);
755    }
756    //L->m[i].data=NULL;
757    //L->m[i].rtyp=0;
758    //L->m[i].attribute=NULL;
759    i++;
760  }
761  omFreeSize((ADDRESS)L->m,(L->nr+1)*sizeof(sleftv));
762  omFreeBin((ADDRESS)L, slists_bin);
763  omFreeSize((ADDRESS)s,strlen(name)+5);
764}
765#endif
766
767//resolvente iiFindRes(char * name, int * len, int *typ0)
768//{
769//  char *s=(char *)omAlloc(strlen(name)+5);
770//  int i=-1;
771//  resolvente r;
772//  idhdl h;
773//
774//  do
775//  {
776//    i++;
777//    sprintf(s,"%s(%d)",name,i+1);
778//    h=currRing->idroot->get(s,myynest);
779//  } while (h!=NULL);
780//  *len=i-1;
781//  if (*len<=0)
782//  {
783//    Werror("no objects %s(1),.. found",name);
784//    omFreeSize((ADDRESS)s,strlen(name)+5);
785//    return NULL;
786//  }
787//  r=(ideal *)omAlloc(/*(len+1)*/ i*sizeof(ideal));
788//  memset(r,0,(*len)*sizeof(ideal));
789//  i=-1;
790//  *typ0=MODUL_CMD;
791//  while (i<(*len))
792//  {
793//    i++;
794//    sprintf(s,"%s(%d)",name,i+1);
795//    h=currRing->idroot->get(s,myynest);
796//    if (h->typ != MODUL_CMD)
797//    {
798//      if ((i!=0) || (h->typ!=IDEAL_CMD))
799//      {
800//        Werror("%s is not of type module",s);
801//        omFreeSize((ADDRESS)r,(*len)*sizeof(ideal));
802//        omFreeSize((ADDRESS)s,strlen(name)+5);
803//        return NULL;
804//      }
805//      *typ0=IDEAL_CMD;
806//    }
807//    if ((i>0) && (idIs0(r[i-1])))
808//    {
809//      *len=i-1;
810//      break;
811//    }
812//    r[i]=IDIDEAL(h);
813//  }
814//  omFreeSize((ADDRESS)s,strlen(name)+5);
815//  return r;
816//}
817
818static resolvente iiCopyRes(resolvente r, int l)
819{
820  int i;
821  resolvente res=(ideal *)omAlloc0((l+1)*sizeof(ideal));
822
823  for (i=0; i<l; i++)
824    res[i]=idCopy(r[i]);
825  return res;
826}
827
828BOOLEAN jjMINRES(leftv res, leftv v)
829{
830  int len=0;
831  int typ0;
832  lists L=(lists)v->Data();
833  intvec *weights=(intvec*)atGet(v,"isHomog",INTVEC_CMD);
834  int add_row_shift = 0;
835  if (weights==NULL)
836    weights=(intvec*)atGet(&(L->m[0]),"isHomog",INTVEC_CMD);
837  if (weights!=NULL)  add_row_shift=weights->min_in();
838  resolvente rr=liFindRes(L,&len,&typ0);
839  if (rr==NULL) return TRUE;
840  resolvente r=iiCopyRes(rr,len);
841
842  syMinimizeResolvente(r,len,0);
843  omFreeSize((ADDRESS)rr,len*sizeof(ideal));
844  len++;
845  res->data=(char *)liMakeResolv(r,len,-1,typ0,NULL,add_row_shift);
846  return FALSE;
847}
848
849BOOLEAN jjBETTI(leftv res, leftv u)
850{
851  sleftv tmp;
852  memset(&tmp,0,sizeof(tmp));
853  tmp.rtyp=INT_CMD;
854  tmp.data=(void *)1;
855  if ((u->Typ()==IDEAL_CMD)
856  || (u->Typ()==MODUL_CMD))
857    return jjBETTI2_ID(res,u,&tmp);
858  else
859    return jjBETTI2(res,u,&tmp);
860}
861
862BOOLEAN jjBETTI2_ID(leftv res, leftv u, leftv v)
863{
864  lists l=(lists) omAllocBin(slists_bin);
865  l->Init(1);
866  l->m[0].rtyp=u->Typ();
867  l->m[0].data=u->Data();
868  l->m[0].attribute=u->attribute;
869  sleftv tmp2;
870  memset(&tmp2,0,sizeof(tmp2));
871  tmp2.rtyp=LIST_CMD;
872  tmp2.data=(void *)l;
873  BOOLEAN r=jjBETTI2(res,&tmp2,v);
874  l->m[0].data=NULL;
875  l->m[0].attribute=NULL;
876  l->m[0].rtyp=DEF_CMD;
877  l->Clean();
878  return r;
879}
880
881BOOLEAN jjBETTI2(leftv res, leftv u, leftv v)
882{
883  resolvente r;
884  int len;
885  int reg,typ0;
886  lists l=(lists)u->Data();
887
888  intvec *weights=NULL;
889  int add_row_shift=0;
890  intvec *ww=(intvec *)atGet(&(l->m[0]),"isHomog",INTVEC_CMD);
891  if (ww!=NULL)
892  {
893     weights=ivCopy(ww);
894     add_row_shift = ww->min_in();
895     (*weights) -= add_row_shift;
896  }
897  //Print("attr:%x\n",weights);
898
899  r=liFindRes(l,&len,&typ0);
900  if (r==NULL) return TRUE;
901  res->data=(char *)syBetti(r,len,&reg,weights,(int)(long)v->Data());
902  omFreeSize((ADDRESS)r,(len)*sizeof(ideal));
903  atSet(res,omStrDup("rowShift"),(void*)add_row_shift,INT_CMD);
904  if (weights!=NULL) delete weights;
905  return FALSE;
906}
907
908int iiRegularity(lists L)
909{
910  int len,reg,typ0;
911
912  resolvente r=liFindRes(L,&len,&typ0);
913
914  if (r==NULL)
915    return -2;
916  intvec *weights=NULL;
917  int add_row_shift=0;
918  intvec *ww=(intvec *)atGet(&(L->m[0]),"isHomog",INTVEC_CMD);
919  if (ww!=NULL)
920  {
921     weights=ivCopy(ww);
922     add_row_shift = ww->min_in();
923     (*weights) -= add_row_shift;
924  }
925  //Print("attr:%x\n",weights);
926
927  intvec *dummy=syBetti(r,len,&reg,weights);
928  if (weights!=NULL) delete weights;
929  delete dummy;
930  omFreeSize((ADDRESS)r,len*sizeof(ideal));
931  return reg+1+add_row_shift;
932}
933
934BOOLEAN iiDebugMarker=TRUE;
935#define BREAK_LINE_LENGTH 80
936void iiDebug()
937{
938  Print("\n-- break point in %s --\n",VoiceName());
939  if (iiDebugMarker) VoiceBackTrack();
940  char * s;
941  iiDebugMarker=FALSE;
942  s = (char *)omAlloc(BREAK_LINE_LENGTH+4);
943  loop
944  {
945    memset(s,0,80);
946    fe_fgets_stdin("",s,BREAK_LINE_LENGTH);
947    if (s[BREAK_LINE_LENGTH-1]!='\0')
948    {
949      Print("line too long, max is %d chars\n",BREAK_LINE_LENGTH);
950    }
951    else
952      break;
953  }
954  if (*s=='\n')
955  {
956    iiDebugMarker=TRUE;
957  }
958#if MDEBUG
959  else if(strncmp(s,"cont;",5)==0)
960  {
961    iiDebugMarker=TRUE;
962  }
963#endif /* MDEBUG */
964  else
965  {
966    strcat( s, "\n;~\n");
967    newBuffer(s,BT_execute);
968  }
969}
970
971lists scIndIndset(ideal S, BOOLEAN all, ideal Q)
972{
973  int i;
974  indset save;
975  lists res=(lists)omAlloc0Bin(slists_bin);
976
977  hexist = hInit(S, Q, &hNexist);
978  if (hNexist == 0)
979  {
980    intvec *iv=new intvec(pVariables);
981    for(i=0; i<pVariables; i++) (*iv)[i]=1;
982    res->Init(1);
983    res->m[0].rtyp=INTVEC_CMD;
984    res->m[0].data=(intvec*)iv;
985    return res;
986  }
987  else if (hisModule!=0)
988  {
989    res->Init(0);
990    return res;
991  }
992  save = ISet = (indset)omAlloc0Bin(indlist_bin);
993  hMu = 0;
994  hwork = (scfmon)omAlloc(hNexist * sizeof(scmon));
995  hvar = (varset)omAlloc((pVariables + 1) * sizeof(int));
996  hpure = (scmon)omAlloc((1 + (pVariables * pVariables)) * sizeof(long));
997  hrad = hexist;
998  hNrad = hNexist;
999  radmem = hCreate(pVariables - 1);
1000  hCo = pVariables + 1;
1001  hNvar = pVariables;
1002  hRadical(hrad, &hNrad, hNvar);
1003  hSupp(hrad, hNrad, hvar, &hNvar);
1004  if (hNvar)
1005  {
1006    hCo = hNvar;
1007    memset(hpure, 0, (pVariables + 1) * sizeof(long));
1008    hPure(hrad, 0, &hNrad, hvar, hNvar, hpure, &hNpure);
1009    hLexR(hrad, hNrad, hvar, hNvar);
1010    hDimSolve(hpure, hNpure, hrad, hNrad, hvar, hNvar);
1011  }
1012  if (hCo && (hCo < pVariables))
1013  {
1014    hIndMult(hpure, hNpure, hrad, hNrad, hvar, hNvar);
1015  }
1016  if (hMu!=0)
1017  {
1018    ISet = save;
1019    hMu2 = 0;
1020    if (all && (hCo+1 < pVariables))
1021    {
1022      JSet = (indset)omAlloc0Bin(indlist_bin);
1023      hIndAllMult(hpure, hNpure, hrad, hNrad, hvar, hNvar);
1024      i=hMu+hMu2;
1025      res->Init(i);
1026      if (hMu2 == 0)
1027      {
1028        omFreeBin((ADDRESS)JSet, indlist_bin);
1029      }
1030    }
1031    else
1032    {
1033      res->Init(hMu);
1034    }
1035    for (i=0;i<hMu;i++)
1036    {
1037      res->m[i].data = (void *)save->set;
1038      res->m[i].rtyp = INTVEC_CMD;
1039      ISet = save;
1040      save = save->nx;
1041      omFreeBin((ADDRESS)ISet, indlist_bin);
1042    }
1043    omFreeBin((ADDRESS)save, indlist_bin);
1044    if (hMu2 != 0)
1045    {
1046      save = JSet;
1047      for (i=hMu;i<hMu+hMu2;i++)
1048      {
1049        res->m[i].data = (void *)save->set;
1050        res->m[i].rtyp = INTVEC_CMD;
1051        JSet = save;
1052        save = save->nx;
1053        omFreeBin((ADDRESS)JSet, indlist_bin);
1054      }
1055      omFreeBin((ADDRESS)save, indlist_bin);
1056    }
1057  }
1058  else
1059  {
1060    res->Init(0);
1061    omFreeBin((ADDRESS)ISet,  indlist_bin);
1062  }
1063  hKill(radmem, pVariables - 1);
1064  omFreeSize((ADDRESS)hpure, (1 + (pVariables * pVariables)) * sizeof(long));
1065  omFreeSize((ADDRESS)hvar, (pVariables + 1) * sizeof(int));
1066  omFreeSize((ADDRESS)hwork, hNexist * sizeof(scmon));
1067  hDelete(hexist, hNexist);
1068  return res;
1069}
1070
1071int iiDeclCommand(leftv sy, leftv name, int lev,int t, idhdl* root,BOOLEAN isring, BOOLEAN init_b)
1072{
1073  BOOLEAN res=FALSE;
1074  const char *id = name->name;
1075
1076  memset(sy,0,sizeof(sleftv));
1077  if ((name->name==NULL)||(isdigit(name->name[0])))
1078  {
1079    WerrorS("object to declare is not a name");
1080    res=TRUE;
1081  }
1082  else
1083  {
1084    //if (name->rtyp!=0)
1085    //{
1086    //  Warn("`%s` is already in use",name->name);
1087    //}
1088    {
1089      sy->data = (char *)enterid(id,lev,t,root,init_b);
1090    }
1091    if (sy->data!=NULL)
1092    {
1093      sy->rtyp=IDHDL;
1094      currid=sy->name=IDID((idhdl)sy->data);
1095      // name->name=NULL; /* used in enterid */
1096      //sy->e = NULL;
1097      if (name->next!=NULL)
1098      {
1099        sy->next=(leftv)omAllocBin(sleftv_bin);
1100        res=iiDeclCommand(sy->next,name->next,lev,t,root, isring);
1101      }
1102    }
1103    else res=TRUE;
1104  }
1105  name->CleanUp();
1106  return res;
1107}
1108
1109BOOLEAN iiDefaultParameter(leftv p)
1110{
1111  attr at=NULL;
1112  if (iiCurrProc!=NULL)
1113     at=iiCurrProc->attribute->get("default_arg");
1114  if (at==NULL)
1115    return FALSE;
1116  sleftv tmp;
1117  memset(&tmp,0,sizeof(sleftv));
1118  tmp.rtyp=at->atyp;
1119  tmp.data=at->CopyA();
1120  return iiAssign(p,&tmp);
1121}
1122BOOLEAN iiParameter(leftv p)
1123{
1124  if (iiCurrArgs==NULL)
1125  {
1126    if (strcmp(p->name,"#")==0)
1127      return iiDefaultParameter(p);
1128    Werror("not enough arguments for proc %s",VoiceName());
1129    p->CleanUp();
1130    return TRUE;
1131  }
1132  leftv h=iiCurrArgs;
1133  if (strcmp(p->name,"#")==0)
1134  {
1135    iiCurrArgs=NULL;
1136  }
1137  else
1138  {
1139    iiCurrArgs=h->next;
1140    h->next=NULL;
1141  }
1142  BOOLEAN res=iiAssign(p,h);
1143  h->CleanUp();
1144  omFreeBin((ADDRESS)h, sleftv_bin);
1145  return res;
1146}
1147BOOLEAN iiAlias(leftv p)
1148{
1149  if (iiCurrArgs==NULL)
1150  {
1151    Werror("not enough arguments for proc %s",VoiceName());
1152    p->CleanUp();
1153    return TRUE;
1154  }
1155  leftv h=iiCurrArgs;
1156  iiCurrArgs=h->next;
1157  h->next=NULL;
1158  if (h->rtyp!=IDHDL)
1159  {
1160    WerrorS("identifier required");
1161    return TRUE;
1162  }
1163  if (h->Typ()!=p->Typ())
1164  {
1165    WerrorS("type mismatch");
1166    return TRUE;
1167  }
1168  idhdl pp=(idhdl)p->data;
1169  switch(pp->typ)
1170  {
1171      case INT_CMD:
1172        break;
1173      case INTVEC_CMD:
1174      case INTMAT_CMD:
1175         delete IDINTVEC(pp);
1176         break;
1177      case NUMBER_CMD:
1178         nDelete(&IDNUMBER(pp));
1179         break;
1180      case BIGINT_CMD:
1181         nlDelete(&IDNUMBER(pp),currRing);
1182         break;
1183      case MAP_CMD:
1184         {
1185           map im = IDMAP(pp);
1186           omFree((ADDRESS)im->preimage);
1187         }
1188         // continue as ideal:
1189      case IDEAL_CMD:
1190      case MODUL_CMD:
1191      case MATRIX_CMD:
1192          idDelete(&IDIDEAL(pp));
1193         break;
1194      case PROC_CMD:
1195      case RESOLUTION_CMD:
1196      case STRING_CMD:
1197         omFree((ADDRESS)IDSTRING(pp));
1198         break;
1199      case LIST_CMD:
1200         IDLIST(pp)->Clean();
1201         break;
1202      case LINK_CMD:
1203         omFreeBin(IDLINK(pp),sip_link_bin);
1204         break;
1205       // case ring: cannot happen
1206       default:
1207         Werror("unknown type %d",p->Typ());
1208         return TRUE;
1209  }
1210  pp->typ=ALIAS_CMD;
1211  IDDATA(pp)=(char*)h->data;
1212  h->CleanUp();
1213  omFreeBin((ADDRESS)h, sleftv_bin);
1214  return FALSE;
1215}
1216
1217static BOOLEAN iiInternalExport (leftv v, int toLev)
1218{
1219  idhdl h=(idhdl)v->data;
1220  //Print("iiInternalExport('%s',%d)%s\n", v->name, toLev,"");
1221  if (IDLEV(h)==0) Warn("`%s` is already global",IDID(h));
1222  else
1223  {
1224    h=IDROOT->get(v->name,toLev);
1225    idhdl *root=&IDROOT;
1226    if ((h==NULL)&&(currRing!=NULL))
1227    {
1228      h=currRing->idroot->get(v->name,toLev);
1229      root=&currRing->idroot;
1230    }
1231    BOOLEAN keepring=FALSE;
1232    if ((h!=NULL)&&(IDLEV(h)==toLev))
1233    {
1234      if (IDTYP(h)==v->Typ())
1235      {
1236        if (((IDTYP(h)==RING_CMD)||(IDTYP(h)==QRING_CMD))
1237        && (v->Data()==IDDATA(h)))
1238        {
1239          IDRING(h)->ref++;
1240          keepring=TRUE;
1241          IDLEV(h)=toLev;
1242          //WarnS("keepring");
1243          return FALSE;
1244        }
1245        if (BVERBOSE(V_REDEFINE))
1246        {
1247          Warn("redefining %s",IDID(h));
1248        }
1249#ifdef USE_IILOCALRING
1250        if (iiLocalRing[0]==IDRING(h) && (!keepring)) iiLocalRing[0]=NULL;
1251#else
1252        proclevel *p=procstack;
1253        while (p->next!=NULL) p=p->next;
1254        if ((p->cRing==IDRING(h)) && (!keepring))
1255        {
1256          p->cRing=NULL;
1257          p->cRingHdl=NULL;
1258        }
1259#endif
1260        killhdl2(h,root,currRing);
1261      }
1262      else
1263      {
1264        return TRUE;
1265      }
1266    }
1267    h=(idhdl)v->data;
1268    IDLEV(h)=toLev;
1269    if (keepring) IDRING(h)->ref--;
1270    iiNoKeepRing=FALSE;
1271    //Print("export %s\n",IDID(h));
1272  }
1273  return FALSE;
1274}
1275
1276BOOLEAN iiInternalExport (leftv v, int toLev, idhdl roothdl)
1277{
1278  idhdl h=(idhdl)v->data;
1279  if(h==NULL)
1280  {
1281    Warn("'%s': no such identifier\n", v->name);
1282    return FALSE;
1283  }
1284  package frompack=v->req_packhdl;
1285  if (frompack==NULL) frompack=currPack;
1286  package rootpack = IDPACKAGE(roothdl);
1287//  Print("iiInternalExport('%s',%d,%s->%s) typ:%d\n", v->name, toLev, IDID(currPackHdl),IDID(roothdl),v->Typ());
1288  if ((RingDependend(IDTYP(h)))
1289  || ((IDTYP(h)==LIST_CMD)
1290     && (lRingDependend(IDLIST(h)))
1291     )
1292  )
1293  {
1294    //Print("// ==> Ringdependent set nesting to 0\n");
1295    return (iiInternalExport(v, toLev));
1296  }
1297  else
1298  {
1299    IDLEV(h)=toLev;
1300    v->req_packhdl=rootpack;
1301    if (h==frompack->idroot)
1302    {
1303      frompack->idroot=h->next;
1304    }
1305    else
1306    {
1307      idhdl hh=frompack->idroot;
1308      while ((hh!=NULL) && (hh->next!=h))
1309        hh=hh->next;
1310      if ((hh!=NULL) && (hh->next==h))
1311        hh->next=h->next;
1312      else
1313      {
1314        Werror("`%s` not found",v->Name());
1315        return TRUE;
1316      }
1317    }
1318    h->next=rootpack->idroot;
1319    rootpack->idroot=h;
1320  }
1321  return FALSE;
1322}
1323
1324BOOLEAN iiExport (leftv v, int toLev)
1325{
1326#ifndef NDEBUG
1327  checkall();
1328#endif
1329  BOOLEAN nok=FALSE;
1330  leftv r=v;
1331  while (v!=NULL)
1332  {
1333    if ((v->name==NULL)||(v->rtyp==0)||(v->e!=NULL))
1334    {
1335      WerrorS("cannot export");
1336      nok=TRUE;
1337    }
1338    else
1339    {
1340      if(iiInternalExport(v, toLev))
1341      {
1342        r->CleanUp();
1343        return TRUE;
1344      }
1345    }
1346    v=v->next;
1347  }
1348  r->CleanUp();
1349#ifndef NDEBUG
1350  checkall();
1351#endif
1352  return nok;
1353}
1354
1355/*assume root!=idroot*/
1356BOOLEAN iiExport (leftv v, int toLev, idhdl root)
1357{
1358#ifndef NDEBUG
1359  checkall();
1360#endif
1361  //  Print("iiExport1: pack=%s\n",IDID(root));
1362  package pack=IDPACKAGE(root);
1363  BOOLEAN nok=FALSE;
1364  leftv rv=v;
1365  while (v!=NULL)
1366  {
1367    if ((v->name==NULL)||(v->rtyp==0)||(v->e!=NULL)
1368    )
1369    {
1370      WerrorS("cannot export");
1371      nok=TRUE;
1372    }
1373    else
1374    {
1375      idhdl old=pack->idroot->get( v->name,toLev);
1376      if (old!=NULL)
1377      {
1378        if ((pack==currPack) && (old==(idhdl)v->data))
1379        {
1380          Warn("`%s` is already global",IDID(old));
1381          break;
1382        }
1383        else if (IDTYP(old)==v->Typ())
1384        {
1385          if (BVERBOSE(V_REDEFINE))
1386          {
1387            Warn("redefining %s",IDID(old));
1388          }
1389          v->name=omStrDup(v->name);
1390          killhdl2(old,&(pack->idroot),currRing);
1391        }
1392        else
1393        {
1394          rv->CleanUp();
1395          return TRUE;
1396        }
1397      }
1398      //Print("iiExport: pack=%s\n",IDID(root));
1399      if(iiInternalExport(v, toLev, root))
1400      {
1401        rv->CleanUp();
1402        return TRUE;
1403      }
1404    }
1405    v=v->next;
1406  }
1407  rv->CleanUp();
1408#ifndef NDEBUG
1409  checkall();
1410#endif
1411  return nok;
1412}
1413
1414BOOLEAN iiCheckRing(int i)
1415{
1416  if (currRingHdl==NULL)
1417  {
1418    #ifdef SIQ
1419    if (siq<=0)
1420    {
1421    #endif
1422      if (RingDependend(i))
1423      {
1424        WerrorS("no ring active");
1425        return TRUE;
1426      }
1427    #ifdef SIQ
1428    }
1429    #endif
1430  }
1431  return FALSE;
1432}
1433
1434poly    iiHighCorner(ideal I, int ak)
1435{
1436  int i;
1437  if(!idIsZeroDim(I)) return NULL; // not zero-dim.
1438  poly po=NULL;
1439  if (rHasLocalOrMixedOrdering_currRing())
1440  {
1441    scComputeHC(I,currQuotient,ak,po);
1442    if (po!=NULL)
1443    {
1444      pGetCoeff(po)=nInit(1);
1445      for (i=pVariables; i>0; i--)
1446      {
1447        if (pGetExp(po, i) > 0) pDecrExp(po,i);
1448      }
1449      pSetComp(po,ak);
1450      pSetm(po);
1451    }
1452  }
1453  else
1454    po=pOne();
1455  return po;
1456}
1457
1458void iiCheckPack(package &p)
1459{
1460  if (p==basePack) return;
1461
1462  idhdl t=basePack->idroot;
1463
1464  while ((t!=NULL) && (IDTYP(t)!=PACKAGE_CMD) && (IDPACKAGE(t)!=p)) t=t->next;
1465
1466  if (t==NULL)
1467  {
1468    WarnS("package not found\n");
1469    p=basePack;
1470  }
1471  return;
1472}
1473
1474idhdl rDefault(const char *s)
1475{
1476  idhdl tmp=NULL;
1477
1478  if (s!=NULL) tmp = enterid(s, myynest, RING_CMD, &IDROOT);
1479  if (tmp==NULL) return NULL;
1480
1481  if (ppNoether!=NULL) pDelete(&ppNoether);
1482  if (sLastPrinted.RingDependend())
1483  {
1484    sLastPrinted.CleanUp();
1485    memset(&sLastPrinted,0,sizeof(sleftv));
1486  }
1487
1488  ring r = IDRING(tmp);
1489
1490  r->ch    = 32003;
1491  r->N     = 3;
1492  /*r->P     = 0; Alloc0 in idhdl::set, ipid.cc*/
1493  /*names*/
1494  r->names = (char **) omAlloc0(3 * sizeof(char_ptr));
1495  r->names[0]  = omStrDup("x");
1496  r->names[1]  = omStrDup("y");
1497  r->names[2]  = omStrDup("z");
1498  /*weights: entries for 3 blocks: NULL*/
1499  r->wvhdl = (int **)omAlloc0(3 * sizeof(int_ptr));
1500  /*order: dp,C,0*/
1501  r->order = (int *) omAlloc(3 * sizeof(int *));
1502  r->block0 = (int *)omAlloc0(3 * sizeof(int *));
1503  r->block1 = (int *)omAlloc0(3 * sizeof(int *));
1504  /* ringorder dp for the first block: var 1..3 */
1505  r->order[0]  = ringorder_dp;
1506  r->block0[0] = 1;
1507  r->block1[0] = 3;
1508  /* ringorder C for the second block: no vars */
1509  r->order[1]  = ringorder_C;
1510  /* the last block: everything is 0 */
1511  r->order[2]  = 0;
1512  /*polynomial ring*/
1513  r->OrdSgn    = 1;
1514
1515  /* complete ring intializations */
1516  rComplete(r);
1517  rSetHdl(tmp);
1518  return currRingHdl;
1519}
1520
1521idhdl rFindHdl(ring r, idhdl n, idhdl w)
1522{
1523  idhdl h=rSimpleFindHdl(r,IDROOT,n);
1524  if (h!=NULL)  return h;
1525  if (IDROOT!=basePack->idroot) h=rSimpleFindHdl(r,basePack->idroot,n);
1526  if (h!=NULL)  return h;
1527  proclevel *p=procstack;
1528  while(p!=NULL)
1529  {
1530    if ((p->cPack!=basePack)
1531    && (p->cPack!=currPack))
1532      h=rSimpleFindHdl(r,p->cPack->idroot,n);
1533    if (h!=NULL)  return h;
1534    p=p->next;
1535  }
1536  idhdl tmp=basePack->idroot;
1537  while (tmp!=NULL)
1538  {
1539    if (IDTYP(tmp)==PACKAGE_CMD)
1540      h=rSimpleFindHdl(r,IDPACKAGE(tmp)->idroot,n);
1541    if (h!=NULL)  return h;
1542    tmp=IDNEXT(tmp);
1543  }
1544  return NULL;
1545}
1546
1547void rDecomposeCF(leftv h,const ring r,const ring R)
1548{
1549  lists L=(lists)omAlloc0Bin(slists_bin);
1550  L->Init(4);
1551  h->rtyp=LIST_CMD;
1552  h->data=(void *)L;
1553  // 0: char/ cf - ring
1554  // 1: list (var)
1555  // 2: list (ord)
1556  // 3: qideal
1557  // ----------------------------------------
1558  // 0: char/ cf - ring
1559  L->m[0].rtyp=INT_CMD;
1560  L->m[0].data=(void *)r->ch;
1561  // ----------------------------------------
1562  // 1: list (var)
1563  lists LL=(lists)omAlloc0Bin(slists_bin);
1564  LL->Init(r->N);
1565  int i;
1566  for(i=0; i<r->N; i++)
1567  {
1568    LL->m[i].rtyp=STRING_CMD;
1569    LL->m[i].data=(void *)omStrDup(r->names[i]);
1570  }
1571  L->m[1].rtyp=LIST_CMD;
1572  L->m[1].data=(void *)LL;
1573  // ----------------------------------------
1574  // 2: list (ord)
1575  LL=(lists)omAlloc0Bin(slists_bin);
1576  i=rBlocks(r)-1;
1577  LL->Init(i);
1578  i--;
1579  lists LLL;
1580  for(; i>=0; i--)
1581  {
1582    intvec *iv;
1583    int j;
1584    LL->m[i].rtyp=LIST_CMD;
1585    LLL=(lists)omAlloc0Bin(slists_bin);
1586    LLL->Init(2);
1587    LLL->m[0].rtyp=STRING_CMD;
1588    LLL->m[0].data=(void *)omStrDup(rSimpleOrdStr(r->order[i]));
1589    if (r->block1[i]-r->block0[i] >=0 )
1590    {
1591      j=r->block1[i]-r->block0[i];
1592      if(r->order[i]==ringorder_M) j=(j+1)*(j+1)-1;
1593      iv=new intvec(j+1);
1594      if ((r->wvhdl!=NULL) && (r->wvhdl[i]!=NULL))
1595      {
1596        for(;j>=0; j--) (*iv)[j]=r->wvhdl[i][j];
1597      }
1598      else switch (r->order[i])
1599      {
1600        case ringorder_dp:
1601        case ringorder_Dp:
1602        case ringorder_ds:
1603        case ringorder_Ds:
1604        case ringorder_lp:
1605          for(;j>=0; j--) (*iv)[j]=1;
1606          break;
1607        default: /* do nothing */;
1608      }
1609    }
1610    else
1611    {
1612      iv=new intvec(1);
1613    }
1614    LLL->m[1].rtyp=INTVEC_CMD;
1615    LLL->m[1].data=(void *)iv;
1616    LL->m[i].data=(void *)LLL;
1617  }
1618  L->m[2].rtyp=LIST_CMD;
1619  L->m[2].data=(void *)LL;
1620  // ----------------------------------------
1621  // 3: qideal
1622  L->m[3].rtyp=IDEAL_CMD;
1623  if (R->minpoly==NULL)
1624    L->m[3].data=(void *)idInit(1,1);
1625  else
1626  {
1627    ideal I=idInit(1,1);
1628    L->m[3].data=(void *)I;
1629    I->m[0]=pNSet(R->minpoly);
1630  }
1631  // ----------------------------------------
1632}
1633void rDecomposeC(leftv h,const ring R)
1634/* field is R or C */
1635{
1636  lists L=(lists)omAlloc0Bin(slists_bin);
1637  if (rField_is_long_C(R)) L->Init(3);
1638  else                     L->Init(2);
1639  h->rtyp=LIST_CMD;
1640  h->data=(void *)L;
1641  // 0: char/ cf - ring
1642  // 1: list (var)
1643  // 2: list (ord)
1644  // ----------------------------------------
1645  // 0: char/ cf - ring
1646  L->m[0].rtyp=INT_CMD;
1647  L->m[0].data=(void *)0;
1648  // ----------------------------------------
1649  // 1:
1650  lists LL=(lists)omAlloc0Bin(slists_bin);
1651  LL->Init(2);
1652    LL->m[0].rtyp=INT_CMD;
1653    LL->m[0].data=(void *)si_max(R->float_len,SHORT_REAL_LENGTH/2);
1654    LL->m[1].rtyp=INT_CMD;
1655    LL->m[1].data=(void *)si_max(R->float_len2,SHORT_REAL_LENGTH);
1656  L->m[1].rtyp=LIST_CMD;
1657  L->m[1].data=(void *)LL;
1658  // ----------------------------------------
1659  // 2: list (par)
1660  if (rField_is_long_C(R))
1661  {
1662    L->m[2].rtyp=STRING_CMD;
1663    L->m[2].data=(void *)omStrDup(R->parameter[0]);
1664  }
1665  // ----------------------------------------
1666}
1667
1668#ifdef HAVE_RINGS
1669void rDecomposeRing(leftv h,const ring R)
1670/* field is R or C */
1671{
1672  lists L=(lists)omAlloc0Bin(slists_bin);
1673  if (rField_is_Ring_Z(R)) L->Init(1);
1674  else                     L->Init(2);
1675  h->rtyp=LIST_CMD;
1676  h->data=(void *)L;
1677  // 0: char/ cf - ring
1678  // 1: list (module)
1679  // ----------------------------------------
1680  // 0: char/ cf - ring
1681  L->m[0].rtyp=STRING_CMD;
1682  L->m[0].data=(void *)omStrDup("integer");
1683  // ----------------------------------------
1684  // 1: module
1685  if (rField_is_Ring_Z(R)) return;
1686  lists LL=(lists)omAlloc0Bin(slists_bin);
1687  LL->Init(2);
1688  LL->m[0].rtyp=BIGINT_CMD;
1689  LL->m[0].data=nlMapGMP((number) R->ringflaga);
1690  LL->m[1].rtyp=INT_CMD;
1691  LL->m[1].data=(void *) R->ringflagb;
1692  L->m[1].rtyp=LIST_CMD;
1693  L->m[1].data=(void *)LL;
1694}
1695#endif
1696
1697
1698lists rDecompose(const ring r)
1699{
1700  // sanity check: require currRing==r for rings with polynomial data
1701  if ((r!=currRing)
1702  && ((r->minpoly!=NULL) || (r->qideal!=NULL) || (r->minideal!=NULL)
1703#ifdef HAVE_PLURAL
1704  || (rIsPluralRing(r))
1705#endif
1706  ))
1707  {
1708    WerrorS("ring with polynomial data must be the base ring or compatible");
1709    return NULL;
1710  }
1711  // 0: char/ cf - ring
1712  // 1: list (var)
1713  // 2: list (ord)
1714  // 3: qideal
1715  // possibly:
1716  // 4: C
1717  // 5: D
1718  lists L=(lists)omAlloc0Bin(slists_bin);
1719  if (rIsPluralRing(r))
1720    L->Init(6);
1721  else
1722    L->Init(4);
1723  // ----------------------------------------
1724  // 0: char/ cf - ring
1725  #if 1 /* TODO */
1726  if (rField_is_numeric(r))
1727  {
1728    rDecomposeC(&(L->m[0]),r);
1729  }
1730#ifdef HAVE_RINGS
1731  else if (rField_is_Ring(r))
1732  {
1733    rDecomposeRing(&(L->m[0]),r);
1734  }
1735#endif
1736  else if (rIsExtension(r))
1737  {
1738    if (r->algring!=NULL)
1739      rDecomposeCF(&(L->m[0]),r->algring,r);
1740    else
1741    {
1742      lists Lc=(lists)omAlloc0Bin(slists_bin);
1743      Lc->Init(4);
1744      // char:
1745      Lc->m[0].rtyp=INT_CMD;
1746      Lc->m[0].data=(void*)r->ch;
1747      // var:
1748      lists Lv=(lists)omAlloc0Bin(slists_bin);
1749      Lv->Init(1);
1750      Lv->m[0].rtyp=STRING_CMD;
1751      Lv->m[0].data=(void *)omStrDup(r->parameter[0]);
1752      Lc->m[1].rtyp=LIST_CMD;
1753      Lc->m[1].data=(void*)Lv;
1754      // ord:
1755      lists Lo=(lists)omAlloc0Bin(slists_bin);
1756      Lo->Init(1);
1757      lists Loo=(lists)omAlloc0Bin(slists_bin);
1758      Loo->Init(2);
1759      Loo->m[0].rtyp=STRING_CMD;
1760      Loo->m[0].data=(void *)omStrDup(rSimpleOrdStr(ringorder_lp));
1761      intvec *iv=new intvec(1); (*iv)[0]=1;
1762      Loo->m[1].rtyp=INTVEC_CMD;
1763      Loo->m[1].data=(void *)iv;
1764      Lo->m[0].rtyp=LIST_CMD;
1765      Lo->m[0].data=(void*)Loo;
1766
1767      Lc->m[2].rtyp=LIST_CMD;
1768      Lc->m[2].data=(void*)Lo;
1769      // q-ideal:
1770      Lc->m[3].rtyp=IDEAL_CMD;
1771      Lc->m[3].data=(void *)idInit(1,1);
1772      // ----------------------
1773      L->m[0].rtyp=LIST_CMD;
1774      L->m[0].data=(void*)Lc;
1775    }
1776    if (L->m[0].rtyp==0)
1777    {
1778      //omFreeBin(slists_bin,(void *)L);
1779      return NULL;
1780    }
1781  }
1782  else
1783  #endif
1784  {
1785    L->m[0].rtyp=INT_CMD;
1786    L->m[0].data=(void *)r->ch;
1787  }
1788  // ----------------------------------------
1789  // 1: list (var)
1790  lists LL=(lists)omAlloc0Bin(slists_bin);
1791  LL->Init(r->N);
1792  int i;
1793  for(i=0; i<r->N; i++)
1794  {
1795    LL->m[i].rtyp=STRING_CMD;
1796    LL->m[i].data=(void *)omStrDup(r->names[i]);
1797  }
1798  L->m[1].rtyp=LIST_CMD;
1799  L->m[1].data=(void *)LL;
1800  // ----------------------------------------
1801  // 2: list (ord)
1802  LL=(lists)omAlloc0Bin(slists_bin);
1803  i=rBlocks(r)-1;
1804  LL->Init(i);
1805  i--;
1806  lists LLL;
1807  for(; i>=0; i--)
1808  {
1809    intvec *iv;
1810    int j;
1811    LL->m[i].rtyp=LIST_CMD;
1812    LLL=(lists)omAlloc0Bin(slists_bin);
1813    LLL->Init(2);
1814    LLL->m[0].rtyp=STRING_CMD;
1815    LLL->m[0].data=(void *)omStrDup(rSimpleOrdStr(r->order[i]));
1816    if (r->block1[i]-r->block0[i] >=0 )
1817    {
1818      j=r->block1[i]-r->block0[i];
1819      if (r->order[i]==ringorder_M)  j=(j+1)*(j+1)-1;
1820      iv=new intvec(j+1);
1821      if ((r->wvhdl!=NULL) && (r->wvhdl[i]!=NULL))
1822      {
1823        for(;j>=0; j--) (*iv)[j]=r->wvhdl[i][j];
1824      }
1825      else switch (r->order[i])
1826      {
1827        case ringorder_dp:
1828        case ringorder_Dp:
1829        case ringorder_ds:
1830        case ringorder_Ds:
1831        case ringorder_lp:
1832          for(;j>=0; j--) (*iv)[j]=1;
1833          break;
1834        default: /* do nothing */;
1835      }
1836    }
1837    else
1838    {
1839      iv=new intvec(1);
1840    }
1841    LLL->m[1].rtyp=INTVEC_CMD;
1842    LLL->m[1].data=(void *)iv;
1843    LL->m[i].data=(void *)LLL;
1844  }
1845  L->m[2].rtyp=LIST_CMD;
1846  L->m[2].data=(void *)LL;
1847  // ----------------------------------------
1848  // 3: qideal
1849  L->m[3].rtyp=IDEAL_CMD;
1850  if (r->qideal==NULL)
1851    L->m[3].data=(void *)idInit(1,1);
1852  else
1853    L->m[3].data=(void *)idCopy(r->qideal);
1854  // ----------------------------------------
1855  #ifdef HAVE_PLURAL // NC! in rDecompose
1856  if (rIsPluralRing(r)) 
1857  {
1858    L->m[4].rtyp=MATRIX_CMD;
1859    L->m[4].data=(void *)mpCopy(r->GetNC()->C);
1860    L->m[5].rtyp=MATRIX_CMD;
1861    L->m[5].data=(void *)mpCopy(r->GetNC()->D);
1862  }
1863  #endif
1864  return L;
1865}
1866
1867void rComposeC(lists L, ring R)
1868/* field is R or C */
1869{
1870  // ----------------------------------------
1871  // 0: char/ cf - ring
1872  if ((L->m[0].rtyp!=INT_CMD) || (L->m[0].data!=(char *)0))
1873  {
1874    Werror("invald coeff. field description, expecting 0");
1875    return;
1876  }
1877  R->ch=-1;
1878  // ----------------------------------------
1879  // 1:
1880  if (L->m[1].rtyp!=LIST_CMD)
1881    Werror("invald coeff. field description, expecting precision list");
1882  lists LL=(lists)L->m[1].data;
1883  int r1=(int)(long)LL->m[0].data;
1884  int r2=(int)(long)LL->m[1].data;
1885  if ((r1<=SHORT_REAL_LENGTH)
1886  && (r2=SHORT_REAL_LENGTH))
1887  {
1888    R->float_len=SHORT_REAL_LENGTH/2;
1889    R->float_len2=SHORT_REAL_LENGTH;
1890  }
1891  else
1892  {
1893    R->float_len=si_min(r1,32767);
1894    R->float_len2=si_min(r2,32767);
1895  }
1896  // ----------------------------------------
1897  // 2: list (par)
1898  if (L->nr==2)
1899  {
1900    R->P=1;
1901    if (L->m[2].rtyp!=STRING_CMD)
1902    {
1903      Werror("invald coeff. field description, expecting parameter name");
1904      return;
1905    }
1906    R->parameter=(char**)omAlloc0(R->P*sizeof(char_ptr));
1907    R->parameter[0]=omStrDup((char *)L->m[2].data);
1908  }
1909  // ----------------------------------------
1910}
1911
1912#ifdef HAVE_RINGS
1913void rComposeRing(lists L, ring R)
1914/* field is R or C */
1915{
1916  // ----------------------------------------
1917  // 0: string: integer
1918  // no further entries --> Z
1919  R->ringflaga = (int_number) omAlloc(sizeof(mpz_t));
1920  if (L->nr == 0)
1921  {
1922    mpz_init_set_ui(R->ringflaga,0);
1923    R->ringflagb = 1;
1924  }
1925  // ----------------------------------------
1926  // 1:
1927  else
1928  {
1929    if (L->m[1].rtyp!=LIST_CMD) Werror("invald data, expecting list of numbers");
1930    lists LL=(lists)L->m[1].data;
1931    mpz_init(R->ringflaga);
1932    if ((LL->nr >= 0) && LL->m[0].rtyp == BIGINT_CMD)
1933    {
1934      number ringflaga = (number) LL->m[0].data;
1935      nlGMP(ringflaga, (number) R->ringflaga);
1936      LL->m[0].data = (void *)ringflaga;
1937    }
1938    else if ((LL->nr >= 0) && LL->m[0].rtyp == INT_CMD)
1939    {
1940      mpz_set_ui(R->ringflaga,(unsigned long) LL->m[0].data);
1941    }
1942    else
1943    {
1944      mpz_set_ui(R->ringflaga,0);
1945    }
1946    if (LL->nr >= 1)
1947    {
1948      R->ringflagb = (unsigned long) LL->m[1].data;
1949    }
1950    else
1951    {
1952      R->ringflagb = 1;
1953    }
1954  }
1955  // ----------------------------------------
1956  if ((mpz_cmp_ui(R->ringflaga, 1) == 0) && (mpz_cmp_ui(R->ringflaga, 0) < 0))
1957  {
1958    Werror("Wrong ground ring specification (module is 1)");
1959    return;
1960  }
1961  if (R->ringflagb < 1)
1962  {
1963    Werror("Wrong ground ring specification (exponent smaller than 1");
1964    return;
1965  }
1966  // module is 0 ---> integers
1967  if (mpz_cmp_ui(R->ringflaga, 0) == 0)
1968  {
1969    R->ch = 0;
1970    R->ringtype = 4;
1971  }
1972  // we have an exponent
1973  else if (R->ringflagb > 1)
1974  {
1975    R->ch = R->ringflagb;
1976    if ((mpz_cmp_ui(R->ringflaga, 2) == 0) && (R->ringflagb + 2 <= 8*sizeof(NATNUMBER)))
1977    {
1978      R->ringtype = 1;       // Use Z/2^ch
1979    }
1980    else
1981    {
1982      R->ringtype = 3;
1983    }
1984  }
1985  // just a module m > 1
1986  else
1987  {
1988    R->ringtype = 2;
1989    R->ch = mpz_get_ui(R->ringflaga);
1990  }
1991}
1992#endif
1993
1994static void rRenameVars(ring R)
1995{
1996  int i,j;
1997  for(i=0;i<R->N-1;i++)
1998  {
1999    for(j=i+1;j<R->N;j++)
2000    {
2001      if (strcmp(R->names[i],R->names[j])==0)
2002      {
2003        Warn("name conflict var(%d) and var(%d): `%s`, rename to `@(%d)`",i+1,j+1,R->names[i],j+1);
2004        omFree(R->names[j]);
2005        R->names[j]=(char *)omAlloc(10);
2006        sprintf(R->names[j],"@(%d)",j+1);
2007      }
2008    }
2009  }
2010  for(i=0;i<R->P; i++)
2011  {
2012    for(j=0;j<R->N;j++)
2013    {
2014      if (strcmp(R->parameter[i],R->names[j])==0)
2015      {
2016        Warn("name conflict par(%d) and var(%d): `%s`, rename to `@@(%d)`",i+1,j+1,R->names[j],i+1);
2017        omFree(R->parameter[i]);
2018        R->parameter[i]=(char *)omAlloc(10);
2019        sprintf(R->parameter[i],"@@(%d)",i+1);
2020      }
2021    }
2022  }
2023}
2024
2025ring rCompose(const lists  L)
2026{
2027  if ((L->nr!=3)
2028#ifdef HAVE_PLURAL
2029  &&(L->nr!=5)
2030#endif
2031  )
2032    return NULL;
2033  int is_gf_char=0;
2034  // 0: char/ cf - ring
2035  // 1: list (var)
2036  // 2: list (ord)
2037  // 3: qideal
2038  // possibly:
2039  // 4: C
2040  // 5: D
2041  ring R=(ring) omAlloc0Bin(sip_sring_bin);
2042  // ------------------------- VARS ---------------------------
2043  if (L->m[1].Typ()==LIST_CMD)
2044  {
2045    lists v=(lists)L->m[1].Data();
2046    R->N = v->nr+1;
2047    R->names   = (char **)omAlloc0(R->N * sizeof(char_ptr));
2048    int i;
2049    for(i=0;i<R->N;i++)
2050    {
2051      if (v->m[i].Typ()==STRING_CMD)
2052        R->names[i]=omStrDup((char *)v->m[i].Data());
2053      else if (v->m[i].Typ()==POLY_CMD)
2054      {
2055        poly p=(poly)v->m[i].Data();
2056        int nr=pIsPurePower(p);
2057        if (nr>0)
2058          R->names[i]=omStrDup(currRing->names[nr-1]);
2059        else
2060        {
2061          Werror("var name %d must be a string or a ring variable",i+1);
2062          goto rCompose_err;
2063        }
2064      }
2065      else
2066      {
2067        Werror("var name %d must be `string`",i+1);
2068        goto rCompose_err;
2069      }
2070    }
2071  }
2072  else
2073  {
2074    WerrorS("variable must be given as `list`");
2075    goto rCompose_err;
2076  }
2077  // ------------------------ ORDER ------------------------------
2078  if (L->m[2].Typ()==LIST_CMD)
2079  {
2080    lists v=(lists)L->m[2].Data();
2081    int n= v->nr+2;
2082    int j;
2083    // initialize fields of R
2084    R->order=(int *)omAlloc0(n*sizeof(int));
2085    R->block0=(int *)omAlloc0(n*sizeof(int));
2086    R->block1=(int *)omAlloc0(n*sizeof(int));
2087    R->wvhdl=(int**)omAlloc0(n*sizeof(int_ptr));
2088    // init order, so that rBlocks works correctly
2089    for (j=0; j < n-1; j++)
2090      R->order[j] = (int) ringorder_unspec;
2091    // orderings
2092    R->OrdSgn=1;
2093    for(j=0;j<n-1;j++)
2094    {
2095    // todo: a(..), M
2096      if (v->m[j].Typ()!=LIST_CMD)
2097      {
2098        WerrorS("ordering must be list of lists");
2099        goto rCompose_err;
2100      }
2101      lists vv=(lists)v->m[j].Data();
2102      if ((vv->nr!=1)
2103      || (vv->m[0].Typ()!=STRING_CMD)
2104      || ((vv->m[1].Typ()!=INTVEC_CMD) && (vv->m[1].Typ()!=INT_CMD)))
2105      {
2106        WerrorS("ordering name must be a (string,intvec)");
2107        goto rCompose_err;
2108      }
2109      R->order[j]=rOrderName(omStrDup((char*)vv->m[0].Data())); // assume STRING
2110      if (j==0) R->block0[0]=1;
2111      else
2112      {
2113         int jj=j-1;
2114         while((jj>=0)
2115         && ((R->order[jj]== ringorder_a)
2116            || (R->order[jj]== ringorder_aa)
2117            || (R->order[jj]== ringorder_c)
2118            || (R->order[jj]== ringorder_C)
2119         ))
2120         {
2121           //Print("jj=%, skip %s\n",rSimpleOrdStr(R->order[jj]));
2122           jj--;
2123         }
2124         if (jj<0) R->block0[j]=1;
2125         else       R->block0[j]=R->block1[jj]+1;
2126      }
2127      intvec *iv;
2128      if (vv->m[1].Typ()==INT_CMD)
2129        iv=new intvec((int)(long)vv->m[1].Data(),(int)(long)vv->m[1].Data());
2130      else
2131        iv=ivCopy((intvec*)vv->m[1].Data()); //assume INTVEC
2132      R->block1[j]=si_max(R->block0[j],R->block0[j]+iv->length()-1);
2133      //Print("block %d from %d to %d\n",j,R->block0[j], R->block1[j]);
2134      int i;
2135      switch (R->order[j])
2136      {
2137         case ringorder_ws:
2138         case ringorder_Ws:
2139            R->OrdSgn=-1;
2140         case ringorder_aa:
2141         case ringorder_a:
2142         case ringorder_wp:
2143         case ringorder_Wp:
2144           R->wvhdl[j] =( int *)omAlloc((iv->length())*sizeof(int));
2145           for (i=0; i<iv->length();i++)
2146           {
2147             R->wvhdl[j][i]=(*iv)[i];
2148           }
2149           break;
2150         case ringorder_M:
2151           R->wvhdl[j] =( int *)omAlloc((iv->length())*sizeof(int));
2152           for (i=0; i<iv->length();i++) R->wvhdl[j][i]=(*iv)[i];
2153           R->block1[j]=si_max(R->block0[j],R->block0[j]+(int)sqrt((double)(iv->length()-1)));
2154           break;
2155         case ringorder_ls:
2156         case ringorder_ds:
2157         case ringorder_Ds:
2158         case ringorder_rs:
2159           R->OrdSgn=-1;
2160         case ringorder_lp:
2161         case ringorder_dp:
2162         case ringorder_Dp:
2163         case ringorder_rp:
2164           break;
2165         case ringorder_S:
2166           break;
2167         case ringorder_c:
2168         case ringorder_C:
2169           R->block1[j]=R->block0[j]=0;
2170           break;
2171         case 0:
2172         case ringorder_unspec:
2173           break;
2174      }
2175      delete iv;
2176    }
2177    // sanity check
2178    j=n-2;
2179    if ((R->order[j]==ringorder_c)
2180    || (R->order[j]==ringorder_C)
2181    || (R->order[j]==ringorder_unspec)) j--;
2182    if (R->block1[j] != R->N)
2183    {
2184      if (((R->order[j]==ringorder_dp) ||
2185           (R->order[j]==ringorder_ds) ||
2186           (R->order[j]==ringorder_Dp) ||
2187           (R->order[j]==ringorder_Ds) ||
2188           (R->order[j]==ringorder_rp) ||
2189           (R->order[j]==ringorder_rs) ||
2190           (R->order[j]==ringorder_lp) ||
2191           (R->order[j]==ringorder_ls))
2192          &&
2193            R->block0[j] <= R->N)
2194      {
2195        R->block1[j] = R->N;
2196      }
2197      else
2198      {
2199        Werror("ordering incomplete: size (%d) should be %d",R->block1[j],R->N);
2200        goto rCompose_err;
2201      }
2202    }
2203  }
2204  else
2205  {
2206    WerrorS("ordering must be given as `list`");
2207    goto rCompose_err;
2208  }
2209  // ------------------------------------------------------------------
2210  // 0: char:
2211  if (L->m[0].Typ()==INT_CMD)
2212  {
2213    R->ch=(int)(long)L->m[0].Data();
2214    if (R->ch!=-1)
2215    {
2216      int l=0;
2217      if (((R->ch!=0) && (R->ch<2) && (is_gf_char=-1))
2218      #ifndef NV_OPS
2219      || (R->ch > 32003)
2220      #endif
2221      || ((l=IsPrime(R->ch))!=R->ch)
2222      )
2223      {
2224        Warn("%d is invalid characteristic of ground field. %d is used.", R->ch,l);
2225        R->ch=l;
2226      }
2227    }
2228  }
2229  else if (L->m[0].Typ()==LIST_CMD)
2230  {
2231    lists LL=(lists)L->m[0].Data();
2232#ifdef HAVE_RINGS
2233    if (LL->m[0].Typ() == STRING_CMD)
2234    {
2235      rComposeRing(LL,R); /* Ring */
2236    }
2237    else
2238#endif
2239    if (LL->nr<3)
2240      rComposeC(LL,R); /* R, long_R, long_C */
2241    else
2242    {
2243      if (LL->m[0].Typ()==INT_CMD)
2244      {
2245        int ch=(int)(long)LL->m[0].Data();
2246        while ((ch!=fftable[is_gf_char]) && (fftable[is_gf_char])) is_gf_char++;
2247        if (fftable[is_gf_char]==0) is_gf_char=-1;
2248      }
2249      if (is_gf_char==-1)
2250      {
2251        R->algring=rCompose((lists)L->m[0].Data());
2252        if (R->algring==NULL)
2253        {
2254          WerrorS("could not create rational function coefficient field");
2255          goto rCompose_err;
2256        }
2257        if (R->algring->ch>0)
2258          R->ch= -R->algring->ch;
2259        else
2260          R->ch=1;
2261        R->P=R->algring->N;
2262        R->parameter=(char**)omAlloc0(R->P*sizeof(char_ptr));
2263        int i;
2264        for(i=R->P-1;i>=0;i--)
2265          R->parameter[i]=omStrDup(R->algring->names[i]);
2266        if (R->algring->qideal!=NULL)
2267        {
2268          if (IDELEMS(R->algring->qideal)==1)
2269          {
2270            R->minpoly=naInit(1,R);
2271            lnumber n=(lnumber)R->minpoly;
2272            n->z=R->algring->qideal->m[0];
2273            R->algring->qideal->m[0]=NULL;
2274            idDelete(&(R->algring->qideal));
2275          }
2276          else
2277          {
2278            WerrorS("not implemented yet.");
2279          }
2280        }
2281      }
2282      else
2283      { // gf-char
2284        R->ch=fftable[is_gf_char];
2285        R->P=1;
2286        R->parameter=(char**)omAlloc0(1*sizeof(char_ptr));
2287        R->parameter[0]=omStrDup((char*)((lists)(LL->m[1].Data()))->m[0].Data());
2288      }
2289    }
2290  }
2291  else
2292  {
2293    WerrorS("coefficient field must be described by `int` or `list`");
2294    goto rCompose_err;
2295  }
2296  rRenameVars(R);
2297  // ------------------------ Q-IDEAL ------------------------
2298  rComplete(R);
2299
2300  if (L->m[3].Typ()==IDEAL_CMD)
2301  {
2302    ideal q=(ideal)L->m[3].Data();
2303    if (q->m[0]!=NULL)
2304    {
2305      if (R->ch!=currRing->ch)
2306      {
2307      #if 0
2308            WerrorS("coefficient fields must be equal if q-ideal !=0");
2309            goto rCompose_err;
2310      #else
2311        ring orig_ring=currRing;
2312        rChangeCurrRing(R);
2313        int *perm=NULL;
2314        int *par_perm=NULL;
2315        int par_perm_size=0;
2316        nMapFunc nMap;
2317        BOOLEAN bo;
2318
2319        if ((nMap=nSetMap(orig_ring))==NULL)
2320        {
2321          if (rEqual(orig_ring,currRing))
2322          {
2323            nMap=nCopy;
2324          }
2325          else
2326          // Allow imap/fetch to be make an exception only for:
2327          if ( (rField_is_Q_a(orig_ring) &&  // Q(a..) -> Q(a..) || Q || Zp || Zp(a)
2328            (rField_is_Q() || rField_is_Q_a() ||
2329             (rField_is_Zp() || rField_is_Zp_a())))
2330           ||
2331           (rField_is_Zp_a(orig_ring) &&  // Zp(a..) -> Zp(a..) || Zp
2332            (rField_is_Zp(currRing, rInternalChar(orig_ring)) ||
2333             rField_is_Zp_a(currRing, rInternalChar(orig_ring)))) )
2334          {
2335            par_perm_size=rPar(orig_ring);
2336            BITSET save_test=test;
2337            naSetChar(rInternalChar(orig_ring),orig_ring);
2338            nSetChar(currRing);
2339            test=save_test;
2340          }
2341          else
2342          {
2343            WerrorS("coefficient fields must be equal if q-ideal !=0");
2344            goto rCompose_err;
2345          }
2346        }
2347        perm=(int *)omAlloc0((orig_ring->N+1)*sizeof(int));
2348        if (par_perm_size!=0)
2349          par_perm=(int *)omAlloc0(par_perm_size*sizeof(int));
2350        int i;
2351        #if 0
2352        // use imap:
2353        maFindPerm(orig_ring->names,orig_ring->N,orig_ring->parameter,orig_ring->P,
2354          currRing->names,currRing->N,currRing->parameter, currRing->P,
2355          perm,par_perm, currRing->ch);
2356        #else
2357        // use fetch
2358        if ((rPar(orig_ring)>0) && (rPar(currRing)==0))
2359        {
2360          for(i=si_min(rPar(orig_ring),rVar(currRing))-1;i>=0;i--) par_perm[i]=i+1;
2361        }
2362        else if (par_perm_size!=0)
2363          for(i=si_min(rPar(orig_ring),rPar(currRing))-1;i>=0;i--) par_perm[i]=-(i+1);
2364        for(i=si_min(orig_ring->N,pVariables);i>0;i--) perm[i]=i;
2365        #endif
2366        ideal dest_id=idInit(IDELEMS(q),1);
2367        for(i=IDELEMS(q)-1; i>=0; i--)
2368        {
2369          dest_id->m[i]=pPermPoly(q->m[i],perm,orig_ring,nMap,
2370                                  par_perm,par_perm_size);
2371          //  PrintS("map:");pWrite(dest_id->m[i]);PrintLn();
2372          pTest(dest_id->m[i]);
2373        }
2374        R->qideal=dest_id;
2375        if (perm!=NULL)
2376          omFreeSize((ADDRESS)perm,(orig_ring->N+1)*sizeof(int));
2377        if (par_perm!=NULL)
2378          omFreeSize((ADDRESS)par_perm,par_perm_size*sizeof(int));
2379        rChangeCurrRing(orig_ring);
2380      #endif
2381      }
2382      else
2383        R->qideal=idrCopyR(q,currRing,R);
2384    }
2385  }
2386  else
2387  {
2388    WerrorS("q-ideal must be given as `ideal`");
2389    goto rCompose_err;
2390  }
2391
2392
2393  // ---------------------------------------------------------------
2394  #ifdef HAVE_PLURAL
2395  if (L->nr==5)
2396  {
2397    if (nc_CallPlural((matrix)L->m[4].Data(),(matrix)L->m[5].Data(),NULL,NULL,R, true)) goto rCompose_err;
2398    // takes care about non-comm. quotient! i.e. calls "nc_SetupQuotient" due to last true
2399  }
2400  #endif
2401  return R;
2402
2403rCompose_err:
2404  if (R->N>0)
2405  {
2406    int i;
2407    if (R->names!=NULL)
2408    {
2409      i=R->N-1;
2410      while (i>=0) { if (R->names[i]!=NULL) omFree(R->names[i]); i--; }
2411      omFree(R->names);
2412    }
2413  }
2414  if (R->order!=NULL) omFree(R->order);
2415  if (R->block0!=NULL) omFree(R->block0);
2416  if (R->block1!=NULL) omFree(R->block1);
2417  if (R->wvhdl!=NULL) omFree(R->wvhdl);
2418  omFree(R);
2419  return NULL;
2420}
2421
2422// from matpol.cc
2423
2424/*2
2425* compute the jacobi matrix of an ideal
2426*/
2427BOOLEAN mpJacobi(leftv res,leftv a)
2428{
2429  int     i,j;
2430  matrix result;
2431  ideal id=(ideal)a->Data();
2432
2433  result =mpNew(IDELEMS(id),pVariables);
2434  for (i=1; i<=IDELEMS(id); i++)
2435  {
2436    for (j=1; j<=pVariables; j++)
2437    {
2438      MATELEM(result,i,j) = pDiff(id->m[i-1],j);
2439    }
2440  }
2441  res->data=(char *)result;
2442  return FALSE;
2443}
2444
2445/*2
2446* returns the Koszul-matrix of degree d of a vectorspace with dimension n
2447* uses the first n entrees of id, if id <> NULL
2448*/
2449BOOLEAN mpKoszul(leftv res,leftv c/*ip*/, leftv b/*in*/, leftv id)
2450{
2451  int n=(int)(long)b->Data();
2452  int d=(int)(long)c->Data();
2453  int     k,l,sign,row,col;
2454  matrix  result;
2455  ideal temp;
2456  BOOLEAN bo;
2457  poly    p;
2458
2459  if ((d>n) || (d<1) || (n<1))
2460  {
2461    res->data=(char *)mpNew(1,1);
2462    return FALSE;
2463  }
2464  int *choise = (int*)omAlloc(d*sizeof(int));
2465  if (id==NULL)
2466    temp=idMaxIdeal(1);
2467  else
2468    temp=(ideal)id->Data();
2469
2470  k = binom(n,d);
2471  l = k*d;
2472  l /= n-d+1;
2473  result =mpNew(l,k);
2474  col = 1;
2475  idInitChoise(d,1,n,&bo,choise);
2476  while (!bo)
2477  {
2478    sign = 1;
2479    for (l=1;l<=d;l++)
2480    {
2481      if (choise[l-1]<=IDELEMS(temp))
2482      {
2483        p = pCopy(temp->m[choise[l-1]-1]);
2484        if (sign == -1) p = pNeg(p);
2485        sign *= -1;
2486        row = idGetNumberOfChoise(l-1,d,1,n,choise);
2487        MATELEM(result,row,col) = p;
2488      }
2489    }
2490    col++;
2491    idGetNextChoise(d,n,&bo,choise);
2492  }
2493  if (id==NULL) idDelete(&temp);
2494
2495  res->data=(char *)result;
2496  return FALSE;
2497}
2498
2499// from syz1.cc
2500/*2
2501* read out the Betti numbers from resolution
2502* (interpreter interface)
2503*/
2504BOOLEAN syBetti2(leftv res, leftv u, leftv w)
2505{
2506  syStrategy syzstr=(syStrategy)u->Data();
2507  BOOLEAN minim=(int)(long)w->Data();
2508  int row_shift=0;
2509  int add_row_shift=0;
2510  intvec *weights=NULL;
2511  intvec *ww=(intvec *)atGet(u,"isHomog",INTVEC_CMD);
2512  if (ww!=NULL)
2513  {
2514     weights=ivCopy(ww);
2515     add_row_shift = ww->min_in();
2516     (*weights) -= add_row_shift;
2517  }
2518  res->data=(void *)syBettiOfComputation(syzstr,minim,&row_shift,weights);
2519  //row_shift += add_row_shift;
2520  //Print("row_shift=%d, add_row_shift=%d\n",row_shift,add_row_shift);
2521  atSet(res,omStrDup("rowShift"),(void*)add_row_shift,INT_CMD);
2522  return FALSE;
2523}
2524BOOLEAN syBetti1(leftv res, leftv u)
2525{
2526  sleftv tmp;
2527  memset(&tmp,0,sizeof(tmp));
2528  tmp.rtyp=INT_CMD;
2529  tmp.data=(void *)1;
2530  return syBetti2(res,u,&tmp);
2531}
2532
2533/*3
2534* converts a resolution into a list of modules
2535*/
2536lists syConvRes(syStrategy syzstr,BOOLEAN toDel,int add_row_shift)
2537{
2538  if ((syzstr->fullres==NULL) && (syzstr->minres==NULL))
2539  {
2540    if (syzstr->hilb_coeffs==NULL)
2541    {
2542      syzstr->fullres = syReorder(syzstr->res,syzstr->length,syzstr);
2543    }
2544    else
2545    {
2546      syzstr->minres = syReorder(syzstr->orderedRes,syzstr->length,syzstr);
2547      syKillEmptyEntres(syzstr->minres,syzstr->length);
2548    }
2549  }
2550  resolvente tr;
2551  int typ0=IDEAL_CMD;
2552  if (syzstr->minres!=NULL)
2553    tr = syzstr->minres;
2554  else
2555    tr = syzstr->fullres;
2556  resolvente trueres=NULL;
2557  intvec ** w=NULL;
2558  if (syzstr->length>0)
2559  {
2560    trueres=(resolvente)omAlloc0((syzstr->length)*sizeof(ideal));
2561    for (int i=(syzstr->length)-1;i>=0;i--)
2562    {
2563      if (tr[i]!=NULL)
2564      {
2565        trueres[i] = idCopy(tr[i]);
2566      }
2567    }
2568    if (idRankFreeModule(trueres[0]) > 0)
2569      typ0 = MODUL_CMD;
2570    if (syzstr->weights!=NULL)
2571    {
2572      w = (intvec**)omAlloc0((syzstr->length)*sizeof(intvec*));
2573      for (int i=(syzstr->length)-1;i>=0;i--)
2574      {
2575        if (syzstr->weights[i]!=NULL) w[i] = ivCopy(syzstr->weights[i]);
2576      }
2577    }
2578  }
2579  lists li = liMakeResolv(trueres,syzstr->length,syzstr->list_length,typ0,
2580                          w,add_row_shift);
2581  if (w != NULL) omFreeSize(w, (syzstr->length)*sizeof(intvec*));
2582  if (toDel) syKillComputation(syzstr);
2583  return li;
2584}
2585
2586/*3
2587* converts a list of modules into a resolution
2588*/
2589syStrategy syConvList(lists li,BOOLEAN toDel)
2590{
2591  int typ0;
2592  syStrategy result=(syStrategy)omAlloc0(sizeof(ssyStrategy));
2593
2594  resolvente fr = liFindRes(li,&(result->length),&typ0,&(result->weights));
2595  if (fr != NULL)
2596  {
2597
2598    result->fullres = (resolvente)omAlloc0((result->length+1)*sizeof(ideal));
2599    for (int i=result->length-1;i>=0;i--)
2600    {
2601      if (fr[i]!=NULL)
2602        result->fullres[i] = idCopy(fr[i]);
2603    }
2604    result->list_length=result->length;
2605    omFreeSize((ADDRESS)fr,(result->length)*sizeof(ideal));
2606  }
2607  else
2608  {
2609    omFreeSize(result, sizeof(ssyStrategy));
2610    result = NULL;
2611  }
2612  if (toDel) li->Clean();
2613  return result;
2614}
2615
2616/*3
2617* converts a list of modules into a minimal resolution
2618*/
2619syStrategy syForceMin(lists li)
2620{
2621  int typ0;
2622  syStrategy result=(syStrategy)omAlloc0(sizeof(ssyStrategy));
2623
2624  resolvente fr = liFindRes(li,&(result->length),&typ0);
2625  result->minres = (resolvente)omAlloc0((result->length+1)*sizeof(ideal));
2626  for (int i=result->length-1;i>=0;i--)
2627  {
2628    if (fr[i]!=NULL)
2629      result->minres[i] = idCopy(fr[i]);
2630  }
2631  omFreeSize((ADDRESS)fr,(result->length)*sizeof(ideal));
2632  return result;
2633}
2634// from weight.cc
2635BOOLEAN kWeight(leftv res,leftv id)
2636{
2637  ideal F=(ideal)id->Data();
2638  intvec * iv = new intvec(pVariables);
2639  polyset s;
2640  int  sl, n, i;
2641  int  *x;
2642
2643  res->data=(char *)iv;
2644  s = F->m;
2645  sl = IDELEMS(F) - 1;
2646  n = pVariables;
2647  double wNsqr = (double)2.0 / (double)n;
2648  wFunctional = wFunctionalBuch;
2649  x = (int * )omAlloc(2 * (n + 1) * sizeof(int));
2650  wCall(s, sl, x, wNsqr);
2651  for (i = n; i!=0; i--)
2652    (*iv)[i-1] = x[i + n + 1];
2653  omFreeSize((ADDRESS)x, 2 * (n + 1) * sizeof(int));
2654  return FALSE;
2655}
2656
2657BOOLEAN kQHWeight(leftv res,leftv v)
2658{
2659  res->data=(char *)idQHomWeight((ideal)v->Data());
2660  if (res->data==NULL)
2661    res->data=(char *)new intvec(pVariables);
2662  return FALSE;
2663}
2664/*==============================================================*/
2665// from clapsing.cc
2666#if 0
2667BOOLEAN jjIS_SQR_FREE(leftv res, leftv u)
2668{
2669  BOOLEAN b=singclap_factorize((poly)(u->CopyD()), &v, 0);
2670  res->data=(void *)b;
2671}
2672#endif
2673
2674BOOLEAN jjRESULTANT(leftv res, leftv u, leftv v, leftv w)
2675{
2676  res->data=singclap_resultant((poly)u->Data(),(poly)v->Data(), (poly)w->Data());
2677  return errorreported;
2678}
2679BOOLEAN jjCHARSERIES(leftv res, leftv u)
2680{
2681  res->data=singclap_irrCharSeries((ideal)u->Data());
2682  return (res->data==NULL);
2683}
2684
2685// from semic.cc
2686#ifdef HAVE_SPECTRUM
2687
2688// ----------------------------------------------------------------------------
2689//  Initialize a  spectrum  deep from another  spectrum
2690// ----------------------------------------------------------------------------
2691
2692void spectrum::copy_deep( const spectrum &spec )
2693{
2694    mu = spec.mu;
2695    pg = spec.pg;
2696    n  = spec.n;
2697
2698    copy_new( n );
2699
2700    for( int i=0; i<n; i++ )
2701    {
2702        s[i] = spec.s[i];
2703        w[i] = spec.w[i];
2704    }
2705}
2706
2707// ----------------------------------------------------------------------------
2708//  Initialize a  spectrum  deep from a  singular  lists
2709// ----------------------------------------------------------------------------
2710
2711void spectrum::copy_deep( lists l )
2712{
2713    mu = (int)(long)(l->m[0].Data( ));
2714    pg = (int)(long)(l->m[1].Data( ));
2715    n  = (int)(long)(l->m[2].Data( ));
2716
2717    copy_new( n );
2718
2719    intvec  *num = (intvec*)l->m[3].Data( );
2720    intvec  *den = (intvec*)l->m[4].Data( );
2721    intvec  *mul = (intvec*)l->m[5].Data( );
2722
2723    for( int i=0; i<n; i++ )
2724    {
2725        s[i] = (Rational)((*num)[i])/(Rational)((*den)[i]);
2726        w[i] = (*mul)[i];
2727    }
2728}
2729
2730// ----------------------------------------------------------------------------
2731//  singular lists  constructor for  spectrum
2732// ----------------------------------------------------------------------------
2733
2734spectrum::spectrum( lists l )
2735{
2736    copy_deep( l );
2737}
2738
2739// ----------------------------------------------------------------------------
2740//  generate a Singular  lists  from a spectrum
2741// ----------------------------------------------------------------------------
2742
2743lists   spectrum::thelist( void )
2744{
2745    lists   L  = (lists)omAllocBin( slists_bin);
2746
2747    L->Init( 6 );
2748
2749    intvec            *num  = new intvec( n );
2750    intvec            *den  = new intvec( n );
2751    intvec            *mult = new intvec( n );
2752
2753    for( int i=0; i<n; i++ )
2754    {
2755        (*num) [i] = s[i].get_num_si( );
2756        (*den) [i] = s[i].get_den_si( );
2757        (*mult)[i] = w[i];
2758    }
2759
2760    L->m[0].rtyp = INT_CMD;    //  milnor number
2761    L->m[1].rtyp = INT_CMD;    //  geometrical genus
2762    L->m[2].rtyp = INT_CMD;    //  # of spectrum numbers
2763    L->m[3].rtyp = INTVEC_CMD; //  numerators
2764    L->m[4].rtyp = INTVEC_CMD; //  denomiantors
2765    L->m[5].rtyp = INTVEC_CMD; //  multiplicities
2766
2767    L->m[0].data = (void*)mu;
2768    L->m[1].data = (void*)pg;
2769    L->m[2].data = (void*)n;
2770    L->m[3].data = (void*)num;
2771    L->m[4].data = (void*)den;
2772    L->m[5].data = (void*)mult;
2773
2774    return  L;
2775}
2776// from spectrum.cc
2777// ----------------------------------------------------------------------------
2778//  print out an error message for a spectrum list
2779// ----------------------------------------------------------------------------
2780
2781void    list_error( semicState state )
2782{
2783    switch( state )
2784    {
2785        case semicListTooShort:
2786            WerrorS( "the list is too short" );
2787            break;
2788        case semicListTooLong:
2789            WerrorS( "the list is too long" );
2790            break;
2791
2792        case semicListFirstElementWrongType:
2793            WerrorS( "first element of the list should be int" );
2794            break;
2795        case semicListSecondElementWrongType:
2796            WerrorS( "second element of the list should be int" );
2797            break;
2798        case semicListThirdElementWrongType:
2799            WerrorS( "third element of the list should be int" );
2800            break;
2801        case semicListFourthElementWrongType:
2802            WerrorS( "fourth element of the list should be intvec" );
2803            break;
2804        case semicListFifthElementWrongType:
2805            WerrorS( "fifth element of the list should be intvec" );
2806            break;
2807        case semicListSixthElementWrongType:
2808            WerrorS( "sixth element of the list should be intvec" );
2809            break;
2810
2811        case semicListNNegative:
2812            WerrorS( "first element of the list should be positive" );
2813            break;
2814        case semicListWrongNumberOfNumerators:
2815            WerrorS( "wrong number of numerators" );
2816            break;
2817        case semicListWrongNumberOfDenominators:
2818            WerrorS( "wrong number of denominators" );
2819            break;
2820        case semicListWrongNumberOfMultiplicities:
2821            WerrorS( "wrong number of multiplicities" );
2822            break;
2823
2824        case semicListMuNegative:
2825            WerrorS( "the Milnor number should be positive" );
2826            break;
2827        case semicListPgNegative:
2828            WerrorS( "the geometrical genus should be nonnegative" );
2829            break;
2830        case semicListNumNegative:
2831            WerrorS( "all numerators should be positive" );
2832            break;
2833        case semicListDenNegative:
2834            WerrorS( "all denominators should be positive" );
2835            break;
2836        case semicListMulNegative:
2837            WerrorS( "all multiplicities should be positive" );
2838            break;
2839
2840        case semicListNotSymmetric:
2841            WerrorS( "it is not symmetric" );
2842            break;
2843        case semicListNotMonotonous:
2844            WerrorS( "it is not monotonous" );
2845            break;
2846
2847        case semicListMilnorWrong:
2848            WerrorS( "the Milnor number is wrong" );
2849            break;
2850        case semicListPGWrong:
2851            WerrorS( "the geometrical genus is wrong" );
2852            break;
2853
2854        default:
2855            WerrorS( "unspecific error" );
2856            break;
2857    }
2858}
2859// ----------------------------------------------------------------------------
2860//  this is the main spectrum computation function
2861// ----------------------------------------------------------------------------
2862
2863spectrumState   spectrumCompute( poly h,lists *L,int fast )
2864{
2865  int i,j;
2866
2867  #ifdef SPECTRUM_DEBUG
2868  #ifdef SPECTRUM_PRINT
2869  #ifdef SPECTRUM_IOSTREAM
2870    cout << "spectrumCompute\n";
2871    if( fast==0 ) cout << "    no optimization" << endl;
2872    if( fast==1 ) cout << "    weight optimization" << endl;
2873    if( fast==2 ) cout << "    symmetry optimization" << endl;
2874  #else
2875    fprintf( stdout,"spectrumCompute\n" );
2876    if( fast==0 ) fprintf( stdout,"    no optimization\n" );
2877    if( fast==1 ) fprintf( stdout,"    weight optimization\n" );
2878    if( fast==2 ) fprintf( stdout,"    symmetry optimization\n" );
2879  #endif
2880  #endif
2881  #endif
2882
2883  // ----------------------
2884  //  check if  h  is zero
2885  // ----------------------
2886
2887  if( h==(poly)NULL )
2888  {
2889    return  spectrumZero;
2890  }
2891
2892  // ----------------------------------
2893  //  check if  h  has a constant term
2894  // ----------------------------------
2895
2896  if( hasConstTerm( h ) )
2897  {
2898    return  spectrumBadPoly;
2899  }
2900
2901  // --------------------------------
2902  //  check if  h  has a linear term
2903  // --------------------------------
2904
2905  if( hasLinearTerm( h ) )
2906  {
2907    *L = (lists)omAllocBin( slists_bin);
2908    (*L)->Init( 1 );
2909    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
2910    /* (*L)->m[0].data = (void*)0;a  -- done by Init */
2911
2912    return  spectrumNoSingularity;
2913  }
2914
2915  // ----------------------------------
2916  //  compute the jacobi ideal of  (h)
2917  // ----------------------------------
2918
2919  ideal J = NULL;
2920  J = idInit( pVariables,1 );
2921
2922  #ifdef SPECTRUM_DEBUG
2923  #ifdef SPECTRUM_PRINT
2924  #ifdef SPECTRUM_IOSTREAM
2925    cout << "\n   computing the Jacobi ideal...\n";
2926  #else
2927    fprintf( stdout,"\n   computing the Jacobi ideal...\n" );
2928  #endif
2929  #endif
2930  #endif
2931
2932  for( i=0; i<pVariables; i++ )
2933  {
2934    J->m[i] = pDiff( h,i+1); //j );
2935
2936    #ifdef SPECTRUM_DEBUG
2937    #ifdef SPECTRUM_PRINT
2938    #ifdef SPECTRUM_IOSTREAM
2939      cout << "        ";
2940    #else
2941      fprintf( stdout,"        " );
2942    #endif
2943      pWrite( J->m[i] );
2944    #endif
2945    #endif
2946  }
2947
2948  // --------------------------------------------
2949  //  compute a standard basis  stdJ  of  jac(h)
2950  // --------------------------------------------
2951
2952  #ifdef SPECTRUM_DEBUG
2953  #ifdef SPECTRUM_PRINT
2954  #ifdef SPECTRUM_IOSTREAM
2955    cout << endl;
2956    cout << "    computing a standard basis..." << endl;
2957  #else
2958    fprintf( stdout,"\n" );
2959    fprintf( stdout,"    computing a standard basis...\n" );
2960  #endif
2961  #endif
2962  #endif
2963
2964  ideal stdJ = kStd(J,currQuotient,isNotHomog,NULL);
2965  idSkipZeroes( stdJ );
2966
2967  #ifdef SPECTRUM_DEBUG
2968  #ifdef SPECTRUM_PRINT
2969    for( i=0; i<IDELEMS(stdJ); i++ )
2970    {
2971      #ifdef SPECTRUM_IOSTREAM
2972        cout << "        ";
2973      #else
2974        fprintf( stdout,"        " );
2975      #endif
2976
2977      pWrite( stdJ->m[i] );
2978    }
2979  #endif
2980  #endif
2981
2982  idDelete( &J );
2983
2984  // ------------------------------------------
2985  //  check if the  h  has a singularity
2986  // ------------------------------------------
2987
2988  if( hasOne( stdJ ) )
2989  {
2990    // -------------------------------
2991    //  h is smooth in the origin
2992    //  return only the Milnor number
2993    // -------------------------------
2994
2995    *L = (lists)omAllocBin( slists_bin);
2996    (*L)->Init( 1 );
2997    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
2998    /* (*L)->m[0].data = (void*)0;a  -- done by Init */
2999
3000    return  spectrumNoSingularity;
3001  }
3002
3003  // ------------------------------------------
3004  //  check if the singularity  h  is isolated
3005  // ------------------------------------------
3006
3007  for( i=pVariables; i>0; i-- )
3008  {
3009    if( hasAxis( stdJ,i )==FALSE )
3010    {
3011      return  spectrumNotIsolated;
3012    }
3013  }
3014
3015  // ------------------------------------------
3016  //  compute the highest corner  hc  of  stdJ
3017  // ------------------------------------------
3018
3019  #ifdef SPECTRUM_DEBUG
3020  #ifdef SPECTRUM_PRINT
3021  #ifdef SPECTRUM_IOSTREAM
3022    cout << "\n    computing the highest corner...\n";
3023  #else
3024    fprintf( stdout,"\n    computing the highest corner...\n" );
3025  #endif
3026  #endif
3027  #endif
3028
3029  poly hc = (poly)NULL;
3030
3031  scComputeHC( stdJ,currQuotient, 0,hc );
3032
3033  if( hc!=(poly)NULL )
3034  {
3035    pGetCoeff(hc) = nInit(1);
3036
3037    for( i=pVariables; i>0; i-- )
3038    {
3039      if( pGetExp( hc,i )>0 ) pDecrExp( hc,i );
3040    }
3041    pSetm( hc );
3042  }
3043  else
3044  {
3045    return  spectrumNoHC;
3046  }
3047
3048  #ifdef SPECTRUM_DEBUG
3049  #ifdef SPECTRUM_PRINT
3050  #ifdef SPECTRUM_IOSTREAM
3051    cout << "       ";
3052  #else
3053    fprintf( stdout,"       " );
3054  #endif
3055    pWrite( hc );
3056  #endif
3057  #endif
3058
3059  // ----------------------------------------
3060  //  compute the Newton polygon  nph  of  h
3061  // ----------------------------------------
3062
3063  #ifdef SPECTRUM_DEBUG
3064  #ifdef SPECTRUM_PRINT
3065  #ifdef SPECTRUM_IOSTREAM
3066    cout << "\n    computing the newton polygon...\n";
3067  #else
3068    fprintf( stdout,"\n    computing the newton polygon...\n" );
3069  #endif
3070  #endif
3071  #endif
3072
3073  newtonPolygon nph( h );
3074
3075  #ifdef SPECTRUM_DEBUG
3076  #ifdef SPECTRUM_PRINT
3077    cout << nph;
3078  #endif
3079  #endif
3080
3081  // -----------------------------------------------
3082  //  compute the weight corner  wc  of  (stdj,nph)
3083  // -----------------------------------------------
3084
3085  #ifdef SPECTRUM_DEBUG
3086  #ifdef SPECTRUM_PRINT
3087  #ifdef SPECTRUM_IOSTREAM
3088    cout << "\n    computing the weight corner...\n";
3089  #else
3090    fprintf( stdout,"\n    computing the weight corner...\n" );
3091  #endif
3092  #endif
3093  #endif
3094
3095  poly    wc = ( fast==0 ? pCopy( hc ) :
3096               ( fast==1 ? computeWC( nph,(Rational)pVariables ) :
3097              /* fast==2 */computeWC( nph,((Rational)pVariables)/(Rational)2 ) ) );
3098
3099  #ifdef SPECTRUM_DEBUG
3100  #ifdef SPECTRUM_PRINT
3101  #ifdef SPECTRUM_IOSTREAM
3102    cout << "        ";
3103  #else
3104    fprintf( stdout,"        " );
3105  #endif
3106    pWrite( wc );
3107  #endif
3108  #endif
3109
3110  // -------------
3111  //  compute  NF
3112  // -------------
3113
3114  #ifdef SPECTRUM_DEBUG
3115  #ifdef SPECTRUM_PRINT
3116  #ifdef SPECTRUM_IOSTREAM
3117    cout << "\n    computing NF...\n" << endl;
3118  #else
3119    fprintf( stdout,"\n    computing NF...\n" );
3120  #endif
3121  #endif
3122  #endif
3123
3124  spectrumPolyList NF( &nph );
3125
3126  computeNF( stdJ,hc,wc,&NF );
3127
3128  #ifdef SPECTRUM_DEBUG
3129  #ifdef SPECTRUM_PRINT
3130    cout << NF;
3131  #ifdef SPECTRUM_IOSTREAM
3132    cout << endl;
3133  #else
3134    fprintf( stdout,"\n" );
3135  #endif
3136  #endif
3137  #endif
3138
3139  // ----------------------------
3140  //  compute the spectrum of  h
3141  // ----------------------------
3142
3143  return  NF.spectrum( L,fast );
3144}
3145
3146// ----------------------------------------------------------------------------
3147//  this procedure is called from the interpreter
3148// ----------------------------------------------------------------------------
3149//  first  = polynomial
3150//  result = list of spectrum numbers
3151// ----------------------------------------------------------------------------
3152
3153BOOLEAN spectrumProc( leftv result,leftv first )
3154{
3155  spectrumState state = spectrumOK;
3156
3157  // -------------------
3158  //  check consistency
3159  // -------------------
3160
3161  //  check for a local ring
3162
3163  if( !ringIsLocal( ) )
3164  {
3165    WerrorS( "only works for local orderings" );
3166    state = spectrumWrongRing;
3167  }
3168
3169  //  no quotient rings are allowed
3170
3171  else if( currRing->qideal != NULL )
3172  {
3173    WerrorS( "does not work in quotient rings" );
3174    state = spectrumWrongRing;
3175  }
3176  else
3177  {
3178    lists   L    = (lists)NULL;
3179    int     flag = 1; // weight corner optimization is safe
3180
3181    state = spectrumCompute( (poly)first->Data( ),&L,flag );
3182
3183    if( state==spectrumOK )
3184    {
3185      result->rtyp = LIST_CMD;
3186      result->data = (char*)L;
3187    }
3188    else
3189    {
3190      spectrumPrintError(state);
3191    }
3192  }
3193
3194  return  (state!=spectrumOK);
3195}
3196
3197// ----------------------------------------------------------------------------
3198//  this procedure is called from the interpreter
3199// ----------------------------------------------------------------------------
3200//  first  = polynomial
3201//  result = list of spectrum numbers
3202// ----------------------------------------------------------------------------
3203
3204BOOLEAN spectrumfProc( leftv result,leftv first )
3205{
3206  spectrumState state = spectrumOK;
3207
3208  // -------------------
3209  //  check consistency
3210  // -------------------
3211
3212  //  check for a local polynomial ring
3213
3214  if( currRing->OrdSgn != -1 )
3215  // ?? HS: the test above is also true for k[x][[y]], k[[x]][y]
3216  // or should we use:
3217  //if( !ringIsLocal( ) )
3218  {
3219    WerrorS( "only works for local orderings" );
3220    state = spectrumWrongRing;
3221  }
3222  else if( currRing->qideal != NULL )
3223  {
3224    WerrorS( "does not work in quotient rings" );
3225    state = spectrumWrongRing;
3226  }
3227  else
3228  {
3229    lists   L    = (lists)NULL;
3230    int     flag = 2; // symmetric optimization
3231
3232    state = spectrumCompute( (poly)first->Data( ),&L,flag );
3233
3234    if( state==spectrumOK )
3235    {
3236      result->rtyp = LIST_CMD;
3237      result->data = (char*)L;
3238    }
3239    else
3240    {
3241      spectrumPrintError(state);
3242    }
3243  }
3244
3245  return  (state!=spectrumOK);
3246}
3247
3248// ----------------------------------------------------------------------------
3249//  check if a list is a spectrum
3250//  check for:
3251//      list has 6 elements
3252//      1st element is int (mu=Milnor number)
3253//      2nd element is int (pg=geometrical genus)
3254//      3rd element is int (n =number of different spectrum numbers)
3255//      4th element is intvec (num=numerators)
3256//      5th element is intvec (den=denomiantors)
3257//      6th element is intvec (mul=multiplicities)
3258//      exactly n numerators
3259//      exactly n denominators
3260//      exactly n multiplicities
3261//      mu>0
3262//      pg>=0
3263//      n>0
3264//      num>0
3265//      den>0
3266//      mul>0
3267//      symmetriy with respect to numberofvariables/2
3268//      monotony
3269//      mu = sum of all multiplicities
3270//      pg = sum of all multiplicities where num/den<=1
3271// ----------------------------------------------------------------------------
3272
3273semicState  list_is_spectrum( lists l )
3274{
3275    // -------------------
3276    //  check list length
3277    // -------------------
3278
3279    if( l->nr < 5 )
3280    {
3281        return  semicListTooShort;
3282    }
3283    else if( l->nr > 5 )
3284    {
3285        return  semicListTooLong;
3286    }
3287
3288    // -------------
3289    //  check types
3290    // -------------
3291
3292    if( l->m[0].rtyp != INT_CMD )
3293    {
3294        return  semicListFirstElementWrongType;
3295    }
3296    else if( l->m[1].rtyp != INT_CMD )
3297    {
3298        return  semicListSecondElementWrongType;
3299    }
3300    else if( l->m[2].rtyp != INT_CMD )
3301    {
3302        return  semicListThirdElementWrongType;
3303    }
3304    else if( l->m[3].rtyp != INTVEC_CMD )
3305    {
3306        return  semicListFourthElementWrongType;
3307    }
3308    else if( l->m[4].rtyp != INTVEC_CMD )
3309    {
3310        return  semicListFifthElementWrongType;
3311    }
3312    else if( l->m[5].rtyp != INTVEC_CMD )
3313    {
3314        return  semicListSixthElementWrongType;
3315    }
3316
3317    // -------------------------
3318    //  check number of entries
3319    // -------------------------
3320
3321    int     mu = (int)(long)(l->m[0].Data( ));
3322    int     pg = (int)(long)(l->m[1].Data( ));
3323    int     n  = (int)(long)(l->m[2].Data( ));
3324
3325    if( n <= 0 )
3326    {
3327        return  semicListNNegative;
3328    }
3329
3330    intvec  *num = (intvec*)l->m[3].Data( );
3331    intvec  *den = (intvec*)l->m[4].Data( );
3332    intvec  *mul = (intvec*)l->m[5].Data( );
3333
3334    if( n != num->length( ) )
3335    {
3336        return  semicListWrongNumberOfNumerators;
3337    }
3338    else if( n != den->length( ) )
3339    {
3340        return  semicListWrongNumberOfDenominators;
3341    }
3342    else if( n != mul->length( ) )
3343    {
3344        return  semicListWrongNumberOfMultiplicities;
3345    }
3346
3347    // --------
3348    //  values
3349    // --------
3350
3351    if( mu <= 0 )
3352    {
3353        return  semicListMuNegative;
3354    }
3355    if( pg < 0 )
3356    {
3357        return  semicListPgNegative;
3358    }
3359
3360    int i;
3361
3362    for( i=0; i<n; i++ )
3363    {
3364        if( (*num)[i] <= 0 )
3365        {
3366            return  semicListNumNegative;
3367        }
3368        if( (*den)[i] <= 0 )
3369        {
3370            return  semicListDenNegative;
3371        }
3372        if( (*mul)[i] <= 0 )
3373        {
3374            return  semicListMulNegative;
3375        }
3376    }
3377
3378    // ----------------
3379    //  check symmetry
3380    // ----------------
3381
3382    int     j;
3383
3384    for( i=0, j=n-1; i<=j; i++,j-- )
3385    {
3386        if( (*num)[i] != pVariables*((*den)[i]) - (*num)[j] ||
3387            (*den)[i] != (*den)[j] ||
3388            (*mul)[i] != (*mul)[j] )
3389        {
3390            return  semicListNotSymmetric;
3391        }
3392    }
3393
3394    // ----------------
3395    //  check monotony
3396    // ----------------
3397
3398    for( i=0, j=1; i<n/2; i++,j++ )
3399    {
3400        if( (*num)[i]*(*den)[j] >= (*num)[j]*(*den)[i] )
3401        {
3402            return  semicListNotMonotonous;
3403        }
3404    }
3405
3406    // ---------------------
3407    //  check Milnor number
3408    // ---------------------
3409
3410    for( mu=0, i=0; i<n; i++ )
3411    {
3412        mu += (*mul)[i];
3413    }
3414
3415    if( mu != (int)(long)(l->m[0].Data( )) )
3416    {
3417        return  semicListMilnorWrong;
3418    }
3419
3420    // -------------------------
3421    //  check geometrical genus
3422    // -------------------------
3423
3424    for( pg=0, i=0; i<n; i++ )
3425    {
3426        if( (*num)[i]<=(*den)[i] )
3427        {
3428            pg += (*mul)[i];
3429        }
3430    }
3431
3432    if( pg != (int)(long)(l->m[1].Data( )) )
3433    {
3434        return  semicListPGWrong;
3435    }
3436
3437    return  semicOK;
3438}
3439
3440// ----------------------------------------------------------------------------
3441//  this procedure is called from the interpreter
3442// ----------------------------------------------------------------------------
3443//  first  = list of spectrum numbers
3444//  second = list of spectrum numbers
3445//  result = sum of the two lists
3446// ----------------------------------------------------------------------------
3447
3448BOOLEAN spaddProc( leftv result,leftv first,leftv second )
3449{
3450    semicState  state;
3451
3452    // -----------------
3453    //  check arguments
3454    // -----------------
3455
3456    lists l1 = (lists)first->Data( );
3457    lists l2 = (lists)second->Data( );
3458
3459    if( (state=list_is_spectrum( l1 )) != semicOK )
3460    {
3461        WerrorS( "first argument is not a spectrum:" );
3462        list_error( state );
3463    }
3464    else if( (state=list_is_spectrum( l2 )) != semicOK )
3465    {
3466        WerrorS( "second argument is not a spectrum:" );
3467        list_error( state );
3468    }
3469    else
3470    {
3471        spectrum s1( l1 );
3472        spectrum s2( l2 );
3473        spectrum sum( s1+s2 );
3474
3475        result->rtyp = LIST_CMD;
3476        result->data = (char*)(sum.thelist( ));
3477    }
3478
3479    return  (state!=semicOK);
3480}
3481
3482// ----------------------------------------------------------------------------
3483//  this procedure is called from the interpreter
3484// ----------------------------------------------------------------------------
3485//  first  = list of spectrum numbers
3486//  second = integer
3487//  result = the multiple of the first list by the second factor
3488// ----------------------------------------------------------------------------
3489
3490BOOLEAN spmulProc( leftv result,leftv first,leftv second )
3491{
3492    semicState  state;
3493
3494    // -----------------
3495    //  check arguments
3496    // -----------------
3497
3498    lists   l = (lists)first->Data( );
3499    int     k = (int)(long)second->Data( );
3500
3501    if( (state=list_is_spectrum( l ))!=semicOK )
3502    {
3503        WerrorS( "first argument is not a spectrum" );
3504        list_error( state );
3505    }
3506    else if( k < 0 )
3507    {
3508        WerrorS( "second argument should be positive" );
3509        state = semicMulNegative;
3510    }
3511    else
3512    {
3513        spectrum s( l );
3514        spectrum product( k*s );
3515
3516        result->rtyp = LIST_CMD;
3517        result->data = (char*)product.thelist( );
3518    }
3519
3520    return  (state!=semicOK);
3521}
3522
3523// ----------------------------------------------------------------------------
3524//  this procedure is called from the interpreter
3525// ----------------------------------------------------------------------------
3526//  first  = list of spectrum numbers
3527//  second = list of spectrum numbers
3528//  result = semicontinuity index
3529// ----------------------------------------------------------------------------
3530
3531BOOLEAN    semicProc3   ( leftv res,leftv u,leftv v,leftv w )
3532{
3533  semicState  state;
3534  BOOLEAN qh=(((int)(long)w->Data())==1);
3535
3536  // -----------------
3537  //  check arguments
3538  // -----------------
3539
3540  lists l1 = (lists)u->Data( );
3541  lists l2 = (lists)v->Data( );
3542
3543  if( (state=list_is_spectrum( l1 ))!=semicOK )
3544  {
3545    WerrorS( "first argument is not a spectrum" );
3546    list_error( state );
3547  }
3548  else if( (state=list_is_spectrum( l2 ))!=semicOK )
3549  {
3550    WerrorS( "second argument is not a spectrum" );
3551    list_error( state );
3552  }
3553  else
3554  {
3555    spectrum s1( l1 );
3556    spectrum s2( l2 );
3557
3558    res->rtyp = INT_CMD;
3559    if (qh)
3560      res->data = (void*)(s1.mult_spectrumh( s2 ));
3561    else
3562      res->data = (void*)(s1.mult_spectrum( s2 ));
3563  }
3564
3565  // -----------------
3566  //  check status
3567  // -----------------
3568
3569  return  (state!=semicOK);
3570}
3571BOOLEAN    semicProc   ( leftv res,leftv u,leftv v )
3572{
3573  sleftv tmp;
3574  memset(&tmp,0,sizeof(tmp));
3575  tmp.rtyp=INT_CMD;
3576  /* tmp.data = (void *)0;  -- done by memset */
3577
3578  return  semicProc3(res,u,v,&tmp);
3579}
3580// from splist.cc
3581// ----------------------------------------------------------------------------
3582//  Compute the spectrum of a  spectrumPolyList
3583// ----------------------------------------------------------------------------
3584
3585spectrumState   spectrumPolyList::spectrum( lists *L,int fast )
3586{
3587    spectrumPolyNode  **node = &root;
3588    spectrumPolyNode  *search;
3589
3590    poly              f,tmp;
3591    int               found,cmp;
3592
3593    Rational smax( ( fast==0 ? 0 : pVariables ),
3594                   ( fast==2 ? 2 : 1 ) );
3595
3596    Rational weight_prev( 0,1 );
3597
3598    int     mu = 0;          // the milnor number
3599    int     pg = 0;          // the geometrical genus
3600    int     n  = 0;          // number of different spectral numbers
3601    int     z  = 0;          // number of spectral number equal to smax
3602
3603    int     k = 0;
3604
3605    while( (*node)!=(spectrumPolyNode*)NULL &&
3606           ( fast==0 || (*node)->weight<=smax ) )
3607    {
3608        // ---------------------------------------
3609        //  determine the first normal form which
3610        //  contains the monomial  node->mon
3611        // ---------------------------------------
3612
3613        found  = FALSE;
3614        search = *node;
3615
3616        while( search!=(spectrumPolyNode*)NULL && found==FALSE )
3617        {
3618            if( search->nf!=(poly)NULL )
3619            {
3620                f = search->nf;
3621
3622                do
3623                {
3624                    // --------------------------------
3625                    //  look for  (*node)->mon  in   f
3626                    // --------------------------------
3627
3628                    cmp = pCmp( (*node)->mon,f );
3629
3630                    if( cmp<0 )
3631                    {
3632                        f = pNext( f );
3633                    }
3634                    else if( cmp==0 )
3635                    {
3636                        // -----------------------------
3637                        //  we have found a normal form
3638                        // -----------------------------
3639
3640                        found = TRUE;
3641
3642                        //  normalize coefficient
3643
3644                        number inv = nInvers( pGetCoeff( f ) );
3645                        pMult_nn( search->nf,inv );
3646                        nDelete( &inv );
3647
3648                        //  exchange  normal forms
3649
3650                        tmp         = (*node)->nf;
3651                        (*node)->nf = search->nf;
3652                        search->nf  = tmp;
3653                    }
3654                }
3655                while( cmp<0 && f!=(poly)NULL );
3656            }
3657            search = search->next;
3658        }
3659
3660        if( found==FALSE )
3661        {
3662            // ------------------------------------------------
3663            //  the weight of  node->mon  is a spectrum number
3664            // ------------------------------------------------
3665
3666            mu++;
3667
3668            if( (*node)->weight<=(Rational)1 )              pg++;
3669            if( (*node)->weight==smax )           z++;
3670            if( (*node)->weight>weight_prev )     n++;
3671
3672            weight_prev = (*node)->weight;
3673            node = &((*node)->next);
3674        }
3675        else
3676        {
3677            // -----------------------------------------------
3678            //  determine all other normal form which contain
3679            //  the monomial  node->mon
3680            //  replace for  node->mon  its normal form
3681            // -----------------------------------------------
3682
3683            while( search!=(spectrumPolyNode*)NULL )
3684            {
3685                    if( search->nf!=(poly)NULL )
3686                {
3687                    f = search->nf;
3688
3689                    do
3690                    {
3691                        // --------------------------------
3692                        //  look for  (*node)->mon  in   f
3693                        // --------------------------------
3694
3695                        cmp = pCmp( (*node)->mon,f );
3696
3697                        if( cmp<0 )
3698                        {
3699                            f = pNext( f );
3700                        }
3701                        else if( cmp==0 )
3702                        {
3703                            search->nf = pSub( search->nf,
3704                                ppMult_nn( (*node)->nf,pGetCoeff( f ) ) );
3705                            pNorm( search->nf );
3706                        }
3707                    }
3708                    while( cmp<0 && f!=(poly)NULL );
3709                }
3710                search = search->next;
3711            }
3712            delete_node( node );
3713        }
3714
3715    }
3716
3717    // --------------------------------------------------------
3718    //  fast computation exploits the symmetry of the spectrum
3719    // --------------------------------------------------------
3720
3721    if( fast==2 )
3722    {
3723        mu = 2*mu - z;
3724        n  = ( z > 0 ? 2*n - 1 : 2*n );
3725    }
3726
3727    // --------------------------------------------------------
3728    //  compute the spectrum numbers with their multiplicities
3729    // --------------------------------------------------------
3730
3731    intvec            *nom  = new intvec( n );
3732    intvec            *den  = new intvec( n );
3733    intvec            *mult = new intvec( n );
3734
3735    int count         = 0;
3736    int multiplicity  = 1;
3737
3738    for( search=root; search!=(spectrumPolyNode*)NULL &&
3739                     ( fast==0 || search->weight<=smax );
3740                     search=search->next )
3741    {
3742        if( search->next==(spectrumPolyNode*)NULL ||
3743            search->weight<search->next->weight )
3744        {
3745            (*nom) [count] = search->weight.get_num_si( );
3746            (*den) [count] = search->weight.get_den_si( );
3747            (*mult)[count] = multiplicity;
3748
3749            multiplicity=1;
3750            count++;
3751        }
3752        else
3753        {
3754            multiplicity++;
3755        }
3756    }
3757
3758    // --------------------------------------------------------
3759    //  fast computation exploits the symmetry of the spectrum
3760    // --------------------------------------------------------
3761
3762    if( fast==2 )
3763    {
3764        int n1,n2;
3765        for( n1=0, n2=n-1; n1<n2; n1++, n2-- )
3766        {
3767            (*nom) [n2] = pVariables*(*den)[n1]-(*nom)[n1];
3768            (*den) [n2] = (*den)[n1];
3769            (*mult)[n2] = (*mult)[n1];
3770        }
3771    }
3772
3773    // -----------------------------------
3774    //  test if the spectrum is symmetric
3775    // -----------------------------------
3776
3777    if( fast==0 || fast==1 )
3778    {
3779        int symmetric=TRUE;
3780
3781        for( int n1=0, n2=n-1 ; n1<n2 && symmetric==TRUE; n1++, n2-- )
3782        {
3783            if( (*mult)[n1]!=(*mult)[n2] ||
3784                (*den) [n1]!= (*den)[n2] ||
3785                (*nom)[n1]+(*nom)[n2]!=pVariables*(*den) [n1] )
3786            {
3787                symmetric = FALSE;
3788            }
3789        }
3790
3791        if( symmetric==FALSE )
3792        {
3793            // ---------------------------------------------
3794            //  the spectrum is not symmetric => degenerate
3795            //  principal part
3796            // ---------------------------------------------
3797
3798            *L = (lists)omAllocBin( slists_bin);
3799            (*L)->Init( 1 );
3800            (*L)->m[0].rtyp = INT_CMD;    //  milnor number
3801            (*L)->m[0].data = (void*)mu;
3802
3803            return spectrumDegenerate;
3804        }
3805    }
3806
3807    *L = (lists)omAllocBin( slists_bin);
3808
3809    (*L)->Init( 6 );
3810
3811    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
3812    (*L)->m[1].rtyp = INT_CMD;    //  geometrical genus
3813    (*L)->m[2].rtyp = INT_CMD;    //  number of spectrum values
3814    (*L)->m[3].rtyp = INTVEC_CMD; //  nominators
3815    (*L)->m[4].rtyp = INTVEC_CMD; //  denomiantors
3816    (*L)->m[5].rtyp = INTVEC_CMD; //  multiplicities
3817
3818    (*L)->m[0].data = (void*)mu;
3819    (*L)->m[1].data = (void*)pg;
3820    (*L)->m[2].data = (void*)n;
3821    (*L)->m[3].data = (void*)nom;
3822    (*L)->m[4].data = (void*)den;
3823    (*L)->m[5].data = (void*)mult;
3824
3825    return  spectrumOK;
3826}
3827
3828#endif
3829
3830//from mpr_inout.cc
3831extern void nPrint(number n);
3832
3833BOOLEAN loNewtonP( leftv res, leftv arg1 )
3834{
3835  res->data= (void*)loNewtonPolytope( (ideal)arg1->Data() );
3836  return FALSE;
3837}
3838
3839BOOLEAN loSimplex( leftv res, leftv args )
3840{
3841  if ( !(rField_is_long_R()) )
3842  {
3843    WerrorS("Ground field not implemented!");
3844    return TRUE;
3845  }
3846
3847  simplex * LP;
3848  matrix m;
3849
3850  leftv v= args;
3851  if ( v->Typ() != MATRIX_CMD ) // 1: matrix
3852    return TRUE;
3853  else
3854    m= (matrix)(v->CopyD());
3855
3856  LP = new simplex(MATROWS(m),MATCOLS(m));
3857  LP->mapFromMatrix(m);
3858
3859  v= v->next;
3860  if ( v->Typ() != INT_CMD )    // 2: m = number of constraints
3861    return TRUE;
3862  else
3863    LP->m= (int)(long)(v->Data());
3864
3865  v= v->next;
3866  if ( v->Typ() != INT_CMD )    // 3: n = number of variables
3867    return TRUE;
3868  else
3869    LP->n= (int)(long)(v->Data());
3870
3871  v= v->next;
3872  if ( v->Typ() != INT_CMD )    // 4: m1 = number of <= constraints
3873    return TRUE;
3874  else
3875    LP->m1= (int)(long)(v->Data());
3876
3877  v= v->next;
3878  if ( v->Typ() != INT_CMD )    // 5: m2 = number of >= constraints
3879    return TRUE;
3880  else
3881    LP->m2= (int)(long)(v->Data());
3882
3883  v= v->next;
3884  if ( v->Typ() != INT_CMD )    // 6: m3 = number of == constraints
3885    return TRUE;
3886  else
3887    LP->m3= (int)(long)(v->Data());
3888
3889#ifdef mprDEBUG_PROT
3890  Print("m (constraints) %d\n",LP->m);
3891  Print("n (columns) %d\n",LP->n);
3892  Print("m1 (<=) %d\n",LP->m1);
3893  Print("m2 (>=) %d\n",LP->m2);
3894  Print("m3 (==) %d\n",LP->m3);
3895#endif
3896
3897  LP->compute();
3898
3899  lists lres= (lists)omAlloc( sizeof(slists) );
3900  lres->Init( 6 );
3901
3902  lres->m[0].rtyp= MATRIX_CMD; // output matrix
3903  lres->m[0].data=(void*)LP->mapToMatrix(m);
3904
3905  lres->m[1].rtyp= INT_CMD;   // found a solution?
3906  lres->m[1].data=(void*)LP->icase;
3907
3908  lres->m[2].rtyp= INTVEC_CMD;
3909  lres->m[2].data=(void*)LP->posvToIV();
3910
3911  lres->m[3].rtyp= INTVEC_CMD;
3912  lres->m[3].data=(void*)LP->zrovToIV();
3913
3914  lres->m[4].rtyp= INT_CMD;
3915  lres->m[4].data=(void*)LP->m;
3916
3917  lres->m[5].rtyp= INT_CMD;
3918  lres->m[5].data=(void*)LP->n;
3919
3920  res->data= (void*)lres;
3921
3922  return FALSE;
3923}
3924
3925BOOLEAN nuMPResMat( leftv res, leftv arg1, leftv arg2 )
3926{
3927  ideal gls = (ideal)(arg1->Data());
3928  int imtype= (int)(long)arg2->Data();
3929
3930  uResultant::resMatType mtype= determineMType( imtype );
3931
3932  // check input ideal ( = polynomial system )
3933  if ( mprIdealCheck( gls, arg1->Name(), mtype, true ) != mprOk )
3934  {
3935    return TRUE;
3936  }
3937
3938  uResultant *resMat= new uResultant( gls, mtype, false );
3939  if (resMat!=NULL)
3940  {
3941    res->rtyp = MODUL_CMD;
3942    res->data= (void*)resMat->accessResMat()->getMatrix();
3943    if (!errorreported) delete resMat;
3944  }
3945  return errorreported;
3946}
3947
3948BOOLEAN nuLagSolve( leftv res, leftv arg1, leftv arg2, leftv arg3 )
3949{
3950
3951  poly gls;
3952  gls= (poly)(arg1->Data());
3953  int howclean= (int)(long)arg3->Data();
3954
3955  if ( !(rField_is_R() ||
3956         rField_is_Q() ||
3957         rField_is_long_R() ||
3958         rField_is_long_C()) )
3959  {
3960    WerrorS("Ground field not implemented!");
3961    return TRUE;
3962  }
3963
3964  if ( !(rField_is_R()||rField_is_long_R()||rField_is_long_C()) )
3965  {
3966    unsigned long int ii = (unsigned long int)arg2->Data();
3967    setGMPFloatDigits( ii, ii );
3968  }
3969
3970  if ( gls == NULL || pIsConstant( gls ) )
3971  {
3972    WerrorS("Input polynomial is constant!");
3973    return TRUE;
3974  }
3975
3976  int ldummy;
3977  int deg= pLDeg( gls, &ldummy, currRing );
3978  //  int deg= pDeg( gls );
3979  int len= pLength( gls );
3980  int i,vpos=0;
3981  poly piter;
3982  lists elist;
3983  lists rlist;
3984
3985  elist= (lists)omAlloc( sizeof(slists) );
3986  elist->Init( 0 );
3987
3988  if ( pVariables > 1 )
3989  {
3990    piter= gls;
3991    for ( i= 1; i <= pVariables; i++ )
3992      if ( pGetExp( piter, i ) )
3993      {
3994        vpos= i;
3995        break;
3996      }
3997    while ( piter )
3998    {
3999      for ( i= 1; i <= pVariables; i++ )
4000        if ( (vpos != i) && (pGetExp( piter, i ) != 0) )
4001        {
4002          WerrorS("The input polynomial must be univariate!");
4003          return TRUE;
4004        }
4005      pIter( piter );
4006    }
4007  }
4008
4009  rootContainer * roots= new rootContainer();
4010  number * pcoeffs= (number *)omAlloc( (deg+1) * sizeof( number ) );
4011  piter= gls;
4012  for ( i= deg; i >= 0; i-- )
4013  {
4014    //if ( piter ) Print("deg %d, pDeg(piter) %d\n",i,pTotaldegree(piter));
4015    if ( piter && pTotaldegree(piter) == i )
4016    {
4017      pcoeffs[i]= nCopy( pGetCoeff( piter ) );
4018      //nPrint( pcoeffs[i] );PrintS("  ");
4019      pIter( piter );
4020    }
4021    else
4022    {
4023      pcoeffs[i]= nInit(0);
4024    }
4025  }
4026
4027#ifdef mprDEBUG_PROT
4028  for (i=deg; i >= 0; i--)
4029  {
4030    nPrint( pcoeffs[i] );PrintS("  ");
4031  }
4032  PrintLn();
4033#endif
4034
4035  roots->fillContainer( pcoeffs, NULL, 1, deg, rootContainer::onepoly, 1 );
4036  roots->solver( howclean );
4037
4038  int elem= roots->getAnzRoots();
4039  char *out;
4040  char *dummy;
4041  int j;
4042
4043  rlist= (lists)omAlloc( sizeof(slists) );
4044  rlist->Init( elem );
4045
4046  if (rField_is_long_C())
4047  {
4048    for ( j= 0; j < elem; j++ )
4049    {
4050      rlist->m[j].rtyp=NUMBER_CMD;
4051      rlist->m[j].data=(void *)nCopy((number)(roots->getRoot(j)));
4052      //rlist->m[j].data=(void *)(number)(roots->getRoot(j));
4053    }
4054  }
4055  else
4056  {
4057    for ( j= 0; j < elem; j++ )
4058    {
4059      dummy = complexToStr( (*roots)[j], gmp_output_digits );
4060      rlist->m[j].rtyp=STRING_CMD;
4061      rlist->m[j].data=(void *)dummy;
4062    }
4063  }
4064
4065  elist->Clean();
4066  //omFreeSize( (ADDRESS) elist, sizeof(slists) );
4067
4068  // this is (via fillContainer) the same data as in root
4069  //for ( i= deg; i >= 0; i-- ) nDelete( &pcoeffs[i] );
4070  //omFreeSize( (ADDRESS) pcoeffs, (deg+1) * sizeof( number ) );
4071
4072  delete roots;
4073
4074  res->rtyp= LIST_CMD;
4075  res->data= (void*)rlist;
4076
4077  return FALSE;
4078}
4079
4080BOOLEAN nuVanderSys( leftv res, leftv arg1, leftv arg2, leftv arg3)
4081{
4082  int i;
4083  ideal p,w;
4084  p= (ideal)arg1->Data();
4085  w= (ideal)arg2->Data();
4086
4087  // w[0] = f(p^0)
4088  // w[1] = f(p^1)
4089  // ...
4090  // p can be a vector of numbers (multivariate polynom)
4091  //   or one number (univariate polynom)
4092  // tdg = deg(f)
4093
4094  int n= IDELEMS( p );
4095  int m= IDELEMS( w );
4096  int tdg= (int)(long)arg3->Data();
4097
4098  res->data= (void*)NULL;
4099
4100  // check the input
4101  if ( tdg < 1 )
4102  {
4103    WerrorS("Last input parameter must be > 0!");
4104    return TRUE;
4105  }
4106  if ( n != pVariables )
4107  {
4108    Werror("Size of first input ideal must be equal to %d!",pVariables);
4109    return TRUE;
4110  }
4111  if ( m != (int)pow((double)tdg+1,(double)n) )
4112  {
4113    Werror("Size of second input ideal must be equal to %d!",
4114      (int)pow((double)tdg+1,(double)n));
4115    return TRUE;
4116  }
4117  if ( !(rField_is_Q() /* ||
4118         rField_is_R() || rField_is_long_R() ||
4119         rField_is_long_C()*/ ) )
4120         {
4121    WerrorS("Ground field not implemented!");
4122    return TRUE;
4123  }
4124
4125  number tmp;
4126  number *pevpoint= (number *)omAlloc( n * sizeof( number ) );
4127  for ( i= 0; i < n; i++ )
4128  {
4129    pevpoint[i]=nInit(0);
4130    if (  (p->m)[i] )
4131    {
4132      tmp = pGetCoeff( (p->m)[i] );
4133      if ( nIsZero(tmp) || nIsOne(tmp) || nIsMOne(tmp) )
4134      {
4135        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
4136        WerrorS("Elements of first input ideal must not be equal to -1, 0, 1!");
4137        return TRUE;
4138      }
4139    } else tmp= NULL;
4140    if ( !nIsZero(tmp) )
4141    {
4142      if ( !pIsConstant((p->m)[i]))
4143      {
4144        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
4145        WerrorS("Elements of first input ideal must be numbers!");
4146        return TRUE;
4147      }
4148      pevpoint[i]= nCopy( tmp );
4149    }
4150  }
4151
4152  number *wresults= (number *)omAlloc( m * sizeof( number ) );
4153  for ( i= 0; i < m; i++ )
4154  {
4155    wresults[i]= nInit(0);
4156    if ( (w->m)[i] && !nIsZero(pGetCoeff((w->m)[i])) )
4157    {
4158      if ( !pIsConstant((w->m)[i]))
4159      {
4160        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
4161        omFreeSize( (ADDRESS)wresults, m * sizeof( number ) );
4162        WerrorS("Elements of second input ideal must be numbers!");
4163        return TRUE;
4164      }
4165      wresults[i]= nCopy(pGetCoeff((w->m)[i]));
4166    }
4167  }
4168
4169  vandermonde vm( m, n, tdg, pevpoint, FALSE );
4170  number *ncpoly= vm.interpolateDense( wresults );
4171  // do not free ncpoly[]!!
4172  poly rpoly= vm.numvec2poly( ncpoly );
4173
4174  omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
4175  omFreeSize( (ADDRESS)wresults, m * sizeof( number ) );
4176
4177  res->data= (void*)rpoly;
4178  return FALSE;
4179}
4180
4181BOOLEAN nuUResSolve( leftv res, leftv args )
4182{
4183  leftv v= args;
4184
4185  ideal gls;
4186  int imtype;
4187  int howclean;
4188
4189  // get ideal
4190  if ( v->Typ() != IDEAL_CMD )
4191    return TRUE;
4192  else gls= (ideal)(v->Data());
4193  v= v->next;
4194
4195  // get resultant matrix type to use (0,1)
4196  if ( v->Typ() != INT_CMD )
4197    return TRUE;
4198  else imtype= (int)(long)v->Data();
4199  v= v->next;
4200
4201  if (imtype==0)
4202  {
4203    ideal test_id=idInit(1,1);
4204    int j;
4205    for(j=IDELEMS(gls)-1;j>=0;j--)
4206    {
4207      if (gls->m[j]!=NULL)
4208      {
4209        test_id->m[0]=gls->m[j];
4210        intvec *dummy_w=idQHomWeight(test_id);
4211        if (dummy_w!=NULL)
4212        {
4213          WerrorS("Newton polytope not of expected dimension");
4214          delete dummy_w;
4215          return TRUE;
4216        }
4217      }
4218    }
4219  }
4220
4221  // get and set precision in digits ( > 0 )
4222  if ( v->Typ() != INT_CMD )
4223    return TRUE;
4224  else if ( !(rField_is_R()||rField_is_long_R()||rField_is_long_C()) )
4225  {
4226    unsigned long int ii=(unsigned long int)v->Data();
4227    setGMPFloatDigits( ii, ii );
4228  }
4229  v= v->next;
4230
4231  // get interpolation steps (0,1,2)
4232  if ( v->Typ() != INT_CMD )
4233    return TRUE;
4234  else howclean= (int)(long)v->Data();
4235
4236  uResultant::resMatType mtype= determineMType( imtype );
4237  int i,c,count;
4238  lists listofroots= NULL;
4239  lists emptylist;
4240  number smv= NULL;
4241  BOOLEAN interpolate_det= (mtype==uResultant::denseResMat)?TRUE:FALSE;
4242
4243  //emptylist= (lists)omAlloc( sizeof(slists) );
4244  //emptylist->Init( 0 );
4245
4246  //res->rtyp = LIST_CMD;
4247  //res->data= (void *)emptylist;
4248
4249  // check input ideal ( = polynomial system )
4250  if ( mprIdealCheck( gls, args->Name(), mtype ) != mprOk )
4251  {
4252    return TRUE;
4253  }
4254
4255  uResultant * ures;
4256  rootContainer ** iproots;
4257  rootContainer ** muiproots;
4258  rootArranger * arranger;
4259
4260  // main task 1: setup of resultant matrix
4261  ures= new uResultant( gls, mtype );
4262  if ( ures->accessResMat()->initState() != resMatrixBase::ready )
4263  {
4264    WerrorS("Error occurred during matrix setup!");
4265    return TRUE;
4266  }
4267
4268  // if dense resultant, check if minor nonsingular
4269  if ( mtype == uResultant::denseResMat )
4270  {
4271    smv= ures->accessResMat()->getSubDet();
4272#ifdef mprDEBUG_PROT
4273    PrintS("// Determinant of submatrix: ");nPrint(smv);PrintLn();
4274#endif
4275    if ( nIsZero(smv) )
4276    {
4277      WerrorS("Unsuitable input ideal: Minor of resultant matrix is singular!");
4278      return TRUE;
4279    }
4280  }
4281
4282  // main task 2: Interpolate specialized resultant polynomials
4283  if ( interpolate_det )
4284    iproots= ures->interpolateDenseSP( false, smv );
4285  else
4286    iproots= ures->specializeInU( false, smv );
4287
4288  // main task 3: Interpolate specialized resultant polynomials
4289  if ( interpolate_det )
4290    muiproots= ures->interpolateDenseSP( true, smv );
4291  else
4292    muiproots= ures->specializeInU( true, smv );
4293
4294#ifdef mprDEBUG_PROT
4295  c= iproots[0]->getAnzElems();
4296  for (i=0; i < c; i++) pWrite(iproots[i]->getPoly());
4297  c= muiproots[0]->getAnzElems();
4298  for (i=0; i < c; i++) pWrite(muiproots[i]->getPoly());
4299#endif
4300
4301  // main task 4: Compute roots of specialized polys and match them up
4302  arranger= new rootArranger( iproots, muiproots, howclean );
4303  arranger->solve_all();
4304
4305  // get list of roots
4306  if ( arranger->success() )
4307  {
4308    arranger->arrange();
4309    listofroots= arranger->listOfRoots( gmp_output_digits );
4310  }
4311  else
4312  {
4313    WerrorS("Solver was unable to find any roots!");
4314    return TRUE;
4315  }
4316
4317  // free everything
4318  count= iproots[0]->getAnzElems();
4319  for (i=0; i < count; i++) delete iproots[i];
4320  omFreeSize( (ADDRESS) iproots, count * sizeof(rootContainer*) );
4321  count= muiproots[0]->getAnzElems();
4322  for (i=0; i < count; i++) delete muiproots[i];
4323  omFreeSize( (ADDRESS) muiproots, count * sizeof(rootContainer*) );
4324
4325  delete ures;
4326  delete arranger;
4327  nDelete( &smv );
4328
4329  res->data= (void *)listofroots;
4330
4331  //emptylist->Clean();
4332  //  omFreeSize( (ADDRESS) emptylist, sizeof(slists) );
4333
4334  return FALSE;
4335}
4336
4337// from mpr_numeric.cc
4338lists rootArranger::listOfRoots( const unsigned int oprec )
4339{
4340  int i,j,tr;
4341  int count= roots[0]->getAnzRoots(); // number of roots
4342  int elem= roots[0]->getAnzElems();  // number of koordinates per root
4343
4344  lists listofroots= (lists)omAlloc( sizeof(slists) ); // must be done this way!
4345
4346  if ( found_roots )
4347  {
4348    listofroots->Init( count );
4349
4350    for (i=0; i < count; i++)
4351    {
4352      lists onepoint= (lists)omAlloc(sizeof(slists)); // must be done this way!
4353      onepoint->Init(elem);
4354      for ( j= 0; j < elem; j++ )
4355      {
4356        if ( !rField_is_long_C() )
4357        {
4358          onepoint->m[j].rtyp=STRING_CMD;
4359          onepoint->m[j].data=(void *)complexToStr((*roots[j])[i],oprec);
4360        }
4361        else
4362        {
4363          onepoint->m[j].rtyp=NUMBER_CMD;
4364          onepoint->m[j].data=(void *)nCopy((number)(roots[j]->getRoot(i)));
4365        }
4366        onepoint->m[j].next= NULL;
4367        onepoint->m[j].name= NULL;
4368      }
4369      listofroots->m[i].rtyp=LIST_CMD;
4370      listofroots->m[i].data=(void *)onepoint;
4371      listofroots->m[j].next= NULL;
4372      listofroots->m[j].name= NULL;
4373    }
4374
4375  }
4376  else
4377  {
4378    listofroots->Init( 0 );
4379  }
4380
4381  return listofroots;
4382}
4383
4384// from ring.cc
4385void rSetHdl(idhdl h)
4386{
4387  int i;
4388  ring rg = NULL;
4389  if (h!=NULL)
4390  {
4391//   Print(" new ring:%s (l:%d)\n",IDID(h),IDLEV(h));
4392    rg = IDRING(h);
4393    if (rg==NULL) return; //id <>NULL, ring==NULL
4394    omCheckAddrSize((ADDRESS)h,sizeof(idrec));
4395    if (IDID(h))  // OB: ????
4396      omCheckAddr((ADDRESS)IDID(h));
4397    rTest(rg);
4398  }
4399
4400  // clean up history
4401  if (sLastPrinted.RingDependend())
4402  {
4403    sLastPrinted.CleanUp();
4404    memset(&sLastPrinted,0,sizeof(sleftv));
4405  }
4406
4407  // test for valid "currRing":
4408  if ((rg!=NULL) && (rg->idroot==NULL))
4409  {
4410    ring old=rg;
4411    rg=rAssure_HasComp(rg);
4412    if (old!=rg)
4413    {
4414      rKill(old);
4415      IDRING(h)=rg;
4416    }
4417  }
4418   /*------------ change the global ring -----------------------*/
4419  rChangeCurrRing(rg);
4420  currRingHdl = h;
4421}
4422
4423BOOLEAN rSleftvOrdering2Ordering(sleftv *ord, ring R)
4424{
4425  int last = 0, o=0, n = 1, i=0, typ = 1, j;
4426  sleftv *sl = ord;
4427
4428  // determine nBlocks
4429  while (sl!=NULL)
4430  {
4431    intvec *iv = (intvec *)(sl->data);
4432    if (((*iv)[1]==ringorder_c)||((*iv)[1]==ringorder_C))
4433      i++;
4434    else if ((*iv)[1]==ringorder_L)
4435    {
4436      R->bitmask=(*iv)[2];
4437      n--;
4438    }
4439    else if (((*iv)[1]!=ringorder_a)
4440    && ((*iv)[1]!=ringorder_a64))
4441      o++;
4442    n++;
4443    sl=sl->next;
4444  }
4445  // check whether at least one real ordering
4446  if (o==0)
4447  {
4448    WerrorS("invalid combination of orderings");
4449    return TRUE;
4450  }
4451  // if no c/C ordering is given, increment n
4452  if (i==0) n++;
4453  else if (i != 1)
4454  {
4455    // throw error if more than one is given
4456    WerrorS("more than one ordering c/C specified");
4457    return TRUE;
4458  }
4459
4460  // initialize fields of R
4461  R->order=(int *)omAlloc0(n*sizeof(int));
4462  R->block0=(int *)omAlloc0(n*sizeof(int));
4463  R->block1=(int *)omAlloc0(n*sizeof(int));
4464  R->wvhdl=(int**)omAlloc0(n*sizeof(int_ptr));
4465
4466  int *weights=(int*)omAlloc0((R->N+1)*sizeof(int));
4467
4468  // init order, so that rBlocks works correctly
4469  for (j=0; j < n-1; j++)
4470    R->order[j] = (int) ringorder_unspec;
4471  // set last _C order, if no c/C order was given
4472  if (i == 0) R->order[n-2] = ringorder_C;
4473
4474  /* init orders */
4475  sl=ord;
4476  n=-1;
4477  while (sl!=NULL)
4478  {
4479    intvec *iv;
4480    iv = (intvec *)(sl->data);
4481    if ((*iv)[1]!=ringorder_L)
4482    {
4483      n++;
4484
4485      /* the format of an ordering:
4486       *  iv[0]: factor
4487       *  iv[1]: ordering
4488       *  iv[2..end]: weights
4489       */
4490      R->order[n] = (*iv)[1];
4491      typ=1;
4492      switch ((*iv)[1])
4493      {
4494          case ringorder_ws:
4495          case ringorder_Ws:
4496            typ=-1;
4497          case ringorder_wp:
4498          case ringorder_Wp:
4499            R->wvhdl[n]=(int*)omAlloc((iv->length()-1)*sizeof(int));
4500            R->block0[n] = last+1;
4501            for (i=2; i<iv->length(); i++)
4502            {
4503              R->wvhdl[n][i-2] = (*iv)[i];
4504              last++;
4505              if (weights[last]==0) weights[last]=(*iv)[i]*typ;
4506            }
4507            R->block1[n] = last;
4508            break;
4509          case ringorder_ls:
4510          case ringorder_ds:
4511          case ringorder_Ds:
4512          case ringorder_rs:
4513            typ=-1;
4514          case ringorder_lp:
4515          case ringorder_dp:
4516          case ringorder_Dp:
4517          case ringorder_rp:
4518            R->block0[n] = last+1;
4519            if (iv->length() == 3) last+=(*iv)[2];
4520            else last += (*iv)[0];
4521            R->block1[n] = last;
4522            //if ((R->block0[n]>R->block1[n])
4523            //|| (R->block1[n]>rVar(R)))
4524            //{
4525            //  R->block1[n]=rVar(R);
4526            //  //WerrorS("ordering larger than number of variables");
4527            //  break;
4528            //}
4529            if (rCheckIV(iv)) return TRUE;
4530            for(i=si_min(rVar(R),R->block1[n]);i>=R->block0[n];i--)
4531            {
4532              if (weights[i]==0) weights[i]=typ;
4533            }
4534            break;
4535          case ringorder_S:
4536          case ringorder_c:
4537          case ringorder_C:
4538            if (rCheckIV(iv)) return TRUE;
4539            break;
4540          case ringorder_aa:
4541          case ringorder_a:
4542            R->block0[n] = last+1;
4543            R->block1[n] = si_min(last+iv->length()-2 , rVar(R));
4544            R->wvhdl[n] = (int*)omAlloc((iv->length()-1)*sizeof(int));
4545            for (i=2; i<iv->length(); i++)
4546            {
4547              R->wvhdl[n][i-2]=(*iv)[i];
4548              last++;
4549              if (weights[last]==0) weights[last]=(*iv)[i]*typ;
4550            }
4551            last=R->block0[n]-1;
4552            break;
4553          case ringorder_a64:
4554          {
4555            R->block0[n] = last+1;
4556            R->block1[n] = si_min(last+iv->length()-2 , rVar(R));
4557            R->wvhdl[n] = (int*)omAlloc((iv->length()-1)*sizeof(int64));
4558            int64 *w=(int64 *)R->wvhdl[n];
4559            for (i=2; i<iv->length(); i++)
4560            {
4561              w[i-2]=(*iv)[i];
4562              last++;
4563              if (weights[last]==0) weights[last]=(*iv)[i]*typ;
4564            }
4565            last=R->block0[n]-1;
4566            break;
4567          }
4568          case ringorder_M:
4569          {
4570            int Mtyp=rTypeOfMatrixOrder(iv);
4571            if (Mtyp==0) return TRUE;
4572            if (Mtyp==-1) typ = -1;
4573
4574            R->wvhdl[n] =( int *)omAlloc((iv->length()-1)*sizeof(int));
4575            for (i=2; i<iv->length();i++)
4576              R->wvhdl[n][i-2]=(*iv)[i];
4577
4578            R->block0[n] = last+1;
4579            last += (int)sqrt((double)(iv->length()-2));
4580            R->block1[n] = last;
4581            for(i=si_min(rVar(R),R->block1[n]);i>=R->block0[n];i--)
4582            {
4583              if (weights[i]==0) weights[i]=typ;
4584            }
4585            break;
4586          }
4587
4588          case ringorder_no:
4589            R->order[n] = ringorder_unspec;
4590            return TRUE;
4591
4592          default:
4593            Werror("Internal Error: Unknown ordering %d", (*iv)[1]);
4594            R->order[n] = ringorder_unspec;
4595            return TRUE;
4596      }
4597    }
4598    sl=sl->next;
4599  }
4600
4601  // check for complete coverage
4602  if ((R->order[n]==ringorder_c) ||  (R->order[n]==ringorder_C)) n--;
4603  if (R->block1[n] != R->N)
4604  {
4605    if (((R->order[n]==ringorder_dp) ||
4606         (R->order[n]==ringorder_ds) ||
4607         (R->order[n]==ringorder_Dp) ||
4608         (R->order[n]==ringorder_Ds) ||
4609         (R->order[n]==ringorder_rp) ||
4610         (R->order[n]==ringorder_rs) ||
4611         (R->order[n]==ringorder_lp) ||
4612         (R->order[n]==ringorder_ls))
4613        &&
4614        R->block0[n] <= R->N)
4615    {
4616      R->block1[n] = R->N;
4617    }
4618    else
4619    {
4620      Werror("mismatch of number of vars (%d) and ordering (%d vars)",
4621             R->N,R->block1[n]);
4622      return TRUE;
4623    }
4624  }
4625  // find OrdSgn:
4626  R->OrdSgn = 1;
4627  for(i=1;i<=R->N;i++)
4628  { if (weights[i]<0) { R->OrdSgn=-1;break; }}
4629  omFree(weights);
4630  return FALSE;
4631}
4632
4633BOOLEAN rSleftvList2StringArray(sleftv* sl, char** p)
4634{
4635
4636  while(sl!=NULL)
4637  {
4638    if (sl->Name() == sNoName)
4639    {
4640      if (sl->Typ()==POLY_CMD)
4641      {
4642        sleftv s_sl;
4643        iiConvert(POLY_CMD,ANY_TYPE,-1,sl,&s_sl);
4644        if (s_sl.Name() != sNoName)
4645          *p = omStrDup(s_sl.Name());
4646        else
4647          *p = NULL;
4648        sl->next = s_sl.next;
4649        s_sl.next = NULL;
4650        s_sl.CleanUp();
4651        if (*p == NULL) return TRUE;
4652      }
4653      else
4654        return TRUE;
4655    }
4656    else
4657      *p = omStrDup(sl->Name());
4658    p++;
4659    sl=sl->next;
4660  }
4661  return FALSE;
4662}
4663
4664////////////////////
4665//
4666// rInit itself:
4667//
4668// INPUT:  s: name, pn: ch & parameter (names), rv: variable (names)
4669//         ord: ordering
4670// RETURN: currRingHdl on success
4671//         NULL        on error
4672// NOTE:   * makes new ring to current ring, on success
4673//         * considers input sleftv's as read-only
4674//idhdl rInit(char *s, sleftv* pn, sleftv* rv, sleftv* ord)
4675ring rInit(sleftv* pn, sleftv* rv, sleftv* ord)
4676{
4677  int ch;
4678#ifdef HAVE_RINGS
4679  unsigned int ringtype = 0;
4680  int_number ringflaga = NULL;
4681  unsigned int ringflagb = 1;
4682#endif
4683  int float_len=0;
4684  int float_len2=0;
4685  ring R = NULL;
4686  idhdl tmp = NULL;
4687  BOOLEAN ffChar=FALSE;
4688  int typ = 1;
4689
4690  /* ch -------------------------------------------------------*/
4691  // get ch of ground field
4692  int numberOfAllocatedBlocks;
4693
4694  if (pn->Typ()==INT_CMD)
4695  {
4696    ch=(int)(long)pn->Data();
4697  }
4698  else if ((pn->name != NULL)
4699  && ((strcmp(pn->name,"real")==0) || (strcmp(pn->name,"complex")==0)))
4700  {
4701    BOOLEAN complex_flag=(strcmp(pn->name,"complex")==0);
4702    ch=-1;
4703    if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4704    {
4705      float_len=(int)(long)pn->next->Data();
4706      float_len2=float_len;
4707      pn=pn->next;
4708      if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4709      {
4710        float_len2=(int)(long)pn->next->Data();
4711        pn=pn->next;
4712      }
4713    }
4714    if ((pn->next==NULL) && complex_flag)
4715    {
4716      pn->next=(leftv)omAlloc0Bin(sleftv_bin);
4717      pn->next->name=omStrDup("i");
4718    }
4719  }
4720#ifdef HAVE_RINGS
4721  else if ((pn->name != NULL) && (strcmp(pn->name, "integer") == 0))
4722  {
4723    ringflaga = (int_number) omAlloc(sizeof(mpz_t));
4724    mpz_init_set_si(ringflaga, 0);
4725    if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4726    {
4727      mpz_set_ui(ringflaga, (int)(long) pn->next->Data());
4728      pn=pn->next;
4729      if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4730      {
4731        ringflagb = (long) pn->next->Data();
4732        pn=pn->next;
4733      }
4734      while ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4735      {
4736        mpz_mul_ui(ringflaga, ringflaga, (int)(long) pn->next->Data());
4737        pn=pn->next;
4738      }
4739    }
4740    if ((mpz_cmp_ui(ringflaga, 1) == 0) && (mpz_cmp_ui(ringflaga, 0) < 0))
4741    {
4742      Werror("Wrong ground ring specification (module is 1)");
4743      goto rInitError;
4744    }
4745    if (ringflagb < 1)
4746    {
4747      Werror("Wrong ground ring specification (exponent smaller than 1");
4748      goto rInitError;
4749    }
4750    // module is 0 ---> integers
4751    if (mpz_cmp_ui(ringflaga, 0) == 0)
4752    {
4753      ch = 0;
4754      ringtype = 4;
4755    }
4756    // we have an exponent
4757    else if (ringflagb > 1)
4758    {
4759      ch = ringflagb;
4760      if ((mpz_cmp_ui(ringflaga, 2) == 0) && (ringflagb + 2 <= 8*sizeof(NATNUMBER)))
4761      {
4762        ringtype = 1;       // Use Z/2^ch
4763      }
4764      else
4765      {
4766        ringtype = 3;
4767      }
4768    }
4769    // just a module m > 1
4770    else
4771    {
4772      ringtype = 2;
4773      ch = mpz_get_ui(ringflaga);
4774    }
4775  }
4776#endif
4777  else
4778  {
4779    Werror("Wrong ground field specification");
4780    goto rInitError;
4781  }
4782  pn=pn->next;
4783
4784#ifdef HAVE_RINGS
4785  if (ringtype > 0)
4786  {
4787    WarnS("You are using coefficient rings which are not fields.");
4788    WarnS("Please note that only limited functionality is available");
4789    WarnS("for these coefficients.");
4790    WarnS("");
4791    WarnS("The following commands are meant to work:");
4792    WarnS("- basic polynomial arithmetic");
4793    WarnS("- std");
4794    WarnS("- syz");
4795    WarnS("- lift");
4796    WarnS("- reduce");
4797  }
4798#endif
4799
4800  int l, last;
4801  sleftv * sl;
4802  /*every entry in the new ring is initialized to 0*/
4803
4804  /* characteristic -----------------------------------------------*/
4805  /* input: 0 ch=0 : Q     parameter=NULL    ffChar=FALSE   float_len
4806   *         0    1 : Q(a,...)        *names         FALSE
4807   *         0   -1 : R               NULL           FALSE  0
4808   *         0   -1 : R               NULL           FALSE  prec. >6
4809   *         0   -1 : C               *names         FALSE  prec. 0..?
4810   *         p    p : Fp              NULL           FALSE
4811   *         p   -p : Fp(a)           *names         FALSE
4812   *         q    q : GF(q=p^n)       *names         TRUE
4813  */
4814  if ((ch!=-1)
4815#ifdef HAVE_RINGS
4816       && (ringtype == 0)
4817#endif
4818     )
4819  {
4820    int l = 0;
4821
4822    if (((ch!=0) && (ch<2))
4823    #ifndef NV_OPS
4824    || (ch > 32003)
4825    #endif
4826    )
4827    {
4828      Warn("%d is invalid characteristic of ground field. 32003 is used.", ch);
4829      ch=32003;
4830    }
4831    // load fftable, if necessary
4832    if (pn!=NULL)
4833    {
4834      while ((ch!=fftable[l]) && (fftable[l])) l++;
4835      if (fftable[l]==0) ch = IsPrime(ch);
4836      else
4837      {
4838        char *m[1]={(char *)sNoName};
4839        nfSetChar(ch,m);
4840        if (errorreported) goto rInitError;
4841        else ffChar=TRUE;
4842      }
4843    }
4844    else
4845    {
4846      ch = IsPrime(ch);
4847    }
4848  }
4849  // allocated ring and set ch
4850  R = (ring) omAlloc0Bin(sip_sring_bin);
4851  R->ch = ch;
4852#ifdef HAVE_RINGS
4853  R->ringtype = ringtype;
4854  R->ringflaga = ringflaga;
4855  R->ringflagb = ringflagb;
4856#endif
4857  if (ch == -1)
4858  {
4859    R->float_len= si_min(float_len,32767);
4860    R->float_len2= si_min(float_len2,32767);
4861  }
4862
4863  /* parameter -------------------------------------------------------*/
4864  if (pn!=NULL)
4865  {
4866    R->P=pn->listLength();
4867    //if ((ffChar|| (ch == 1)) && (R->P > 1))
4868    if ((R->P > 1) && (ffChar || (ch == -1)))
4869    {
4870      WerrorS("too many parameters");
4871      goto rInitError;
4872    }
4873    R->parameter=(char**)omAlloc0(R->P*sizeof(char_ptr));
4874    if (rSleftvList2StringArray(pn, R->parameter))
4875    {
4876      WerrorS("parameter expected");
4877      goto rInitError;
4878    }
4879    if (ch>1 && !ffChar) R->ch=-ch;
4880    else if (ch==0) R->ch=1;
4881  }
4882  else if (ffChar)
4883  {
4884    WerrorS("need one parameter");
4885    goto rInitError;
4886  }
4887  /* post-processing of field description */
4888  // we have short reals, but no short complex
4889  if ((R->ch == - 1)
4890  && (R->parameter !=NULL)
4891  && (R->float_len < SHORT_REAL_LENGTH))
4892  {
4893    R->float_len = SHORT_REAL_LENGTH;
4894    R->float_len2 = SHORT_REAL_LENGTH;
4895  }
4896
4897  /* names and number of variables-------------------------------------*/
4898  {
4899    int l=rv->listLength();
4900#if SIZEOF_SHORT == 2
4901#define MAX_SHORT 0x7fff
4902#endif
4903    if (l>MAX_SHORT)
4904    {
4905      Werror("too many ring variables(%d), max is %d",l,MAX_SHORT);
4906       goto rInitError;
4907    }
4908    R->N = l; /*rv->listLength();*/
4909  }
4910  R->names   = (char **)omAlloc0(R->N * sizeof(char_ptr));
4911  if (rSleftvList2StringArray(rv, R->names))
4912  {
4913    WerrorS("name of ring variable expected");
4914    goto rInitError;
4915  }
4916
4917  /* check names and parameters for conflicts ------------------------- */
4918  rRenameVars(R); // conflicting variables will be renamed
4919  /* ordering -------------------------------------------------------------*/
4920  if (rSleftvOrdering2Ordering(ord, R))
4921    goto rInitError;
4922
4923  // Complete the initialization
4924  if (rComplete(R,1))
4925    goto rInitError;
4926
4927  rTest(R);
4928
4929  // try to enter the ring into the name list
4930  // need to clean up sleftv here, before this ring can be set to
4931  // new currRing or currRing can be killed beacuse new ring has
4932  // same name
4933  if (pn != NULL) pn->CleanUp();
4934  if (rv != NULL) rv->CleanUp();
4935  if (ord != NULL) ord->CleanUp();
4936  //if ((tmp = enterid(s, myynest, RING_CMD, &IDROOT))==NULL)
4937  //  goto rInitError;
4938
4939  //memcpy(IDRING(tmp),R,sizeof(*R));
4940  // set current ring
4941  //omFreeBin(R,  ip_sring_bin);
4942  //return tmp;
4943  return R;
4944
4945  // error case:
4946  rInitError:
4947  if  (R != NULL) rDelete(R);
4948  if (pn != NULL) pn->CleanUp();
4949  if (rv != NULL) rv->CleanUp();
4950  if (ord != NULL) ord->CleanUp();
4951  return NULL;
4952}
4953
4954ring rSubring(ring org_ring, sleftv* rv)
4955{
4956  ring R = rCopy0(org_ring);
4957  int *perm=(int *)omAlloc0((org_ring->N+1)*sizeof(int));
4958  int last = 0, o=0, n = rBlocks(org_ring), i=0, typ = 1, j;
4959
4960  /* names and number of variables-------------------------------------*/
4961  {
4962    int l=rv->listLength();
4963    if (l>MAX_SHORT)
4964    {
4965      Werror("too many ring variables(%d), max is %d",l,MAX_SHORT);
4966       goto rInitError;
4967    }
4968    R->N = l; /*rv->listLength();*/
4969  }
4970  omFree(R->names);
4971  R->names   = (char **)omAlloc0(R->N * sizeof(char_ptr));
4972  if (rSleftvList2StringArray(rv, R->names))
4973  {
4974    WerrorS("name of ring variable expected");
4975    goto rInitError;
4976  }
4977
4978  /* check names for subring in org_ring ------------------------- */
4979  {
4980    i=0;
4981
4982    for(j=0;j<R->N;j++)
4983    {
4984      for(;i<org_ring->N;i++)
4985      {
4986        if (strcmp(org_ring->names[i],R->names[j])==0)
4987        {
4988          perm[i+1]=j+1;
4989          break;
4990        }
4991      }
4992      if (i>org_ring->N)
4993      {
4994        Werror("variable %d (%s) not in basering",j+1,R->names[j]);
4995        break;
4996      }
4997    }
4998  }
4999  //Print("perm=");
5000  //for(i=1;i<org_ring->N;i++) Print("v%d -> v%d\n",i,perm[i]);
5001  /* ordering -------------------------------------------------------------*/
5002
5003  for(i=0;i<n;i++)
5004  {
5005    int min_var=-1;
5006    int max_var=-1;
5007    for(j=R->block0[i];j<=R->block1[i];j++)
5008    {
5009      if (perm[j]>0)
5010      {
5011        if (min_var==-1) min_var=perm[j];
5012        max_var=perm[j];
5013      }
5014    }
5015    if (min_var!=-1)
5016    {
5017      //Print("block %d: old %d..%d, now:%d..%d\n",
5018      //      i,R->block0[i],R->block1[i],min_var,max_var);
5019      R->block0[i]=min_var;
5020      R->block1[i]=max_var;
5021      if (R->wvhdl[i]!=NULL)
5022      {
5023        omFree(R->wvhdl[i]);
5024        R->wvhdl[i]=(int*)omAlloc0((max_var-min_var+1)*sizeof(int));
5025        for(j=org_ring->block0[i];j<=org_ring->block1[i];j++)
5026        {
5027          if (perm[j]>0)
5028          {
5029            R->wvhdl[i][perm[j]-R->block0[i]]=
5030                org_ring->wvhdl[i][j-org_ring->block0[i]];
5031            //Print("w%d=%d (orig_w%d)\n",perm[j],R->wvhdl[i][perm[j]-R->block0[i]],j);
5032          }
5033        }
5034      }
5035    }
5036    else
5037    {
5038      if(R->block0[i]>0)
5039      {
5040        //Print("skip block %d\n",i);
5041        R->order[i]=ringorder_unspec;
5042        if (R->wvhdl[i] !=NULL) omFree(R->wvhdl[i]);
5043        R->wvhdl[i]=NULL;
5044      }
5045      //else Print("keep block %d\n",i);
5046    }
5047  }
5048  i=n-1;
5049  while(i>0)
5050  {
5051    // removed unneded blocks
5052    if(R->order[i-1]==ringorder_unspec)
5053    {
5054      for(j=i;j<=n;j++)
5055      {
5056        R->order[j-1]=R->order[j];
5057        R->block0[j-1]=R->block0[j];
5058        R->block1[j-1]=R->block1[j];
5059        if (R->wvhdl[j-1] !=NULL) omFree(R->wvhdl[j-1]);
5060        R->wvhdl[j-1]=R->wvhdl[j];
5061      }
5062      R->order[n]=ringorder_unspec;
5063      n--;
5064    }
5065    i--;
5066  }
5067  n=rBlocks(org_ring)-1;
5068  while (R->order[n]==0)  n--;
5069  while (R->order[n]==ringorder_unspec)  n--;
5070  if ((R->order[n]==ringorder_c) ||  (R->order[n]==ringorder_C)) n--;
5071  if (R->block1[n] != R->N)
5072  {
5073    if (((R->order[n]==ringorder_dp) ||
5074         (R->order[n]==ringorder_ds) ||
5075         (R->order[n]==ringorder_Dp) ||
5076         (R->order[n]==ringorder_Ds) ||
5077         (R->order[n]==ringorder_rp) ||
5078         (R->order[n]==ringorder_rs) ||
5079         (R->order[n]==ringorder_lp) ||
5080         (R->order[n]==ringorder_ls))
5081        &&
5082        R->block0[n] <= R->N)
5083    {
5084      R->block1[n] = R->N;
5085    }
5086    else
5087    {
5088      Werror("mismatch of number of vars (%d) and ordering (%d vars) in block %d",
5089             R->N,R->block1[n],n);
5090      return NULL;
5091    }
5092  }
5093  omFree(perm);
5094  // find OrdSgn:
5095  R->OrdSgn = org_ring->OrdSgn; // IMPROVE!
5096  //for(i=1;i<=R->N;i++)
5097  //{ if (weights[i]<0) { R->OrdSgn=-1;break; }}
5098  //omFree(weights);
5099  // Complete the initialization
5100  if (rComplete(R,1))
5101    goto rInitError;
5102
5103  rTest(R);
5104
5105  if (rv != NULL) rv->CleanUp();
5106
5107  return R;
5108
5109  // error case:
5110  rInitError:
5111  if  (R != NULL) rDelete(R);
5112  if (rv != NULL) rv->CleanUp();
5113  return NULL;
5114}
5115
5116void rKill(ring r)
5117{
5118  if ((r->ref<=0)&&(r->order!=NULL))
5119  {
5120#ifdef RDEBUG
5121    if (traceit &TRACE_SHOW_RINGS) Print("kill ring %lx\n",(long)r);
5122#endif
5123    if (r->qideal!=NULL)
5124    {
5125      id_Delete(&r->qideal, r);
5126      r->qideal = NULL;
5127    }
5128    int i=1;
5129    int j;
5130    int *pi=r->order;
5131#ifdef USE_IILOCALRING
5132    for (j=0;j<iiRETURNEXPR_len;j++)
5133    {
5134      if (iiLocalRing[j]==r)
5135      {
5136        if (j<myynest) Warn("killing the basering for level %d",j);
5137        iiLocalRing[j]=NULL;
5138      }
5139    }
5140#else /* USE_IILOCALRING */
5141//#endif /* USE_IILOCALRING */
5142    {
5143      proclevel * nshdl = procstack;
5144      int lev=myynest-1;
5145
5146      for(; nshdl != NULL; nshdl = nshdl->next)
5147      {
5148        if (nshdl->cRing==r)
5149        {
5150          Warn("killing the basering for level %d",lev);
5151          nshdl->cRing=NULL;
5152          nshdl->cRingHdl=NULL;
5153        }
5154      }
5155    }
5156#endif /* USE_IILOCALRING */
5157// any variables depending on r ?
5158    while (r->idroot!=NULL)
5159    {
5160      killhdl2(r->idroot,&(r->idroot),r);
5161    }
5162    if (r==currRing)
5163    {
5164      // all dependend stuff is done, clean global vars:
5165      if (r->qideal!=NULL)
5166      {
5167        currQuotient=NULL;
5168      }
5169      if (ppNoether!=NULL) pDelete(&ppNoether);
5170      if (sLastPrinted.RingDependend())
5171      {
5172        sLastPrinted.CleanUp();
5173      }
5174      if ((myynest>0) && (iiRETURNEXPR[myynest].RingDependend()))
5175      {
5176        WerrorS("return value depends on local ring variable (export missing ?)");
5177        iiRETURNEXPR[myynest].CleanUp();
5178      }
5179      currRing=NULL;
5180      currRingHdl=NULL;
5181    }
5182
5183    /* nKillChar(r); will be called from inside of rDelete */
5184    rDelete(r);
5185    return;
5186  }
5187  r->ref--;
5188}
5189
5190void rKill(idhdl h)
5191{
5192  ring r = IDRING(h);
5193  int ref=0;
5194  if (r!=NULL)
5195  {
5196    ref=r->ref;
5197    rKill(r);
5198  }
5199  if (h==currRingHdl)
5200  {
5201    if (ref<=0) { currRing=NULL; currRingHdl=NULL;}
5202    else
5203    {
5204      currRingHdl=rFindHdl(r,currRingHdl,NULL);
5205    }
5206  }
5207}
5208
5209idhdl rSimpleFindHdl(ring r, idhdl root, idhdl n=NULL)
5210{
5211  //idhdl next_best=NULL;
5212  idhdl h=root;
5213  while (h!=NULL)
5214  {
5215    if (((IDTYP(h)==RING_CMD)||(IDTYP(h)==QRING_CMD))
5216    && (h!=n)
5217    && (IDRING(h)==r)
5218    )
5219    {
5220   //   if (IDLEV(h)==myynest)
5221   //     return h;
5222   //   if ((IDLEV(h)==0) || (next_best==NULL))
5223   //     next_best=h;
5224   //   else if (IDLEV(next_best)<IDLEV(h))
5225   //     next_best=h;
5226      return h;
5227    }
5228    h=IDNEXT(h);
5229  }
5230  //return next_best;
5231  return NULL;
5232}
5233
5234extern BOOLEAN jjPROC(leftv res, leftv u, leftv v);
5235ideal kGroebner(ideal F, ideal Q)
5236{
5237  //test|=Sy_bit(OPT_PROT);
5238  idhdl save_ringhdl=currRingHdl;
5239  ideal resid;
5240  idhdl new_ring=NULL;
5241  if ((currRingHdl==NULL) || (IDRING(currRingHdl)!=currRing))
5242  {
5243    currRingHdl=enterid(omStrDup(" GROEBNERring"),0,RING_CMD,&IDROOT,FALSE);
5244    new_ring=currRingHdl;
5245    IDRING(currRingHdl)=currRing;
5246  }
5247  sleftv v; memset(&v,0,sizeof(v)); v.rtyp=IDEAL_CMD; v.data=(char *) F;
5248  idhdl h=ggetid("groebner");
5249  sleftv u; memset(&u,0,sizeof(u)); u.rtyp=IDHDL; u.data=(char *) h;
5250            u.name=IDID(h);
5251
5252  sleftv res; memset(&res,0,sizeof(res));
5253  if(jjPROC(&res,&u,&v))
5254  {
5255    resid=kStd(F,Q,testHomog,NULL);
5256  }
5257  else
5258  {
5259    //printf("typ:%d\n",res.rtyp);
5260    resid=(ideal)(res.data);
5261  }
5262  // cleanup GROEBNERring, save_ringhdl, u,v,(res )
5263  if (new_ring!=NULL)
5264  {
5265    idhdl h=IDROOT;
5266    if (h==new_ring) IDROOT=h->next;
5267    else
5268    {
5269      while ((h!=NULL) &&(h->next!=new_ring)) h=h->next;
5270      if (h!=NULL) h->next=h->next->next;
5271    }
5272    if (h!=NULL) omFreeSize(h,sizeof(*h));
5273  }
5274  currRingHdl=save_ringhdl;
5275  u.CleanUp();
5276  v.CleanUp();
5277  return resid;
5278}
5279
5280void jjINT_S_TO_ID(int n,int *e, leftv res)
5281{
5282  if (n==0) n=1;
5283  ideal l=idInit(n,1);
5284  int i;
5285  poly p;
5286  for(i=pVariables;i>0;i--)
5287  {
5288    if (e[i]>0)
5289    {
5290      n--;
5291      p=pOne();
5292      pSetExp(p,i,1);
5293      pSetm(p);
5294      l->m[n]=p;
5295      if (n==0) break;
5296    }
5297  }
5298  res->data=(char*)l;
5299  omFreeSize((ADDRESS)e,(pVariables+1)*sizeof(int));
5300}
5301BOOLEAN jjVARIABLES_P(leftv res, leftv u)
5302{
5303  int *e=(int *)omAlloc0((pVariables+1)*sizeof(int));
5304  int n=pGetVariables((poly)u->Data(),e);
5305  jjINT_S_TO_ID(n,e,res);
5306  return FALSE;
5307}
5308
5309BOOLEAN jjVARIABLES_ID(leftv res, leftv u)
5310{
5311  int *e=(int *)omAlloc0((pVariables+1)*sizeof(int));
5312  ideal I=(ideal)u->Data();
5313  int i;
5314  int n=0;
5315  for(i=I->nrows*I->ncols-1;i>=0;i--)
5316  {
5317    n=pGetVariables(I->m[i],e);
5318  }
5319  jjINT_S_TO_ID(n,e,res);
5320  return FALSE;
5321}
Note: See TracBrowser for help on using the repository browser.