source: git/Singular/ipshell.cc @ bf5ca41

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