source: git/Singular/ipshell.cc @ 8f63da5

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