source: git/Singular/ipshell.cc @ 925a4b9

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