source: git/Singular/ipshell.cc @ c99fd4

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