source: git/Singular/ipshell.cc @ 84a6a7

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