source: git/Singular/ipshell.cc @ 20704f

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