source: git/Singular/ipshell.cc @ 178d03

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