source: git/Singular/ipshell.cc @ 341696

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