source: git/Singular/ipshell.cc @ 27afa1

spielwiese
Last change on this file since 27afa1 was 27afa1, checked in by Hans Schönemann <hannes@…>, 17 years ago
*hannes: imap ->fetch in rCompose git-svn-id: file:///usr/local/Singular/svn/trunk@9738 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.151 2007-01-18 13:29:39 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          pTest(dest_id->m[i]);
2099        }
2100        R->qideal=dest_id;
2101        if (perm!=NULL)
2102          omFreeSize((ADDRESS)perm,(orig_ring->N+1)*sizeof(int));
2103        if (par_perm!=NULL)
2104          omFreeSize((ADDRESS)par_perm,par_perm_size*sizeof(int));
2105        rChangeCurrRing(orig_ring);
2106      #endif
2107      }
2108      else
2109        R->qideal=idrCopyR(q,currRing,R);
2110    }
2111  }
2112  else
2113  {
2114    WerrorS("q-ideal must be given as `ideal`");
2115    goto rCompose_err;
2116  }
2117
2118
2119  // ---------------------------------------------------------------
2120  #ifdef HAVE_PLURAL
2121  if (L->nr==5)
2122  {
2123    if (nc_CallPlural((matrix)L->m[4].Data(),(matrix)L->m[5].Data(),
2124        NULL,NULL,R))
2125      goto rCompose_err;
2126  }
2127  #endif
2128  return R;
2129
2130rCompose_err:
2131  if (R->N>0)
2132  {
2133    int i;
2134    if (R->names!=NULL)
2135    {
2136      i=R->N-1;
2137      while (i>=0) { if (R->names[i]!=NULL) omFree(R->names[i]); i--; }
2138      omFree(R->names);
2139    }
2140  }
2141  if (R->order!=NULL) omFree(R->order);
2142  if (R->block0!=NULL) omFree(R->block0);
2143  if (R->block1!=NULL) omFree(R->block1);
2144  if (R->wvhdl!=NULL) omFree(R->wvhdl);
2145  omFree(R);
2146  return NULL;
2147}
2148
2149// from matpol.cc
2150
2151/*2
2152* compute the jacobi matrix of an ideal
2153*/
2154BOOLEAN mpJacobi(leftv res,leftv a)
2155{
2156  int     i,j;
2157  matrix result;
2158  ideal id=(ideal)a->Data();
2159
2160  result =mpNew(IDELEMS(id),pVariables);
2161  for (i=1; i<=IDELEMS(id); i++)
2162  {
2163    for (j=1; j<=pVariables; j++)
2164    {
2165      MATELEM(result,i,j) = pDiff(id->m[i-1],j);
2166    }
2167  }
2168  res->data=(char *)result;
2169  return FALSE;
2170}
2171
2172/*2
2173* returns the Koszul-matrix of degree d of a vectorspace with dimension n
2174* uses the first n entrees of id, if id <> NULL
2175*/
2176BOOLEAN mpKoszul(leftv res,leftv c/*ip*/, leftv b/*in*/, leftv id)
2177{
2178  int n=(int)(long)b->Data();
2179  int d=(int)(long)c->Data();
2180  int     k,l,sign,row,col;
2181  matrix  result;
2182  ideal temp;
2183  BOOLEAN bo;
2184  poly    p;
2185
2186  if ((d>n) || (d<1) || (n<1))
2187  {
2188    res->data=(char *)mpNew(1,1);
2189    return FALSE;
2190  }
2191  int *choise = (int*)omAlloc(d*sizeof(int));
2192  if (id==NULL)
2193    temp=idMaxIdeal(1);
2194  else
2195    temp=(ideal)id->Data();
2196
2197  k = binom(n,d);
2198  l = k*d;
2199  l /= n-d+1;
2200  result =mpNew(l,k);
2201  col = 1;
2202  idInitChoise(d,1,n,&bo,choise);
2203  while (!bo)
2204  {
2205    sign = 1;
2206    for (l=1;l<=d;l++)
2207    {
2208      if (choise[l-1]<=IDELEMS(temp))
2209      {
2210        p = pCopy(temp->m[choise[l-1]-1]);
2211        if (sign == -1) p = pNeg(p);
2212        sign *= -1;
2213        row = idGetNumberOfChoise(l-1,d,1,n,choise);
2214        MATELEM(result,row,col) = p;
2215      }
2216    }
2217    col++;
2218    idGetNextChoise(d,n,&bo,choise);
2219  }
2220  if (id==NULL) idDelete(&temp);
2221
2222  res->data=(char *)result;
2223  return FALSE;
2224}
2225
2226// from syz1.cc
2227/*2
2228* read out the Betti numbers from resolution
2229* (interpreter interface)
2230*/
2231BOOLEAN syBetti2(leftv res, leftv u, leftv w)
2232{
2233  syStrategy syzstr=(syStrategy)u->Data();
2234  BOOLEAN minim=(int)(long)w->Data();
2235  int row_shift=0;
2236  int add_row_shift=0;
2237  intvec *weights=NULL;
2238  intvec *ww=(intvec *)atGet(u,"isHomog",INTVEC_CMD);
2239  if (ww!=NULL)
2240  {
2241     weights=ivCopy(ww);
2242     add_row_shift = ww->min_in();
2243     (*weights) -= add_row_shift;
2244  }
2245  res->data=(void *)syBettiOfComputation(syzstr,minim,&row_shift,weights);
2246  //row_shift += add_row_shift;
2247  //Print("row_shift=%d, add_row_shift=%d\n",row_shift,add_row_shift);
2248  atSet(res,omStrDup("rowShift"),(void*)add_row_shift,INT_CMD);
2249  return FALSE;
2250}
2251BOOLEAN syBetti1(leftv res, leftv u)
2252{
2253  sleftv tmp;
2254  memset(&tmp,0,sizeof(tmp));
2255  tmp.rtyp=INT_CMD;
2256  tmp.data=(void *)1;
2257  return syBetti2(res,u,&tmp);
2258}
2259
2260/*3
2261* converts a resolution into a list of modules
2262*/
2263lists syConvRes(syStrategy syzstr,BOOLEAN toDel,int add_row_shift)
2264{
2265  if ((syzstr->fullres==NULL) && (syzstr->minres==NULL))
2266  {
2267    if (syzstr->hilb_coeffs==NULL)
2268    {
2269      syzstr->fullres = syReorder(syzstr->res,syzstr->length,syzstr);
2270    }
2271    else
2272    {
2273      syzstr->minres = syReorder(syzstr->orderedRes,syzstr->length,syzstr);
2274      syKillEmptyEntres(syzstr->minres,syzstr->length);
2275    }
2276  }
2277  resolvente tr;
2278  int typ0=IDEAL_CMD;
2279  if (syzstr->minres!=NULL)
2280    tr = syzstr->minres;
2281  else
2282    tr = syzstr->fullres;
2283  resolvente trueres=NULL;
2284  intvec ** w=NULL;
2285  if (syzstr->length>0)
2286  {
2287    trueres=(resolvente)omAlloc0((syzstr->length)*sizeof(ideal));
2288    for (int i=(syzstr->length)-1;i>=0;i--)
2289    {
2290      if (tr[i]!=NULL)
2291      {
2292        trueres[i] = idCopy(tr[i]);
2293      }
2294    }
2295    if (idRankFreeModule(trueres[0]) > 0)
2296      typ0 = MODUL_CMD;
2297    if (syzstr->weights!=NULL)
2298    {
2299      w = (intvec**)omAlloc0((syzstr->length)*sizeof(intvec*));
2300      for (int i=(syzstr->length)-1;i>=0;i--)
2301      {
2302        if (syzstr->weights[i]!=NULL) w[i] = ivCopy(syzstr->weights[i]);
2303      }
2304    }
2305  }
2306  lists li = liMakeResolv(trueres,syzstr->length,syzstr->list_length,typ0,
2307                          w,add_row_shift);
2308  if (w != NULL) omFreeSize(w, (syzstr->length)*sizeof(intvec*));
2309  if (toDel) syKillComputation(syzstr);
2310  return li;
2311}
2312
2313/*3
2314* converts a list of modules into a resolution
2315*/
2316syStrategy syConvList(lists li,BOOLEAN toDel)
2317{
2318  int typ0;
2319  syStrategy result=(syStrategy)omAlloc0(sizeof(ssyStrategy));
2320
2321  resolvente fr = liFindRes(li,&(result->length),&typ0,&(result->weights));
2322  if (fr != NULL)
2323  {
2324
2325    result->fullres = (resolvente)omAlloc0((result->length+1)*sizeof(ideal));
2326    for (int i=result->length-1;i>=0;i--)
2327    {
2328      if (fr[i]!=NULL)
2329        result->fullres[i] = idCopy(fr[i]);
2330    }
2331    result->list_length=result->length;
2332    omFreeSize((ADDRESS)fr,(result->length)*sizeof(ideal));
2333  }
2334  else
2335  {
2336    omFreeSize(result, sizeof(ssyStrategy));
2337    result = NULL;
2338  }
2339  if (toDel) li->Clean();
2340  return result;
2341}
2342
2343/*3
2344* converts a list of modules into a minimal resolution
2345*/
2346syStrategy syForceMin(lists li)
2347{
2348  int typ0;
2349  syStrategy result=(syStrategy)omAlloc0(sizeof(ssyStrategy));
2350
2351  resolvente fr = liFindRes(li,&(result->length),&typ0);
2352  result->minres = (resolvente)omAlloc0((result->length+1)*sizeof(ideal));
2353  for (int i=result->length-1;i>=0;i--)
2354  {
2355    if (fr[i]!=NULL)
2356      result->minres[i] = idCopy(fr[i]);
2357  }
2358  omFreeSize((ADDRESS)fr,(result->length)*sizeof(ideal));
2359  return result;
2360}
2361// from weight.cc
2362BOOLEAN kWeight(leftv res,leftv id)
2363{
2364  ideal F=(ideal)id->Data();
2365  intvec * iv = new intvec(pVariables);
2366  polyset s;
2367  int  sl, n, i;
2368  int  *x;
2369
2370  res->data=(char *)iv;
2371  s = F->m;
2372  sl = IDELEMS(F) - 1;
2373  n = pVariables;
2374  wNsqr = (double)2.0 / (double)n;
2375  wFunctional = wFunctionalBuch;
2376  x = (int * )omAlloc(2 * (n + 1) * sizeof(int));
2377  wCall(s, sl, x);
2378  for (i = n; i!=0; i--)
2379    (*iv)[i-1] = x[i + n + 1];
2380  omFreeSize((ADDRESS)x, 2 * (n + 1) * sizeof(int));
2381  return FALSE;
2382}
2383
2384BOOLEAN kQHWeight(leftv res,leftv v)
2385{
2386  res->data=(char *)idQHomWeight((ideal)v->Data());
2387  if (res->data==NULL)
2388    res->data=(char *)new intvec(pVariables);
2389  return FALSE;
2390}
2391/*==============================================================*/
2392// from clapsing.cc
2393#if 0
2394BOOLEAN jjIS_SQR_FREE(leftv res, leftv u)
2395{
2396  BOOLEAN b=singclap_factorize((poly)(u->Data()), &v, 0);
2397  res->data=(void *)b;
2398}
2399#endif
2400
2401BOOLEAN jjRESULTANT(leftv res, leftv u, leftv v, leftv w)
2402{
2403  res->data=singclap_resultant((poly)u->Data(),(poly)v->Data(), (poly)w->Data());
2404  return errorreported;
2405}
2406BOOLEAN jjCHARSERIES(leftv res, leftv u)
2407{
2408  res->data=singclap_irrCharSeries((ideal)u->Data());
2409  return (res->data==NULL);
2410}
2411
2412// from semic.cc
2413#ifdef HAVE_SPECTRUM
2414
2415// ----------------------------------------------------------------------------
2416//  Initialize a  spectrum  deep from another  spectrum
2417// ----------------------------------------------------------------------------
2418
2419void spectrum::copy_deep( const spectrum &spec )
2420{
2421    mu = spec.mu;
2422    pg = spec.pg;
2423    n  = spec.n;
2424
2425    copy_new( n );
2426
2427    for( int i=0; i<n; i++ )
2428    {
2429        s[i] = spec.s[i];
2430        w[i] = spec.w[i];
2431    }
2432}
2433
2434// ----------------------------------------------------------------------------
2435//  Initialize a  spectrum  deep from a  singular  lists
2436// ----------------------------------------------------------------------------
2437
2438void spectrum::copy_deep( lists l )
2439{
2440    mu = (int)(long)(l->m[0].Data( ));
2441    pg = (int)(long)(l->m[1].Data( ));
2442    n  = (int)(long)(l->m[2].Data( ));
2443
2444    copy_new( n );
2445
2446    intvec  *num = (intvec*)l->m[3].Data( );
2447    intvec  *den = (intvec*)l->m[4].Data( );
2448    intvec  *mul = (intvec*)l->m[5].Data( );
2449
2450    for( int i=0; i<n; i++ )
2451    {
2452        s[i] = (Rational)((*num)[i])/(Rational)((*den)[i]);
2453        w[i] = (*mul)[i];
2454    }
2455}
2456
2457// ----------------------------------------------------------------------------
2458//  singular lists  constructor for  spectrum
2459// ----------------------------------------------------------------------------
2460
2461spectrum::spectrum( lists l )
2462{
2463    copy_deep( l );
2464}
2465
2466// ----------------------------------------------------------------------------
2467//  generate a Singular  lists  from a spectrum
2468// ----------------------------------------------------------------------------
2469
2470lists   spectrum::thelist( void )
2471{
2472    lists   L  = (lists)omAllocBin( slists_bin);
2473
2474    L->Init( 6 );
2475
2476    intvec            *num  = new intvec( n );
2477    intvec            *den  = new intvec( n );
2478    intvec            *mult = new intvec( n );
2479
2480    for( int i=0; i<n; i++ )
2481    {
2482        (*num) [i] = s[i].get_num_si( );
2483        (*den) [i] = s[i].get_den_si( );
2484        (*mult)[i] = w[i];
2485    }
2486
2487    L->m[0].rtyp = INT_CMD;    //  milnor number
2488    L->m[1].rtyp = INT_CMD;    //  geometrical genus
2489    L->m[2].rtyp = INT_CMD;    //  # of spectrum numbers
2490    L->m[3].rtyp = INTVEC_CMD; //  numerators
2491    L->m[4].rtyp = INTVEC_CMD; //  denomiantors
2492    L->m[5].rtyp = INTVEC_CMD; //  multiplicities
2493
2494    L->m[0].data = (void*)mu;
2495    L->m[1].data = (void*)pg;
2496    L->m[2].data = (void*)n;
2497    L->m[3].data = (void*)num;
2498    L->m[4].data = (void*)den;
2499    L->m[5].data = (void*)mult;
2500
2501    return  L;
2502}
2503// from spectrum.cc
2504// ----------------------------------------------------------------------------
2505//  print out an error message for a spectrum list
2506// ----------------------------------------------------------------------------
2507
2508void    list_error( semicState state )
2509{
2510    switch( state )
2511    {
2512        case semicListTooShort:
2513            WerrorS( "the list is too short" );
2514            break;
2515        case semicListTooLong:
2516            WerrorS( "the list is too long" );
2517            break;
2518
2519        case semicListFirstElementWrongType:
2520            WerrorS( "first element of the list should be int" );
2521            break;
2522        case semicListSecondElementWrongType:
2523            WerrorS( "second element of the list should be int" );
2524            break;
2525        case semicListThirdElementWrongType:
2526            WerrorS( "third element of the list should be int" );
2527            break;
2528        case semicListFourthElementWrongType:
2529            WerrorS( "fourth element of the list should be intvec" );
2530            break;
2531        case semicListFifthElementWrongType:
2532            WerrorS( "fifth element of the list should be intvec" );
2533            break;
2534        case semicListSixthElementWrongType:
2535            WerrorS( "sixth element of the list should be intvec" );
2536            break;
2537
2538        case semicListNNegative:
2539            WerrorS( "first element of the list should be positive" );
2540            break;
2541        case semicListWrongNumberOfNumerators:
2542            WerrorS( "wrong number of numerators" );
2543            break;
2544        case semicListWrongNumberOfDenominators:
2545            WerrorS( "wrong number of denominators" );
2546            break;
2547        case semicListWrongNumberOfMultiplicities:
2548            WerrorS( "wrong number of multiplicities" );
2549            break;
2550
2551        case semicListMuNegative:
2552            WerrorS( "the Milnor number should be positive" );
2553            break;
2554        case semicListPgNegative:
2555            WerrorS( "the geometrical genus should be nonnegative" );
2556            break;
2557        case semicListNumNegative:
2558            WerrorS( "all numerators should be positive" );
2559            break;
2560        case semicListDenNegative:
2561            WerrorS( "all denominators should be positive" );
2562            break;
2563        case semicListMulNegative:
2564            WerrorS( "all multiplicities should be positive" );
2565            break;
2566
2567        case semicListNotSymmetric:
2568            WerrorS( "it is not symmetric" );
2569            break;
2570        case semicListNotMonotonous:
2571            WerrorS( "it is not monotonous" );
2572            break;
2573
2574        case semicListMilnorWrong:
2575            WerrorS( "the Milnor number is wrong" );
2576            break;
2577        case semicListPGWrong:
2578            WerrorS( "the geometrical genus is wrong" );
2579            break;
2580
2581        default:
2582            WerrorS( "unspecific error" );
2583            break;
2584    }
2585}
2586// ----------------------------------------------------------------------------
2587//  this is the main spectrum computation function
2588// ----------------------------------------------------------------------------
2589
2590spectrumState   spectrumCompute( poly h,lists *L,int fast )
2591{
2592  int i,j;
2593
2594  #ifdef SPECTRUM_DEBUG
2595  #ifdef SPECTRUM_PRINT
2596  #ifdef SPECTRUM_IOSTREAM
2597    cout << "spectrumCompute\n";
2598    if( fast==0 ) cout << "    no optimization" << endl;
2599    if( fast==1 ) cout << "    weight optimization" << endl;
2600    if( fast==2 ) cout << "    symmetry optimization" << endl;
2601  #else
2602    fprintf( stdout,"spectrumCompute\n" );
2603    if( fast==0 ) fprintf( stdout,"    no optimization\n" );
2604    if( fast==1 ) fprintf( stdout,"    weight optimization\n" );
2605    if( fast==2 ) fprintf( stdout,"    symmetry optimization\n" );
2606  #endif
2607  #endif
2608  #endif
2609
2610  // ----------------------
2611  //  check if  h  is zero
2612  // ----------------------
2613
2614  if( h==(poly)NULL )
2615  {
2616    return  spectrumZero;
2617  }
2618
2619  // ----------------------------------
2620  //  check if  h  has a constant term
2621  // ----------------------------------
2622
2623  if( hasConstTerm( h ) )
2624  {
2625    return  spectrumBadPoly;
2626  }
2627
2628  // --------------------------------
2629  //  check if  h  has a linear term
2630  // --------------------------------
2631
2632  if( hasLinearTerm( h ) )
2633  {
2634    *L = (lists)omAllocBin( slists_bin);
2635    (*L)->Init( 1 );
2636    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
2637    /* (*L)->m[0].data = (void*)0;a  -- done by Init */
2638
2639    return  spectrumNoSingularity;
2640  }
2641
2642  // ----------------------------------
2643  //  compute the jacobi ideal of  (h)
2644  // ----------------------------------
2645
2646  ideal J = NULL;
2647  J = idInit( pVariables,1 );
2648
2649  #ifdef SPECTRUM_DEBUG
2650  #ifdef SPECTRUM_PRINT
2651  #ifdef SPECTRUM_IOSTREAM
2652    cout << "\n   computing the Jacobi ideal...\n";
2653  #else
2654    fprintf( stdout,"\n   computing the Jacobi ideal...\n" );
2655  #endif
2656  #endif
2657  #endif
2658
2659  for( i=0; i<pVariables; i++ )
2660  {
2661    J->m[i] = pDiff( h,i+1); //j );
2662
2663    #ifdef SPECTRUM_DEBUG
2664    #ifdef SPECTRUM_PRINT
2665    #ifdef SPECTRUM_IOSTREAM
2666      cout << "        ";
2667    #else
2668      fprintf( stdout,"        " );
2669    #endif
2670      pWrite( J->m[i] );
2671    #endif
2672    #endif
2673  }
2674
2675  // --------------------------------------------
2676  //  compute a standard basis  stdJ  of  jac(h)
2677  // --------------------------------------------
2678
2679  #ifdef SPECTRUM_DEBUG
2680  #ifdef SPECTRUM_PRINT
2681  #ifdef SPECTRUM_IOSTREAM
2682    cout << endl;
2683    cout << "    computing a standard basis..." << endl;
2684  #else
2685    fprintf( stdout,"\n" );
2686    fprintf( stdout,"    computing a standard basis...\n" );
2687  #endif
2688  #endif
2689  #endif
2690
2691  ideal stdJ = kStd(J,currQuotient,isNotHomog,NULL);
2692  idSkipZeroes( stdJ );
2693
2694  #ifdef SPECTRUM_DEBUG
2695  #ifdef SPECTRUM_PRINT
2696    for( i=0; i<IDELEMS(stdJ); i++ )
2697    {
2698      #ifdef SPECTRUM_IOSTREAM
2699        cout << "        ";
2700      #else
2701        fprintf( stdout,"        " );
2702      #endif
2703
2704      pWrite( stdJ->m[i] );
2705    }
2706  #endif
2707  #endif
2708
2709  idDelete( &J );
2710
2711  // ------------------------------------------
2712  //  check if the  h  has a singularity
2713  // ------------------------------------------
2714
2715  if( hasOne( stdJ ) )
2716  {
2717    // -------------------------------
2718    //  h is smooth in the origin
2719    //  return only the Milnor number
2720    // -------------------------------
2721
2722    *L = (lists)omAllocBin( slists_bin);
2723    (*L)->Init( 1 );
2724    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
2725    /* (*L)->m[0].data = (void*)0;a  -- done by Init */
2726
2727    return  spectrumNoSingularity;
2728  }
2729
2730  // ------------------------------------------
2731  //  check if the singularity  h  is isolated
2732  // ------------------------------------------
2733
2734  for( i=pVariables; i>0; i-- )
2735  {
2736    if( hasAxis( stdJ,i )==FALSE )
2737    {
2738      return  spectrumNotIsolated;
2739    }
2740  }
2741
2742  // ------------------------------------------
2743  //  compute the highest corner  hc  of  stdJ
2744  // ------------------------------------------
2745
2746  #ifdef SPECTRUM_DEBUG
2747  #ifdef SPECTRUM_PRINT
2748  #ifdef SPECTRUM_IOSTREAM
2749    cout << "\n    computing the highest corner...\n";
2750  #else
2751    fprintf( stdout,"\n    computing the highest corner...\n" );
2752  #endif
2753  #endif
2754  #endif
2755
2756  poly hc = (poly)NULL;
2757
2758  scComputeHC( stdJ,currQuotient, 0,hc );
2759
2760  if( hc!=(poly)NULL )
2761  {
2762    pGetCoeff(hc) = nInit(1);
2763
2764    for( i=pVariables; i>0; i-- )
2765    {
2766      if( pGetExp( hc,i )>0 ) pDecrExp( hc,i );
2767    }
2768    pSetm( hc );
2769  }
2770  else
2771  {
2772    return  spectrumNoHC;
2773  }
2774
2775  #ifdef SPECTRUM_DEBUG
2776  #ifdef SPECTRUM_PRINT
2777  #ifdef SPECTRUM_IOSTREAM
2778    cout << "       ";
2779  #else
2780    fprintf( stdout,"       " );
2781  #endif
2782    pWrite( hc );
2783  #endif
2784  #endif
2785
2786  // ----------------------------------------
2787  //  compute the Newton polygon  nph  of  h
2788  // ----------------------------------------
2789
2790  #ifdef SPECTRUM_DEBUG
2791  #ifdef SPECTRUM_PRINT
2792  #ifdef SPECTRUM_IOSTREAM
2793    cout << "\n    computing the newton polygon...\n";
2794  #else
2795    fprintf( stdout,"\n    computing the newton polygon...\n" );
2796  #endif
2797  #endif
2798  #endif
2799
2800  newtonPolygon nph( h );
2801
2802  #ifdef SPECTRUM_DEBUG
2803  #ifdef SPECTRUM_PRINT
2804    cout << nph;
2805  #endif
2806  #endif
2807
2808  // -----------------------------------------------
2809  //  compute the weight corner  wc  of  (stdj,nph)
2810  // -----------------------------------------------
2811
2812  #ifdef SPECTRUM_DEBUG
2813  #ifdef SPECTRUM_PRINT
2814  #ifdef SPECTRUM_IOSTREAM
2815    cout << "\n    computing the weight corner...\n";
2816  #else
2817    fprintf( stdout,"\n    computing the weight corner...\n" );
2818  #endif
2819  #endif
2820  #endif
2821
2822  poly    wc = ( fast==0 ? pCopy( hc ) :
2823               ( fast==1 ? computeWC( nph,(Rational)pVariables ) :
2824              /* fast==2 */computeWC( nph,((Rational)pVariables)/(Rational)2 ) ) );
2825
2826  #ifdef SPECTRUM_DEBUG
2827  #ifdef SPECTRUM_PRINT
2828  #ifdef SPECTRUM_IOSTREAM
2829    cout << "        ";
2830  #else
2831    fprintf( stdout,"        " );
2832  #endif
2833    pWrite( wc );
2834  #endif
2835  #endif
2836
2837  // -------------
2838  //  compute  NF
2839  // -------------
2840
2841  #ifdef SPECTRUM_DEBUG
2842  #ifdef SPECTRUM_PRINT
2843  #ifdef SPECTRUM_IOSTREAM
2844    cout << "\n    computing NF...\n" << endl;
2845  #else
2846    fprintf( stdout,"\n    computing NF...\n" );
2847  #endif
2848  #endif
2849  #endif
2850
2851  spectrumPolyList NF( &nph );
2852
2853  computeNF( stdJ,hc,wc,&NF );
2854
2855  #ifdef SPECTRUM_DEBUG
2856  #ifdef SPECTRUM_PRINT
2857    cout << NF;
2858  #ifdef SPECTRUM_IOSTREAM
2859    cout << endl;
2860  #else
2861    fprintf( stdout,"\n" );
2862  #endif
2863  #endif
2864  #endif
2865
2866  // ----------------------------
2867  //  compute the spectrum of  h
2868  // ----------------------------
2869
2870  return  NF.spectrum( L,fast );
2871}
2872
2873// ----------------------------------------------------------------------------
2874//  this procedure is called from the interpreter
2875// ----------------------------------------------------------------------------
2876//  first  = polynomial
2877//  result = list of spectrum numbers
2878// ----------------------------------------------------------------------------
2879
2880BOOLEAN spectrumProc( leftv result,leftv first )
2881{
2882  spectrumState state = spectrumOK;
2883
2884  // -------------------
2885  //  check consistency
2886  // -------------------
2887
2888  //  check for a local ring
2889
2890  if( !ringIsLocal( ) )
2891  {
2892    WerrorS( "only works for local orderings" );
2893    state = spectrumWrongRing;
2894  }
2895
2896  //  no quotient rings are allowed
2897
2898  else if( currRing->qideal != NULL )
2899  {
2900    WerrorS( "does not work in quotient rings" );
2901    state = spectrumWrongRing;
2902  }
2903  else
2904  {
2905    lists   L    = (lists)NULL;
2906    int     flag = 1; // weight corner optimization is safe
2907
2908    state = spectrumCompute( (poly)first->Data( ),&L,flag );
2909
2910    if( state==spectrumOK )
2911    {
2912      result->rtyp = LIST_CMD;
2913      result->data = (char*)L;
2914    }
2915    else
2916    {
2917      spectrumPrintError(state);
2918    }
2919  }
2920
2921  return  (state!=spectrumOK);
2922}
2923
2924// ----------------------------------------------------------------------------
2925//  this procedure is called from the interpreter
2926// ----------------------------------------------------------------------------
2927//  first  = polynomial
2928//  result = list of spectrum numbers
2929// ----------------------------------------------------------------------------
2930
2931BOOLEAN spectrumfProc( leftv result,leftv first )
2932{
2933  spectrumState state = spectrumOK;
2934
2935  // -------------------
2936  //  check consistency
2937  // -------------------
2938
2939  //  check for a local polynomial ring
2940
2941  if( currRing->OrdSgn != -1 )
2942  // ?? HS: the test above is also true for k[x][[y]], k[[x]][y]
2943  // or should we use:
2944  //if( !ringIsLocal( ) )
2945  {
2946    WerrorS( "only works for local orderings" );
2947    state = spectrumWrongRing;
2948  }
2949  else if( currRing->qideal != NULL )
2950  {
2951    WerrorS( "does not work in quotient rings" );
2952    state = spectrumWrongRing;
2953  }
2954  else
2955  {
2956    lists   L    = (lists)NULL;
2957    int     flag = 2; // symmetric optimization
2958
2959    state = spectrumCompute( (poly)first->Data( ),&L,flag );
2960
2961    if( state==spectrumOK )
2962    {
2963      result->rtyp = LIST_CMD;
2964      result->data = (char*)L;
2965    }
2966    else
2967    {
2968      spectrumPrintError(state);
2969    }
2970  }
2971
2972  return  (state!=spectrumOK);
2973}
2974
2975// ----------------------------------------------------------------------------
2976//  check if a list is a spectrum
2977//  check for:
2978//      list has 6 elements
2979//      1st element is int (mu=Milnor number)
2980//      2nd element is int (pg=geometrical genus)
2981//      3rd element is int (n =number of different spectrum numbers)
2982//      4th element is intvec (num=numerators)
2983//      5th element is intvec (den=denomiantors)
2984//      6th element is intvec (mul=multiplicities)
2985//      exactly n numerators
2986//      exactly n denominators
2987//      exactly n multiplicities
2988//      mu>0
2989//      pg>=0
2990//      n>0
2991//      num>0
2992//      den>0
2993//      mul>0
2994//      symmetriy with respect to numberofvariables/2
2995//      monotony
2996//      mu = sum of all multiplicities
2997//      pg = sum of all multiplicities where num/den<=1
2998// ----------------------------------------------------------------------------
2999
3000semicState  list_is_spectrum( lists l )
3001{
3002    // -------------------
3003    //  check list length
3004    // -------------------
3005
3006    if( l->nr < 5 )
3007    {
3008        return  semicListTooShort;
3009    }
3010    else if( l->nr > 5 )
3011    {
3012        return  semicListTooLong;
3013    }
3014
3015    // -------------
3016    //  check types
3017    // -------------
3018
3019    if( l->m[0].rtyp != INT_CMD )
3020    {
3021        return  semicListFirstElementWrongType;
3022    }
3023    else if( l->m[1].rtyp != INT_CMD )
3024    {
3025        return  semicListSecondElementWrongType;
3026    }
3027    else if( l->m[2].rtyp != INT_CMD )
3028    {
3029        return  semicListThirdElementWrongType;
3030    }
3031    else if( l->m[3].rtyp != INTVEC_CMD )
3032    {
3033        return  semicListFourthElementWrongType;
3034    }
3035    else if( l->m[4].rtyp != INTVEC_CMD )
3036    {
3037        return  semicListFifthElementWrongType;
3038    }
3039    else if( l->m[5].rtyp != INTVEC_CMD )
3040    {
3041        return  semicListSixthElementWrongType;
3042    }
3043
3044    // -------------------------
3045    //  check number of entries
3046    // -------------------------
3047
3048    int     mu = (int)(long)(l->m[0].Data( ));
3049    int     pg = (int)(long)(l->m[1].Data( ));
3050    int     n  = (int)(long)(l->m[2].Data( ));
3051
3052    if( n <= 0 )
3053    {
3054        return  semicListNNegative;
3055    }
3056
3057    intvec  *num = (intvec*)l->m[3].Data( );
3058    intvec  *den = (intvec*)l->m[4].Data( );
3059    intvec  *mul = (intvec*)l->m[5].Data( );
3060
3061    if( n != num->length( ) )
3062    {
3063        return  semicListWrongNumberOfNumerators;
3064    }
3065    else if( n != den->length( ) )
3066    {
3067        return  semicListWrongNumberOfDenominators;
3068    }
3069    else if( n != mul->length( ) )
3070    {
3071        return  semicListWrongNumberOfMultiplicities;
3072    }
3073
3074    // --------
3075    //  values
3076    // --------
3077
3078    if( mu <= 0 )
3079    {
3080        return  semicListMuNegative;
3081    }
3082    if( pg < 0 )
3083    {
3084        return  semicListPgNegative;
3085    }
3086
3087    int i;
3088
3089    for( i=0; i<n; i++ )
3090    {
3091        if( (*num)[i] <= 0 )
3092        {
3093            return  semicListNumNegative;
3094        }
3095        if( (*den)[i] <= 0 )
3096        {
3097            return  semicListDenNegative;
3098        }
3099        if( (*mul)[i] <= 0 )
3100        {
3101            return  semicListMulNegative;
3102        }
3103    }
3104
3105    // ----------------
3106    //  check symmetry
3107    // ----------------
3108
3109    int     j;
3110
3111    for( i=0, j=n-1; i<=j; i++,j-- )
3112    {
3113        if( (*num)[i] != pVariables*((*den)[i]) - (*num)[j] ||
3114            (*den)[i] != (*den)[j] ||
3115            (*mul)[i] != (*mul)[j] )
3116        {
3117            return  semicListNotSymmetric;
3118        }
3119    }
3120
3121    // ----------------
3122    //  check monotony
3123    // ----------------
3124
3125    for( i=0, j=1; i<n/2; i++,j++ )
3126    {
3127        if( (*num)[i]*(*den)[j] >= (*num)[j]*(*den)[i] )
3128        {
3129            return  semicListNotMonotonous;
3130        }
3131    }
3132
3133    // ---------------------
3134    //  check Milnor number
3135    // ---------------------
3136
3137    for( mu=0, i=0; i<n; i++ )
3138    {
3139        mu += (*mul)[i];
3140    }
3141
3142    if( mu != (int)(long)(l->m[0].Data( )) )
3143    {
3144        return  semicListMilnorWrong;
3145    }
3146
3147    // -------------------------
3148    //  check geometrical genus
3149    // -------------------------
3150
3151    for( pg=0, i=0; i<n; i++ )
3152    {
3153        if( (*num)[i]<=(*den)[i] )
3154        {
3155            pg += (*mul)[i];
3156        }
3157    }
3158
3159    if( pg != (int)(long)(l->m[1].Data( )) )
3160    {
3161        return  semicListPGWrong;
3162    }
3163
3164    return  semicOK;
3165}
3166
3167// ----------------------------------------------------------------------------
3168//  this procedure is called from the interpreter
3169// ----------------------------------------------------------------------------
3170//  first  = list of spectrum numbers
3171//  second = list of spectrum numbers
3172//  result = sum of the two lists
3173// ----------------------------------------------------------------------------
3174
3175BOOLEAN spaddProc( leftv result,leftv first,leftv second )
3176{
3177    semicState  state;
3178
3179    // -----------------
3180    //  check arguments
3181    // -----------------
3182
3183    lists l1 = (lists)first->Data( );
3184    lists l2 = (lists)second->Data( );
3185
3186    if( (state=list_is_spectrum( l1 )) != semicOK )
3187    {
3188        WerrorS( "first argument is not a spectrum:" );
3189        list_error( state );
3190    }
3191    else if( (state=list_is_spectrum( l2 )) != semicOK )
3192    {
3193        WerrorS( "second argument is not a spectrum:" );
3194        list_error( state );
3195    }
3196    else
3197    {
3198        spectrum s1( l1 );
3199        spectrum s2( l2 );
3200        spectrum sum( s1+s2 );
3201
3202        result->rtyp = LIST_CMD;
3203        result->data = (char*)(sum.thelist( ));
3204    }
3205
3206    return  (state!=semicOK);
3207}
3208
3209// ----------------------------------------------------------------------------
3210//  this procedure is called from the interpreter
3211// ----------------------------------------------------------------------------
3212//  first  = list of spectrum numbers
3213//  second = integer
3214//  result = the multiple of the first list by the second factor
3215// ----------------------------------------------------------------------------
3216
3217BOOLEAN spmulProc( leftv result,leftv first,leftv second )
3218{
3219    semicState  state;
3220
3221    // -----------------
3222    //  check arguments
3223    // -----------------
3224
3225    lists   l = (lists)first->Data( );
3226    int     k = (int)(long)second->Data( );
3227
3228    if( (state=list_is_spectrum( l ))!=semicOK )
3229    {
3230        WerrorS( "first argument is not a spectrum" );
3231        list_error( state );
3232    }
3233    else if( k < 0 )
3234    {
3235        WerrorS( "second argument should be positive" );
3236        state = semicMulNegative;
3237    }
3238    else
3239    {
3240        spectrum s( l );
3241        spectrum product( k*s );
3242
3243        result->rtyp = LIST_CMD;
3244        result->data = (char*)product.thelist( );
3245    }
3246
3247    return  (state!=semicOK);
3248}
3249
3250// ----------------------------------------------------------------------------
3251//  this procedure is called from the interpreter
3252// ----------------------------------------------------------------------------
3253//  first  = list of spectrum numbers
3254//  second = list of spectrum numbers
3255//  result = semicontinuity index
3256// ----------------------------------------------------------------------------
3257
3258BOOLEAN    semicProc3   ( leftv res,leftv u,leftv v,leftv w )
3259{
3260  semicState  state;
3261  BOOLEAN qh=(((int)(long)w->Data())==1);
3262
3263  // -----------------
3264  //  check arguments
3265  // -----------------
3266
3267  lists l1 = (lists)u->Data( );
3268  lists l2 = (lists)v->Data( );
3269
3270  if( (state=list_is_spectrum( l1 ))!=semicOK )
3271  {
3272    WerrorS( "first argument is not a spectrum" );
3273    list_error( state );
3274  }
3275  else if( (state=list_is_spectrum( l2 ))!=semicOK )
3276  {
3277    WerrorS( "second argument is not a spectrum" );
3278    list_error( state );
3279  }
3280  else
3281  {
3282    spectrum s1( l1 );
3283    spectrum s2( l2 );
3284
3285    res->rtyp = INT_CMD;
3286    if (qh)
3287      res->data = (void*)(s1.mult_spectrumh( s2 ));
3288    else
3289      res->data = (void*)(s1.mult_spectrum( s2 ));
3290  }
3291
3292  // -----------------
3293  //  check status
3294  // -----------------
3295
3296  return  (state!=semicOK);
3297}
3298BOOLEAN    semicProc   ( leftv res,leftv u,leftv v )
3299{
3300  sleftv tmp;
3301  memset(&tmp,0,sizeof(tmp));
3302  tmp.rtyp=INT_CMD;
3303  /* tmp.data = (void *)0;  -- done by memset */
3304
3305  return  semicProc3(res,u,v,&tmp);
3306}
3307// from splist.cc
3308// ----------------------------------------------------------------------------
3309//  Compute the spectrum of a  spectrumPolyList
3310// ----------------------------------------------------------------------------
3311
3312spectrumState   spectrumPolyList::spectrum( lists *L,int fast )
3313{
3314    spectrumPolyNode  **node = &root;
3315    spectrumPolyNode  *search;
3316
3317    poly              f,tmp;
3318    int               found,cmp;
3319
3320    Rational smax( ( fast==0 ? 0 : pVariables ),
3321                   ( fast==2 ? 2 : 1 ) );
3322
3323    Rational weight_prev( 0,1 );
3324
3325    int     mu = 0;          // the milnor number
3326    int     pg = 0;          // the geometrical genus
3327    int     n  = 0;          // number of different spectral numbers
3328    int     z  = 0;          // number of spectral number equal to smax
3329
3330    int     k = 0;
3331
3332    while( (*node)!=(spectrumPolyNode*)NULL &&
3333           ( fast==0 || (*node)->weight<=smax ) )
3334    {
3335        // ---------------------------------------
3336        //  determine the first normal form which
3337        //  contains the monomial  node->mon
3338        // ---------------------------------------
3339
3340        found  = FALSE;
3341        search = *node;
3342
3343        while( search!=(spectrumPolyNode*)NULL && found==FALSE )
3344        {
3345            if( search->nf!=(poly)NULL )
3346            {
3347                f = search->nf;
3348
3349                do
3350                {
3351                    // --------------------------------
3352                    //  look for  (*node)->mon  in   f
3353                    // --------------------------------
3354
3355                    cmp = pCmp( (*node)->mon,f );
3356
3357                    if( cmp<0 )
3358                    {
3359                        f = pNext( f );
3360                    }
3361                    else if( cmp==0 )
3362                    {
3363                        // -----------------------------
3364                        //  we have found a normal form
3365                        // -----------------------------
3366
3367                        found = TRUE;
3368
3369                        //  normalize coefficient
3370
3371                        number inv = nInvers( pGetCoeff( f ) );
3372                        pMult_nn( search->nf,inv );
3373                        nDelete( &inv );
3374
3375                        //  exchange  normal forms
3376
3377                        tmp         = (*node)->nf;
3378                        (*node)->nf = search->nf;
3379                        search->nf  = tmp;
3380                    }
3381                }
3382                while( cmp<0 && f!=(poly)NULL );
3383            }
3384            search = search->next;
3385        }
3386
3387        if( found==FALSE )
3388        {
3389            // ------------------------------------------------
3390            //  the weight of  node->mon  is a spectrum number
3391            // ------------------------------------------------
3392
3393            mu++;
3394
3395            if( (*node)->weight<=(Rational)1 )              pg++;
3396            if( (*node)->weight==smax )           z++;
3397            if( (*node)->weight>weight_prev )     n++;
3398
3399            weight_prev = (*node)->weight;
3400            node = &((*node)->next);
3401        }
3402        else
3403        {
3404            // -----------------------------------------------
3405            //  determine all other normal form which contain
3406            //  the monomial  node->mon
3407            //  replace for  node->mon  its normal form
3408            // -----------------------------------------------
3409
3410            while( search!=(spectrumPolyNode*)NULL )
3411            {
3412                    if( search->nf!=(poly)NULL )
3413                {
3414                    f = search->nf;
3415
3416                    do
3417                    {
3418                        // --------------------------------
3419                        //  look for  (*node)->mon  in   f
3420                        // --------------------------------
3421
3422                        cmp = pCmp( (*node)->mon,f );
3423
3424                        if( cmp<0 )
3425                        {
3426                            f = pNext( f );
3427                        }
3428                        else if( cmp==0 )
3429                        {
3430                            search->nf = pSub( search->nf,
3431                                ppMult_nn( (*node)->nf,pGetCoeff( f ) ) );
3432                            pNorm( search->nf );
3433                        }
3434                    }
3435                    while( cmp<0 && f!=(poly)NULL );
3436                }
3437                search = search->next;
3438            }
3439            delete_node( node );
3440        }
3441
3442    }
3443
3444    // --------------------------------------------------------
3445    //  fast computation exploits the symmetry of the spectrum
3446    // --------------------------------------------------------
3447
3448    if( fast==2 )
3449    {
3450        mu = 2*mu - z;
3451        n  = ( z > 0 ? 2*n - 1 : 2*n );
3452    }
3453
3454    // --------------------------------------------------------
3455    //  compute the spectrum numbers with their multiplicities
3456    // --------------------------------------------------------
3457
3458    intvec            *nom  = new intvec( n );
3459    intvec            *den  = new intvec( n );
3460    intvec            *mult = new intvec( n );
3461
3462    int count         = 0;
3463    int multiplicity  = 1;
3464
3465    for( search=root; search!=(spectrumPolyNode*)NULL &&
3466                     ( fast==0 || search->weight<=smax );
3467                     search=search->next )
3468    {
3469        if( search->next==(spectrumPolyNode*)NULL ||
3470            search->weight<search->next->weight )
3471        {
3472            (*nom) [count] = search->weight.get_num_si( );
3473            (*den) [count] = search->weight.get_den_si( );
3474            (*mult)[count] = multiplicity;
3475
3476            multiplicity=1;
3477            count++;
3478        }
3479        else
3480        {
3481            multiplicity++;
3482        }
3483    }
3484
3485    // --------------------------------------------------------
3486    //  fast computation exploits the symmetry of the spectrum
3487    // --------------------------------------------------------
3488
3489    if( fast==2 )
3490    {
3491        int n1,n2;
3492        for( n1=0, n2=n-1; n1<n2; n1++, n2-- )
3493        {
3494            (*nom) [n2] = pVariables*(*den)[n1]-(*nom)[n1];
3495            (*den) [n2] = (*den)[n1];
3496            (*mult)[n2] = (*mult)[n1];
3497        }
3498    }
3499
3500    // -----------------------------------
3501    //  test if the spectrum is symmetric
3502    // -----------------------------------
3503
3504    if( fast==0 || fast==1 )
3505    {
3506        int symmetric=TRUE;
3507
3508        for( int n1=0, n2=n-1 ; n1<n2 && symmetric==TRUE; n1++, n2-- )
3509        {
3510            if( (*mult)[n1]!=(*mult)[n2] ||
3511                (*den) [n1]!= (*den)[n2] ||
3512                (*nom)[n1]+(*nom)[n2]!=pVariables*(*den) [n1] )
3513            {
3514                symmetric = FALSE;
3515            }
3516        }
3517
3518        if( symmetric==FALSE )
3519        {
3520            // ---------------------------------------------
3521            //  the spectrum is not symmetric => degenerate
3522            //  principal part
3523            // ---------------------------------------------
3524
3525            *L = (lists)omAllocBin( slists_bin);
3526            (*L)->Init( 1 );
3527            (*L)->m[0].rtyp = INT_CMD;    //  milnor number
3528            (*L)->m[0].data = (void*)mu;
3529
3530            return spectrumDegenerate;
3531        }
3532    }
3533
3534    *L = (lists)omAllocBin( slists_bin);
3535
3536    (*L)->Init( 6 );
3537
3538    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
3539    (*L)->m[1].rtyp = INT_CMD;    //  geometrical genus
3540    (*L)->m[2].rtyp = INT_CMD;    //  number of spectrum values
3541    (*L)->m[3].rtyp = INTVEC_CMD; //  nominators
3542    (*L)->m[4].rtyp = INTVEC_CMD; //  denomiantors
3543    (*L)->m[5].rtyp = INTVEC_CMD; //  multiplicities
3544
3545    (*L)->m[0].data = (void*)mu;
3546    (*L)->m[1].data = (void*)pg;
3547    (*L)->m[2].data = (void*)n;
3548    (*L)->m[3].data = (void*)nom;
3549    (*L)->m[4].data = (void*)den;
3550    (*L)->m[5].data = (void*)mult;
3551
3552    return  spectrumOK;
3553}
3554
3555#endif
3556
3557//from mpr_inout.cc
3558extern void nPrint(number n);
3559
3560BOOLEAN loNewtonP( leftv res, leftv arg1 )
3561{
3562  res->data= (void*)loNewtonPolytope( (ideal)arg1->Data() );
3563  return FALSE;
3564}
3565
3566BOOLEAN loSimplex( leftv res, leftv args )
3567{
3568  if ( !(rField_is_long_R()) )
3569  {
3570    WerrorS("Ground field not implemented!");
3571    return TRUE;
3572  }
3573
3574  simplex * LP;
3575  matrix m;
3576
3577  leftv v= args;
3578  if ( v->Typ() != MATRIX_CMD ) // 1: matrix
3579    return TRUE;
3580  else
3581    m= (matrix)(v->CopyD());
3582
3583  LP = new simplex(MATROWS(m),MATCOLS(m));
3584  LP->mapFromMatrix(m);
3585
3586  v= v->next;
3587  if ( v->Typ() != INT_CMD )    // 2: m = number of constraints
3588    return TRUE;
3589  else
3590    LP->m= (int)(long)(v->Data());
3591
3592  v= v->next;
3593  if ( v->Typ() != INT_CMD )    // 3: n = number of variables
3594    return TRUE;
3595  else
3596    LP->n= (int)(long)(v->Data());
3597
3598  v= v->next;
3599  if ( v->Typ() != INT_CMD )    // 4: m1 = number of <= constraints
3600    return TRUE;
3601  else
3602    LP->m1= (int)(long)(v->Data());
3603
3604  v= v->next;
3605  if ( v->Typ() != INT_CMD )    // 5: m2 = number of >= constraints
3606    return TRUE;
3607  else
3608    LP->m2= (int)(long)(v->Data());
3609
3610  v= v->next;
3611  if ( v->Typ() != INT_CMD )    // 6: m3 = number of == constraints
3612    return TRUE;
3613  else
3614    LP->m3= (int)(long)(v->Data());
3615
3616#ifdef mprDEBUG_PROT
3617  Print("m (constraints) %d\n",LP->m);
3618  Print("n (columns) %d\n",LP->n);
3619  Print("m1 (<=) %d\n",LP->m1);
3620  Print("m2 (>=) %d\n",LP->m2);
3621  Print("m3 (==) %d\n",LP->m3);
3622#endif
3623
3624  LP->compute();
3625
3626  lists lres= (lists)omAlloc( sizeof(slists) );
3627  lres->Init( 6 );
3628
3629  lres->m[0].rtyp= MATRIX_CMD; // output matrix
3630  lres->m[0].data=(void*)LP->mapToMatrix(m);
3631
3632  lres->m[1].rtyp= INT_CMD;   // found a solution?
3633  lres->m[1].data=(void*)LP->icase;
3634
3635  lres->m[2].rtyp= INTVEC_CMD;
3636  lres->m[2].data=(void*)LP->posvToIV();
3637
3638  lres->m[3].rtyp= INTVEC_CMD;
3639  lres->m[3].data=(void*)LP->zrovToIV();
3640
3641  lres->m[4].rtyp= INT_CMD;
3642  lres->m[4].data=(void*)LP->m;
3643
3644  lres->m[5].rtyp= INT_CMD;
3645  lres->m[5].data=(void*)LP->n;
3646
3647  res->data= (void*)lres;
3648
3649  return FALSE;
3650}
3651
3652BOOLEAN nuMPResMat( leftv res, leftv arg1, leftv arg2 )
3653{
3654  ideal gls = (ideal)(arg1->Data());
3655  int imtype= (int)(long)arg2->Data();
3656
3657  uResultant::resMatType mtype= determineMType( imtype );
3658
3659  // check input ideal ( = polynomial system )
3660  if ( mprIdealCheck( gls, arg1->Name(), mtype, true ) != mprOk )
3661  {
3662    return TRUE;
3663  }
3664
3665  uResultant *resMat= new uResultant( gls, mtype, false );
3666
3667  res->rtyp = MODUL_CMD;
3668  res->data= (void*)resMat->accessResMat()->getMatrix();
3669
3670  delete resMat;
3671
3672  return FALSE;
3673}
3674
3675BOOLEAN nuLagSolve( leftv res, leftv arg1, leftv arg2, leftv arg3 )
3676{
3677
3678  poly gls;
3679  gls= (poly)(arg1->Data());
3680  int howclean= (int)(long)arg3->Data();
3681
3682  if ( !(rField_is_R() ||
3683         rField_is_Q() ||
3684         rField_is_long_R() ||
3685         rField_is_long_C()) )
3686  {
3687    WerrorS("Ground field not implemented!");
3688    return TRUE;
3689  }
3690
3691  if ( !(rField_is_R()||rField_is_long_R()||rField_is_long_C()) )
3692  {
3693    unsigned long int ii = (unsigned long int)arg2->Data();
3694    setGMPFloatDigits( ii, ii );
3695  }
3696
3697  if ( gls == NULL || pIsConstant( gls ) )
3698  {
3699    WerrorS("Input polynomial is constant!");
3700    return TRUE;
3701  }
3702
3703  int ldummy;
3704  int deg= pLDeg( gls, &ldummy, currRing );
3705  //  int deg= pDeg( gls );
3706  int len= pLength( gls );
3707  int i,vpos;
3708  poly piter;
3709  lists elist;
3710  lists rlist;
3711
3712  elist= (lists)omAlloc( sizeof(slists) );
3713  elist->Init( 0 );
3714
3715  if ( pVariables > 1 )
3716  {
3717    piter= gls;
3718    for ( i= 1; i <= pVariables; i++ )
3719      if ( pGetExp( piter, i ) )
3720      {
3721        vpos= i;
3722        break;
3723      }
3724    while ( piter )
3725    {
3726      for ( i= 1; i <= pVariables; i++ )
3727        if ( (vpos != i) && (pGetExp( piter, i ) != 0) )
3728        {
3729          WerrorS("The input polynomial must be univariate!");
3730          return TRUE;
3731        }
3732      pIter( piter );
3733    }
3734  }
3735
3736  rootContainer * roots= new rootContainer();
3737  number * pcoeffs= (number *)omAlloc( (deg+1) * sizeof( number ) );
3738  piter= gls;
3739  for ( i= deg; i >= 0; i-- )
3740  {
3741    //if ( piter ) Print("deg %d, pDeg(piter) %d\n",i,pTotaldegree(piter));
3742    if ( piter && pTotaldegree(piter) == i )
3743    {
3744      pcoeffs[i]= nCopy( pGetCoeff( piter ) );
3745      //nPrint( pcoeffs[i] );PrintS("  ");
3746      pIter( piter );
3747    }
3748    else
3749    {
3750      pcoeffs[i]= nInit(0);
3751    }
3752  }
3753
3754#ifdef mprDEBUG_PROT
3755  for (i=deg; i >= 0; i--)
3756  {
3757    nPrint( pcoeffs[i] );PrintS("  ");
3758  }
3759  PrintLn();
3760#endif
3761
3762  roots->fillContainer( pcoeffs, NULL, 1, deg, rootContainer::onepoly, 1 );
3763  roots->solver( howclean );
3764
3765  int elem= roots->getAnzRoots();
3766  char *out;
3767  char *dummy;
3768  int j;
3769
3770  rlist= (lists)omAlloc( sizeof(slists) );
3771  rlist->Init( elem );
3772
3773  if (rField_is_long_C())
3774  {
3775    for ( j= 0; j < elem; j++ )
3776    {
3777      rlist->m[j].rtyp=NUMBER_CMD;
3778      rlist->m[j].data=(void *)nCopy((number)(roots->getRoot(j)));
3779      //rlist->m[j].data=(void *)(number)(roots->getRoot(j));
3780    }
3781  }
3782  else
3783  {
3784    for ( j= 0; j < elem; j++ )
3785    {
3786      dummy = complexToStr( (*roots)[j], gmp_output_digits );
3787      rlist->m[j].rtyp=STRING_CMD;
3788      rlist->m[j].data=(void *)dummy;
3789    }
3790  }
3791
3792  elist->Clean();
3793  //omFreeSize( (ADDRESS) elist, sizeof(slists) );
3794
3795  // this is (via fillContainer) the same data as in root
3796  //for ( i= deg; i >= 0; i-- ) nDelete( &pcoeffs[i] );
3797  //omFreeSize( (ADDRESS) pcoeffs, (deg+1) * sizeof( number ) );
3798
3799  delete roots;
3800
3801  res->rtyp= LIST_CMD;
3802  res->data= (void*)rlist;
3803
3804  return FALSE;
3805}
3806
3807BOOLEAN nuVanderSys( leftv res, leftv arg1, leftv arg2, leftv arg3)
3808{
3809  int i;
3810  ideal p,w;
3811  p= (ideal)arg1->Data();
3812  w= (ideal)arg2->Data();
3813
3814  // w[0] = f(p^0)
3815  // w[1] = f(p^1)
3816  // ...
3817  // p can be a vector of numbers (multivariate polynom)
3818  //   or one number (univariate polynom)
3819  // tdg = deg(f)
3820
3821  int n= IDELEMS( p );
3822  int m= IDELEMS( w );
3823  int tdg= (int)(long)arg3->Data();
3824
3825  res->data= (void*)NULL;
3826
3827  // check the input
3828  if ( tdg < 1 )
3829  {
3830    WerrorS("Last input parameter must be > 0!");
3831    return TRUE;
3832  }
3833  if ( n != pVariables )
3834  {
3835    Werror("Size of first input ideal must be equal to %d!",pVariables);
3836    return TRUE;
3837  }
3838  if ( m != (int)pow((double)tdg+1,(double)n) )
3839  {
3840    Werror("Size of second input ideal must be equal to %d!",
3841      (int)pow((double)tdg+1,(double)n));
3842    return TRUE;
3843  }
3844  if ( !(rField_is_Q() /* ||
3845         rField_is_R() || rField_is_long_R() ||
3846         rField_is_long_C()*/ ) )
3847         {
3848    WerrorS("Ground field not implemented!");
3849    return TRUE;
3850  }
3851
3852  number tmp;
3853  number *pevpoint= (number *)omAlloc( n * sizeof( number ) );
3854  for ( i= 0; i < n; i++ )
3855  {
3856    pevpoint[i]=nInit(0);
3857    if (  (p->m)[i] )
3858    {
3859      tmp = pGetCoeff( (p->m)[i] );
3860      if ( nIsZero(tmp) || nIsOne(tmp) || nIsMOne(tmp) )
3861      {
3862        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3863        WerrorS("Elements of first input ideal must not be equal to -1, 0, 1!");
3864        return TRUE;
3865      }
3866    } else tmp= NULL;
3867    if ( !nIsZero(tmp) )
3868    {
3869      if ( !pIsConstant((p->m)[i]))
3870      {
3871        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3872        WerrorS("Elements of first input ideal must be numbers!");
3873        return TRUE;
3874      }
3875      pevpoint[i]= nCopy( tmp );
3876    }
3877  }
3878
3879  number *wresults= (number *)omAlloc( m * sizeof( number ) );
3880  for ( i= 0; i < m; i++ )
3881  {
3882    wresults[i]= nInit(0);
3883    if ( (w->m)[i] && !nIsZero(pGetCoeff((w->m)[i])) )
3884    {
3885      if ( !pIsConstant((w->m)[i]))
3886      {
3887        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3888        omFreeSize( (ADDRESS)wresults, m * sizeof( number ) );
3889        WerrorS("Elements of second input ideal must be numbers!");
3890        return TRUE;
3891      }
3892      wresults[i]= nCopy(pGetCoeff((w->m)[i]));
3893    }
3894  }
3895
3896  vandermonde vm( m, n, tdg, pevpoint, FALSE );
3897  number *ncpoly= vm.interpolateDense( wresults );
3898  // do not free ncpoly[]!!
3899  poly rpoly= vm.numvec2poly( ncpoly );
3900
3901  omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3902  omFreeSize( (ADDRESS)wresults, m * sizeof( number ) );
3903
3904  res->data= (void*)rpoly;
3905  return FALSE;
3906}
3907
3908BOOLEAN nuUResSolve( leftv res, leftv args )
3909{
3910  leftv v= args;
3911
3912  ideal gls;
3913  int imtype;
3914  int howclean;
3915
3916  // get ideal
3917  if ( v->Typ() != IDEAL_CMD )
3918    return TRUE;
3919  else gls= (ideal)(v->Data());
3920  v= v->next;
3921
3922  // get resultant matrix type to use (0,1)
3923  if ( v->Typ() != INT_CMD )
3924    return TRUE;
3925  else imtype= (int)(long)v->Data();
3926  v= v->next;
3927
3928  if (imtype==0)
3929  {
3930    ideal test_id=idInit(1,1);
3931    int j;
3932    for(j=IDELEMS(gls)-1;j>=0;j--)
3933    {
3934      if (gls->m[j]!=NULL)
3935      {
3936        test_id->m[0]=gls->m[j];
3937        intvec *dummy_w=idQHomWeight(test_id);
3938        if (dummy_w!=NULL)
3939        {
3940          WerrorS("Newton polytope not of expected dimension");
3941          delete dummy_w;
3942          return TRUE;
3943        }
3944      }
3945    }
3946  }
3947
3948  // get and set precision in digits ( > 0 )
3949  if ( v->Typ() != INT_CMD )
3950    return TRUE;
3951  else if ( !(rField_is_R()||rField_is_long_R()||rField_is_long_C()) )
3952  {
3953    unsigned long int ii=(unsigned long int)v->Data();
3954    setGMPFloatDigits( ii, ii );
3955  }
3956  v= v->next;
3957
3958  // get interpolation steps (0,1,2)
3959  if ( v->Typ() != INT_CMD )
3960    return TRUE;
3961  else howclean= (int)(long)v->Data();
3962
3963  uResultant::resMatType mtype= determineMType( imtype );
3964  int i,c,count;
3965  lists listofroots= NULL;
3966  lists emptylist;
3967  number smv= NULL;
3968  BOOLEAN interpolate_det= (mtype==uResultant::denseResMat)?TRUE:FALSE;
3969
3970  //emptylist= (lists)omAlloc( sizeof(slists) );
3971  //emptylist->Init( 0 );
3972
3973  //res->rtyp = LIST_CMD;
3974  //res->data= (void *)emptylist;
3975
3976  // check input ideal ( = polynomial system )
3977  if ( mprIdealCheck( gls, args->Name(), mtype ) != mprOk )
3978  {
3979    return TRUE;
3980  }
3981
3982  uResultant * ures;
3983  rootContainer ** iproots;
3984  rootContainer ** muiproots;
3985  rootArranger * arranger;
3986
3987  // main task 1: setup of resultant matrix
3988  ures= new uResultant( gls, mtype );
3989  if ( ures->accessResMat()->initState() != resMatrixBase::ready )
3990  {
3991    WerrorS("Error occurred during matrix setup!");
3992    return TRUE;
3993  }
3994
3995  // if dense resultant, check if minor nonsingular
3996  if ( mtype == uResultant::denseResMat )
3997  {
3998    smv= ures->accessResMat()->getSubDet();
3999#ifdef mprDEBUG_PROT
4000    PrintS("// Determinant of submatrix: ");nPrint(smv);PrintLn();
4001#endif
4002    if ( nIsZero(smv) )
4003    {
4004      WerrorS("Unsuitable input ideal: Minor of resultant matrix is singular!");
4005      return TRUE;
4006    }
4007  }
4008
4009  // main task 2: Interpolate specialized resultant polynomials
4010  if ( interpolate_det )
4011    iproots= ures->interpolateDenseSP( false, smv );
4012  else
4013    iproots= ures->specializeInU( false, smv );
4014
4015  // main task 3: Interpolate specialized resultant polynomials
4016  if ( interpolate_det )
4017    muiproots= ures->interpolateDenseSP( true, smv );
4018  else
4019    muiproots= ures->specializeInU( true, smv );
4020
4021#ifdef mprDEBUG_PROT
4022  c= iproots[0]->getAnzElems();
4023  for (i=0; i < c; i++) pWrite(iproots[i]->getPoly());
4024  c= muiproots[0]->getAnzElems();
4025  for (i=0; i < c; i++) pWrite(muiproots[i]->getPoly());
4026#endif
4027
4028  // main task 4: Compute roots of specialized polys and match them up
4029  arranger= new rootArranger( iproots, muiproots, howclean );
4030  arranger->solve_all();
4031
4032  // get list of roots
4033  if ( arranger->success() )
4034  {
4035    arranger->arrange();
4036    listofroots= arranger->listOfRoots( gmp_output_digits );
4037  }
4038  else
4039  {
4040    WerrorS("Solver was unable to find any roots!");
4041    return TRUE;
4042  }
4043
4044  // free everything
4045  count= iproots[0]->getAnzElems();
4046  for (i=0; i < count; i++) delete iproots[i];
4047  omFreeSize( (ADDRESS) iproots, count * sizeof(rootContainer*) );
4048  count= muiproots[0]->getAnzElems();
4049  for (i=0; i < count; i++) delete muiproots[i];
4050  omFreeSize( (ADDRESS) muiproots, count * sizeof(rootContainer*) );
4051
4052  delete ures;
4053  delete arranger;
4054  nDelete( &smv );
4055
4056  res->data= (void *)listofroots;
4057
4058  //emptylist->Clean();
4059  //  omFreeSize( (ADDRESS) emptylist, sizeof(slists) );
4060
4061  return FALSE;
4062}
4063
4064// from mpr_numeric.cc
4065lists rootArranger::listOfRoots( const unsigned int oprec )
4066{
4067  int i,j,tr;
4068  int count= roots[0]->getAnzRoots(); // number of roots
4069  int elem= roots[0]->getAnzElems();  // number of koordinates per root
4070
4071  lists listofroots= (lists)omAlloc( sizeof(slists) ); // must be done this way!
4072
4073  if ( found_roots )
4074  {
4075    listofroots->Init( count );
4076
4077    for (i=0; i < count; i++)
4078    {
4079      lists onepoint= (lists)omAlloc(sizeof(slists)); // must be done this way!
4080      onepoint->Init(elem);
4081      for ( j= 0; j < elem; j++ )
4082      {
4083        if ( !rField_is_long_C() )
4084        {
4085          onepoint->m[j].rtyp=STRING_CMD;
4086          onepoint->m[j].data=(void *)complexToStr((*roots[j])[i],oprec);
4087        }
4088        else
4089        {
4090          onepoint->m[j].rtyp=NUMBER_CMD;
4091          onepoint->m[j].data=(void *)nCopy((number)(roots[j]->getRoot(i)));
4092        }
4093        onepoint->m[j].next= NULL;
4094        onepoint->m[j].name= NULL;
4095      }
4096      listofroots->m[i].rtyp=LIST_CMD;
4097      listofroots->m[i].data=(void *)onepoint;
4098      listofroots->m[j].next= NULL;
4099      listofroots->m[j].name= NULL;
4100    }
4101
4102  }
4103  else
4104  {
4105    listofroots->Init( 0 );
4106  }
4107
4108  return listofroots;
4109}
4110
4111#ifdef PDEBUG
4112
4113#if (OM_TRACK > 2) && defined(OM_TRACK_CUSTOM)
4114
4115void p_SetRingOfPoly(poly p, ring r)
4116{
4117  while (p != NULL)
4118  {
4119    p_SetRingOfLm(p, r);
4120    pIter(p);
4121  }
4122}
4123
4124void p_SetRingOfIdeal(ideal id, ring r)
4125{
4126  if (id == NULL) return;
4127
4128  int i, n = id->ncols*id->nrows;
4129
4130  for (i=0; i<n; i++)
4131  {
4132    p_SetRingOfPoly(id->m[i], r);
4133  }
4134}
4135
4136void p_SetRingOfList(lists L, ring r)
4137{
4138  int i;
4139  for (i=0; i<L->nr; i++)
4140  {
4141    p_SetRingOfLeftv(&(L->m[i]), r);
4142  }
4143}
4144
4145void p_SetRingOfCommand(command cmd, ring r)
4146{
4147  if (cmd->op == PROC_CMD && cmd->argc == 2)
4148    p_SetRingOfLeftv(&(cmd->arg2), r);
4149  else if (cmd->argc > 0)
4150  {
4151    p_SetRingOfLeftv(&(cmd->arg1), r);
4152    if (cmd->argc > 1)
4153    {
4154      p_SetRingOfLeftv(&(cmd->arg2), r);
4155      if (cmd->argc > 2)
4156        p_SetRingOfLeftv(&(cmd->arg3), r);
4157    }
4158  }
4159}
4160
4161void p_SetRingOfLeftv(leftv l, ring r)
4162{
4163  while (l != NULL)
4164  {
4165    switch(l->rtyp)
4166    {
4167        case POLY_CMD:
4168        case VECTOR_CMD:
4169          p_SetRingOfPoly((poly) l->data, r);
4170      break;
4171
4172      case IDEAL_CMD:
4173      case MODUL_CMD:
4174      case MATRIX_CMD:
4175      case MAP_CMD:
4176        p_SetRingOfIdeal((ideal) l->data, r);
4177        break;
4178
4179        case LIST_CMD:
4180          p_SetRingOfList((lists) l->data, r);
4181          break;
4182
4183        case COMMAND:
4184          p_SetRingOfCommand((command)l->data, r);
4185        default:
4186          break;
4187    }
4188    l = l->next;
4189  }
4190}
4191#endif // (OM_TRACK > 2) && defined(OM_TRACK_CUSTOM)
4192
4193#endif // PDEBUG
4194
4195// from ring.cc
4196void rSetHdl(idhdl h)
4197{
4198  int i;
4199  ring rg = NULL;
4200  if (h!=NULL)
4201  {
4202//   Print(" new ring:%s (l:%d)\n",IDID(h),IDLEV(h));
4203    rg = IDRING(h);
4204    omCheckAddrSize((ADDRESS)h,sizeof(idrec));
4205    if (IDID(h))  // OB: ????
4206      omCheckAddr((ADDRESS)IDID(h));
4207    rTest(rg);
4208  }
4209
4210  // clean up history
4211  if (sLastPrinted.RingDependend())
4212  {
4213    sLastPrinted.CleanUp();
4214    memset(&sLastPrinted,0,sizeof(sleftv));
4215  }
4216
4217   /*------------ change the global ring -----------------------*/
4218  rChangeCurrRing(rg);
4219  currRingHdl = h;
4220}
4221
4222BOOLEAN rSleftvOrdering2Ordering(sleftv *ord, ring R)
4223{
4224  int last = 0, o=0, n = 1, i=0, typ = 1, j;
4225  sleftv *sl = ord;
4226
4227  // determine nBlocks
4228  while (sl!=NULL)
4229  {
4230    intvec *iv = (intvec *)(sl->data);
4231    if (((*iv)[1]==ringorder_c)||((*iv)[1]==ringorder_C))
4232      i++;
4233    else if ((*iv)[1]==ringorder_L)
4234    {
4235      R->bitmask=(*iv)[2];
4236      n--;
4237    }
4238    else if (((*iv)[1]!=ringorder_a)
4239    && ((*iv)[1]!=ringorder_a64))
4240      o++;
4241    n++;
4242    sl=sl->next;
4243  }
4244  // check whether at least one real ordering
4245  if (o==0)
4246  {
4247    WerrorS("invalid combination of orderings");
4248    return TRUE;
4249  }
4250  // if no c/C ordering is given, increment n
4251  if (i==0) n++;
4252  else if (i != 1)
4253  {
4254    // throw error if more than one is given
4255    WerrorS("more than one ordering c/C specified");
4256    return TRUE;
4257  }
4258
4259  // initialize fields of R
4260  R->order=(int *)omAlloc0(n*sizeof(int));
4261  R->block0=(int *)omAlloc0(n*sizeof(int));
4262  R->block1=(int *)omAlloc0(n*sizeof(int));
4263  R->wvhdl=(int**)omAlloc0(n*sizeof(int_ptr));
4264
4265  // init order, so that rBlocks works correctly
4266  for (j=0; j < n-1; j++)
4267    R->order[j] = (int) ringorder_unspec;
4268  // set last _C order, if no c/C order was given
4269  if (i == 0) R->order[n-2] = ringorder_C;
4270
4271  /* init orders */
4272  sl=ord;
4273  n=-1;
4274  while (sl!=NULL)
4275  {
4276    intvec *iv;
4277    iv = (intvec *)(sl->data);
4278    if ((*iv)[1]!=ringorder_L)
4279    {
4280      n++;
4281
4282      /* the format of an ordering:
4283       *  iv[0]: factor
4284       *  iv[1]: ordering
4285       *  iv[2..end]: weights
4286       */
4287      R->order[n] = (*iv)[1];
4288      switch ((*iv)[1])
4289      {
4290          case ringorder_ws:
4291          case ringorder_Ws:
4292            typ=-1;
4293          case ringorder_wp:
4294          case ringorder_Wp:
4295            R->wvhdl[n]=(int*)omAlloc((iv->length()-1)*sizeof(int));
4296            for (i=2; i<iv->length(); i++)
4297              R->wvhdl[n][i-2] = (*iv)[i];
4298            R->block0[n] = last+1;
4299            last += iv->length()-2;
4300            R->block1[n] = last;
4301            break;
4302          case ringorder_ls:
4303          case ringorder_ds:
4304          case ringorder_Ds:
4305            typ=-1;
4306          case ringorder_lp:
4307          case ringorder_dp:
4308          case ringorder_Dp:
4309          case ringorder_rp:
4310            R->block0[n] = last+1;
4311            if (iv->length() == 3) last+=(*iv)[2];
4312            else last += (*iv)[0];
4313            R->block1[n] = last;
4314            if (R->block0[n]>R->block1[n]) return TRUE;
4315            if (rCheckIV(iv)) return TRUE;
4316            break;
4317          case ringorder_S:
4318          case ringorder_c:
4319          case ringorder_C:
4320            if (rCheckIV(iv)) return TRUE;
4321            break;
4322          case ringorder_aa:
4323          case ringorder_a:
4324            R->block0[n] = last+1;
4325            R->block1[n] = si_min(last+iv->length()-2 , R->N);
4326            R->wvhdl[n] = (int*)omAlloc((iv->length()-1)*sizeof(int));
4327            for (i=2; i<iv->length(); i++)
4328            {
4329              R->wvhdl[n][i-2]=(*iv)[i];
4330              if ((*iv)[i]<0) typ=-1;
4331            }
4332            break;
4333          case ringorder_a64:
4334          {
4335            R->block0[n] = last+1;
4336            R->block1[n] = si_min(last+iv->length()-2 , R->N);
4337            R->wvhdl[n] = (int*)omAlloc((iv->length()-1)*sizeof(int64));
4338            int64 *w=(int64 *)R->wvhdl[n];
4339            for (i=2; i<iv->length(); i++)
4340            {
4341              w[i-2]=(*iv)[i];
4342              if ((*iv)[i]<0) typ=-1;
4343            }
4344            break;
4345          }
4346          case ringorder_M:
4347          {
4348            int Mtyp=rTypeOfMatrixOrder(iv);
4349            if (Mtyp==0) return TRUE;
4350            if (Mtyp==-1) typ = -1;
4351
4352            R->wvhdl[n] =( int *)omAlloc((iv->length()-1)*sizeof(int));
4353            for (i=2; i<iv->length();i++)
4354              R->wvhdl[n][i-2]=(*iv)[i];
4355
4356            R->block0[n] = last+1;
4357            last += (int)sqrt((double)(iv->length()-2));
4358            R->block1[n] = last;
4359            break;
4360          }
4361
4362          case ringorder_no:
4363            R->order[n] = ringorder_unspec;
4364            return TRUE;
4365
4366          default:
4367            Werror("Internal Error: Unknown ordering %d", (*iv)[1]);
4368            R->order[n] = ringorder_unspec;
4369            return TRUE;
4370      }
4371    }
4372    sl=sl->next;
4373  }
4374
4375  // check for complete coverage
4376  if ((R->order[n]==ringorder_c) ||  (R->order[n]==ringorder_C)) n--;
4377  if (R->block1[n] != R->N)
4378  {
4379    if (((R->order[n]==ringorder_dp) ||
4380         (R->order[n]==ringorder_ds) ||
4381         (R->order[n]==ringorder_Dp) ||
4382         (R->order[n]==ringorder_Ds) ||
4383         (R->order[n]==ringorder_rp) ||
4384         (R->order[n]==ringorder_lp) ||
4385         (R->order[n]==ringorder_ls))
4386        &&
4387        R->block0[n] <= R->N)
4388    {
4389      R->block1[n] = R->N;
4390    }
4391    else
4392    {
4393      Werror("mismatch of number of vars (%d) and ordering (%d vars)",
4394             R->N,R->block1[n]);
4395      return TRUE;
4396    }
4397  }
4398  R->OrdSgn = typ;
4399  return FALSE;
4400}
4401
4402BOOLEAN rSleftvList2StringArray(sleftv* sl, char** p)
4403{
4404
4405  while(sl!=NULL)
4406  {
4407    if (sl->Name() == sNoName)
4408    {
4409      if (sl->Typ()==POLY_CMD)
4410      {
4411        sleftv s_sl;
4412        iiConvert(POLY_CMD,ANY_TYPE,-1,sl,&s_sl);
4413        if (s_sl.Name() != sNoName)
4414          *p = omStrDup(s_sl.Name());
4415        else
4416          *p = NULL;
4417        sl->next = s_sl.next;
4418        s_sl.next = NULL;
4419        s_sl.CleanUp();
4420        if (*p == NULL) return TRUE;
4421      }
4422      else
4423        return TRUE;
4424    }
4425    else
4426      *p = omStrDup(sl->Name());
4427    p++;
4428    sl=sl->next;
4429  }
4430  return FALSE;
4431}
4432
4433////////////////////
4434//
4435// rInit itself:
4436//
4437// INPUT:  s: name, pn: ch & parameter (names), rv: variable (names)
4438//         ord: ordering
4439// RETURN: currRingHdl on success
4440//         NULL        on error
4441// NOTE:   * makes new ring to current ring, on success
4442//         * considers input sleftv's as read-only
4443//idhdl rInit(char *s, sleftv* pn, sleftv* rv, sleftv* ord)
4444ring rInit(sleftv* pn, sleftv* rv, sleftv* ord)
4445{
4446  int ch;
4447#ifdef HAVE_RING2TOM
4448  int cring = 0;
4449#endif
4450  int float_len=0;
4451  int float_len2=0;
4452  ring R = NULL;
4453  idhdl tmp = NULL;
4454  BOOLEAN ffChar=FALSE;
4455  int typ = 1;
4456
4457  /* ch -------------------------------------------------------*/
4458  // get ch of ground field
4459  int numberOfAllocatedBlocks;
4460
4461  if (pn->Typ()==INT_CMD)
4462  {
4463    ch=(int)(long)pn->Data();
4464  }
4465  else if ((pn->name != NULL)
4466  && ((strcmp(pn->name,"real")==0) || (strcmp(pn->name,"complex")==0)))
4467  {
4468    BOOLEAN complex_flag=(strcmp(pn->name,"complex")==0);
4469    ch=-1;
4470    if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4471    {
4472      float_len=(int)(long)pn->next->Data();
4473      float_len2=float_len;
4474      pn=pn->next;
4475      if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4476      {
4477        float_len2=(int)(long)pn->next->Data();
4478        pn=pn->next;
4479      }
4480    }
4481    if ((pn->next==NULL) && complex_flag)
4482    {
4483      pn->next=(leftv)omAlloc0Bin(sleftv_bin);
4484      pn->next->name=omStrDup("i");
4485    }
4486  }
4487  else
4488  {
4489    Werror("Wrong ground field specification");
4490    goto rInitError;
4491  }
4492  pn=pn->next;
4493
4494  int l, last;
4495  sleftv * sl;
4496  /*every entry in the new ring is initialized to 0*/
4497
4498  /* characteristic -----------------------------------------------*/
4499  /* input: 0 ch=0 : Q     parameter=NULL    ffChar=FALSE   float_len
4500   *         0    1 : Q(a,...)        *names         FALSE
4501   *         0   -1 : R               NULL           FALSE  0
4502   *         0   -1 : R               NULL           FALSE  prec. >6
4503   *         0   -1 : C               *names         FALSE  prec. 0..?
4504   *         p    p : Fp              NULL           FALSE
4505   *         p   -p : Fp(a)           *names         FALSE
4506   *         q    q : GF(q=p^n)       *names         TRUE
4507  */
4508  if (ch!=-1)
4509  {
4510    int l = 0;
4511
4512    if (((ch!=0) && (ch<2))
4513    #ifndef NV_OPS
4514    || (ch > 32003)
4515    #endif
4516    )
4517    {
4518      Warn("%d is invalid characteristic of ground field. 32003 is used.", ch);
4519      ch=32003;
4520    }
4521    // load fftable, if necessary
4522    if (pn!=NULL)
4523    {
4524      while ((ch!=fftable[l]) && (fftable[l])) l++;
4525      if (fftable[l]==0) ch = IsPrime(ch);
4526      else
4527      {
4528        char *m[1]={(char *)sNoName};
4529        nfSetChar(ch,m);
4530        if (errorreported) goto rInitError;
4531        else ffChar=TRUE;
4532      }
4533    }
4534    else
4535    {
4536#ifdef HAVE_RING2TOM
4537      int blupp = Is2toM(ch);
4538      if (blupp != 0)
4539      {
4540        cring = 1; // Use Z/2^ch
4541        ch = blupp;
4542        Print("Beta: using Z/2^%d", ch);
4543        PrintLn();
4544      }
4545      else
4546#endif
4547        ch = IsPrime(ch);
4548    }
4549  }
4550  // allocated ring and set ch
4551  R = (ring) omAlloc0Bin(sip_sring_bin);
4552  R->ch = ch;
4553#ifdef HAVE_RING2TOM
4554  R->cring = cring;
4555#endif
4556  if (ch == -1)
4557  {
4558    R->float_len= si_min(float_len,32767);
4559    R->float_len2= si_min(float_len2,32767);
4560  }
4561
4562  /* parameter -------------------------------------------------------*/
4563  if (pn!=NULL)
4564  {
4565    R->P=pn->listLength();
4566    //if ((ffChar|| (ch == 1)) && (R->P > 1))
4567    if ((R->P > 1) && (ffChar || (ch == -1)))
4568    {
4569      WerrorS("too many parameters");
4570      goto rInitError;
4571    }
4572    R->parameter=(char**)omAlloc0(R->P*sizeof(char_ptr));
4573    if (rSleftvList2StringArray(pn, R->parameter))
4574    {
4575      WerrorS("parameter expected");
4576      goto rInitError;
4577    }
4578    if (ch>1 && !ffChar) R->ch=-ch;
4579    else if (ch==0) R->ch=1;
4580  }
4581  else if (ffChar)
4582  {
4583    WerrorS("need one parameter");
4584    goto rInitError;
4585  }
4586  /* post-processing of field description */
4587  // we have short reals, but no short complex
4588  if ((R->ch == - 1)
4589  && (R->parameter !=NULL)
4590  && (R->float_len < SHORT_REAL_LENGTH))
4591  {
4592    R->float_len = SHORT_REAL_LENGTH;
4593    R->float_len2 = SHORT_REAL_LENGTH;
4594  }
4595
4596  /* names and number of variables-------------------------------------*/
4597  {
4598    int l=rv->listLength();
4599#if SIZEOF_SHORT == 2
4600#define MAX_SHORT 0x7fff
4601#endif
4602    if (l>MAX_SHORT)
4603    {
4604      Werror("too many ring variables(%d), max is %d",l,MAX_SHORT);
4605       goto rInitError;
4606    }
4607    R->N = l; /*rv->listLength();*/
4608  }
4609  R->names   = (char **)omAlloc0(R->N * sizeof(char_ptr));
4610  if (rSleftvList2StringArray(rv, R->names))
4611  {
4612    WerrorS("name of ring variable expected");
4613    goto rInitError;
4614  }
4615
4616  /* check names and parameters for conflicts ------------------------- */
4617  {
4618    int i,j;
4619    for(i=0;i<R->P; i++)
4620    {
4621      for(j=0;j<R->N;j++)
4622      {
4623        if (strcmp(R->parameter[i],R->names[j])==0)
4624        {
4625          Werror("parameter %d conflicts with variable %d",i+1,j+1);
4626          goto rInitError;
4627        }
4628      }
4629    }
4630  }
4631  rNameCheck(R);
4632  /* ordering -------------------------------------------------------------*/
4633  if (rSleftvOrdering2Ordering(ord, R))
4634    goto rInitError;
4635
4636  // Complete the initialization
4637  if (rComplete(R,1))
4638    goto rInitError;
4639
4640  rTest(R);
4641
4642  // try to enter the ring into the name list
4643  // need to clean up sleftv here, before this ring can be set to
4644  // new currRing or currRing can be killed beacuse new ring has
4645  // same name
4646  if (pn != NULL) pn->CleanUp();
4647  if (rv != NULL) rv->CleanUp();
4648  if (ord != NULL) ord->CleanUp();
4649  //if ((tmp = enterid(s, myynest, RING_CMD, &IDROOT))==NULL)
4650  //  goto rInitError;
4651
4652  //memcpy(IDRING(tmp),R,sizeof(*R));
4653  // set current ring
4654  //omFreeBin(R,  ip_sring_bin);
4655  //return tmp;
4656  return R;
4657
4658  // error case:
4659  rInitError:
4660  if  (R != NULL) rDelete(R);
4661  if (pn != NULL) pn->CleanUp();
4662  if (rv != NULL) rv->CleanUp();
4663  if (ord != NULL) ord->CleanUp();
4664  return NULL;
4665}
4666
4667void rKill(ring r)
4668{
4669  if ((r->ref<=0)&&(r->order!=NULL))
4670  {
4671#ifdef RDEBUG
4672    if (traceit &TRACE_SHOW_RINGS) Print("kill ring %x\n",r);
4673#endif
4674    if (r==currRing)
4675    {
4676      if (r->qideal!=NULL)
4677      {
4678        idDelete(&r->qideal);
4679        r->qideal=NULL;
4680        currQuotient=NULL;
4681      }
4682      if (ppNoether!=NULL) pDelete(&ppNoether);
4683      if (sLastPrinted.RingDependend())
4684      {
4685        sLastPrinted.CleanUp();
4686      }
4687      if ((myynest>0) && (iiRETURNEXPR[myynest].RingDependend()))
4688      {
4689        WerrorS("return value depends on local ring variable (export missing ?)");
4690        iiRETURNEXPR[myynest].CleanUp();
4691      }
4692      currRing=NULL;
4693      currRingHdl=NULL;
4694    }
4695    else if (r->qideal!=NULL)
4696    {
4697      id_Delete(&r->qideal, r);
4698      r->qideal = NULL;
4699    }
4700    int i=1;
4701    int j;
4702    int *pi=r->order;
4703#ifdef USE_IILOCALRING
4704    for (j=0;j<iiRETURNEXPR_len;j++)
4705    {
4706      if (iiLocalRing[j]==r)
4707      {
4708        if (j<myynest) Warn("killing the basering for level %d",j);
4709        iiLocalRing[j]=NULL;
4710      }
4711    }
4712#else /* USE_IILOCALRING */
4713//#endif /* USE_IILOCALRING */
4714    {
4715      proclevel * nshdl = procstack;
4716      int lev=myynest-1;
4717
4718      for(; nshdl != NULL; nshdl = nshdl->next)
4719      {
4720        if (nshdl->cRing==r)
4721        {
4722          Warn("killing the basering for level %d",lev);
4723          nshdl->cRing=NULL;
4724          nshdl->cRingHdl=NULL;
4725        }
4726      }
4727    }
4728#endif /* USE_IILOCALRING */
4729
4730    /* nKillChar(r); will be called from inside of rDelete */
4731    rDelete(r);
4732    return;
4733  }
4734  r->ref--;
4735}
4736
4737void rKill(idhdl h)
4738{
4739  ring r = IDRING(h);
4740  int ref=0;
4741  if (r!=NULL)
4742  {
4743    ref=r->ref;
4744    rKill(r);
4745  }
4746  if (h==currRingHdl)
4747  {
4748    if (ref<=0) { currRing=NULL; currRingHdl=NULL;}
4749    else
4750    {
4751      currRingHdl=rFindHdl(r,currRingHdl,NULL);
4752    }
4753  }
4754}
4755
4756idhdl rSimpleFindHdl(ring r, idhdl root, idhdl n=NULL)
4757{
4758  //idhdl next_best=NULL;
4759  idhdl h=root;
4760  while (h!=NULL)
4761  {
4762    if (((IDTYP(h)==RING_CMD)||(IDTYP(h)==QRING_CMD))
4763    && (h!=n)
4764    && (IDRING(h)==r)
4765    )
4766    {
4767   //   if (IDLEV(h)==myynest)
4768   //     return h;
4769   //   if ((IDLEV(h)==0) || (next_best==NULL))
4770   //     next_best=h;
4771   //   else if (IDLEV(next_best)<IDLEV(h))
4772   //     next_best=h;
4773      return h;
4774    }
4775    h=IDNEXT(h);
4776  }
4777  //return next_best;
4778  return NULL;
4779}
Note: See TracBrowser for help on using the repository browser.