source: git/Singular/ipshell.cc @ 2a38938

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