Code coverage tests

This page documents the degree to which the PARI/GP source code is tested by our public test suite, distributed with the source distribution in directory src/test/. This is measured by the gcov utility; we then process gcov output using the lcov frond-end.

We test a few variants depending on Configure flags on the pari.math.u-bordeaux.fr machine (x86_64 architecture), and agregate them in the final report:

The target is to exceed 90% coverage for all mathematical modules (given that branches depending on DEBUGLEVEL or DEBUGMEM are not covered). This script is run to produce the results below.

LCOV - code coverage report
Current view: top level - language - es.c (source / functions) Coverage Total Hit
Test: PARI/GP v2.18.1 lcov report (development 31041-bd73e9fcdd) Lines: 73.1 % 2797 2046
Test Date: 2026-07-22 22:45:42 Functions: 81.3 % 310 252
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Copyright (C) 2000  The PARI group.
       2              : 
       3              : This file is part of the PARI/GP package.
       4              : 
       5              : PARI/GP is free software; you can redistribute it and/or modify it under the
       6              : terms of the GNU General Public License as published by the Free Software
       7              : Foundation; either version 2 of the License, or (at your option) any later
       8              : version. It is distributed in the hope that it will be useful, but WITHOUT
       9              : ANY WARRANTY WHATSOEVER.
      10              : 
      11              : Check the License for details. You should have received a copy of it, along
      12              : with the package; see the file 'COPYING'. If not, write to the Free Software
      13              : Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
      14              : 
      15              : /*******************************************************************/
      16              : /**                                                               **/
      17              : /**                 INPUT/OUTPUT SUBROUTINES                      **/
      18              : /**                                                               **/
      19              : /*******************************************************************/
      20              : #ifdef _WIN32
      21              : #include "../systems/mingw/pwinver.h"
      22              : #include <windows.h>
      23              : #include <process.h> /* for getpid */
      24              : #include <fcntl.h>
      25              : #include <io.h>      /* for setmode */
      26              : #include "../systems/mingw/mingw.h"
      27              : #endif
      28              : #include "paricfg.h"
      29              : #ifdef HAS_STAT
      30              : #include <sys/stat.h>
      31              : #elif defined(HAS_OPENDIR)
      32              : #include <dirent.h>
      33              : #endif
      34              : #ifdef HAS_WAITPID
      35              : #  include <sys/wait.h>
      36              : #endif
      37              : 
      38              : #include "pari.h"
      39              : #include "paripriv.h"
      40              : #include "anal.h"
      41              : #ifdef __EMSCRIPTEN__
      42              : #include "../systems/emscripten/emscripten.h"
      43              : #endif
      44              : 
      45              : #define DEBUGLEVEL DEBUGLEVEL_io
      46              : 
      47              : typedef void (*OUT_FUN)(GEN, pariout_t *, pari_str *);
      48              : 
      49              : static void bruti_sign(GEN g, pariout_t *T, pari_str *S, int addsign);
      50              : static void matbruti(GEN g, pariout_t *T, pari_str *S);
      51              : static void texi_sign(GEN g, pariout_t *T, pari_str *S, int addsign);
      52              : 
      53              : static void
      54      1191259 : bruti(GEN g, pariout_t *T, pari_str *S) { bruti_sign(g,T,S,1); }
      55              : static void
      56          319 : texi(GEN g, pariout_t *T, pari_str *S) { texi_sign(g,T,S,1); }
      57              : 
      58              : void
      59            0 : pari_ask_confirm(const char *s)
      60              : {
      61            0 :   if (!cb_pari_ask_confirm)
      62            0 :     pari_err(e_MISC,"Can't ask for confirmation. Please define cb_pari_ask_confirm()");
      63            0 :   cb_pari_ask_confirm(s);
      64            0 : }
      65              : 
      66              : static char *
      67            0 : strip_last_nl(char *s)
      68              : {
      69            0 :   ulong l = strlen(s);
      70              :   char *t;
      71            0 :   if (l && s[l-1] != '\n') return s;
      72            0 :   if (l>1 && s[l-2] == '\r') l--;
      73            0 :   t = stack_malloc(l); memcpy(t, s, l-1); t[l-1] = 0;
      74            0 :   return t;
      75              : }
      76              : 
      77              : /********************************************************************/
      78              : /**                                                                **/
      79              : /**                        INPUT FILTER                            **/
      80              : /**                                                                **/
      81              : /********************************************************************/
      82              : #define ONE_LINE_COMMENT   2
      83              : #define MULTI_LINE_COMMENT 1
      84              : #define LBRACE '{'
      85              : #define RBRACE '}'
      86              : 
      87              : static int
      88         2471 : in_help(filtre_t *F)
      89              : {
      90              :   char c;
      91         2471 :   if (!F->buf) return (*F->s == '?');
      92         2464 :   c = *F->buf->buf;
      93         2464 :   return c? (c == '?'): (*F->s == '?');
      94              : }
      95              : /* Filter F->s into F->t */
      96              : static char *
      97      1009423 : filtre0(filtre_t *F)
      98              : {
      99      1009423 :   const char *s = F->s;
     100      1009423 :   char c, *t = F->t;
     101      1009423 :   int doctest = GP_DATA->doctest, more_input = F->more_input;
     102              : 
     103      1009423 :   if (odd(more_input)) F->more_input = 0;
     104      1009423 :   if (doctest && more_input <= 1)
     105              :   {
     106            0 :     int is_doctest = isspace((unsigned char)*s);
     107            0 :     while (isspace((unsigned char)*s)) s++;
     108            0 :     if (*s==0) goto END;
     109            0 :     if (*s=='?' && s[1]==' ') s+=2;
     110            0 :     else if (is_doctest)
     111            0 :       F->in_comment = ONE_LINE_COMMENT;
     112              :   }
     113    253409827 :   while ((c = *s++))
     114              :   {
     115    252401162 :     if (F->in_string)
     116              :     {
     117     30151722 :       *t++ = c; /* copy verbatim */
     118     30151722 :       switch(c)
     119              :       {
     120          666 :         case '\\': /* in strings, \ is the escape character */
     121          666 :           if (*s) *t++ = *s++;
     122          666 :           break;
     123              : 
     124      3822483 :         case '"': F->in_string = 0;
     125              :       }
     126     30151722 :       continue;
     127              :     }
     128              : 
     129    222249440 :     if (F->in_comment)
     130              :     { /* look for comment's end */
     131         8820 :       if (F->in_comment == MULTI_LINE_COMMENT)
     132              :       {
     133        37363 :         while (c != '*' || *s != '/')
     134              :         {
     135        36663 :           if (!*s)
     136              :           {
     137          422 :             if (!F->more_input) F->more_input = 1;
     138          422 :             goto END;
     139              :           }
     140        36241 :           c = *s++;
     141              :         }
     142          700 :         s++;
     143              :       }
     144              :       else
     145       124899 :         while (c != '\n' && *s) c = *s++;
     146         8398 :       F->in_comment = 0;
     147         8398 :       continue;
     148              :     }
     149              : 
     150              :     /* weed out comments and spaces */
     151    222240620 :     if (c=='\\' && *s=='\\') { F->in_comment = ONE_LINE_COMMENT; continue; }
     152    222232922 :     if (isspace((unsigned char)c)) continue;
     153    220134094 :     *t++ = c;
     154    220134094 :     switch(c)
     155              :     {
     156       906414 :       case '/':
     157       906414 :         if (*s == '*') { t--; F->in_comment = MULTI_LINE_COMMENT; }
     158       906414 :         break;
     159              : 
     160         1086 :       case '\\':
     161         1086 :         if (!*s) {
     162            7 :           if (in_help(F)) break; /* '?...\' */
     163            7 :           t--;
     164            7 :           if (!F->more_input) F->more_input = 1;
     165            7 :           goto END;
     166              :         }
     167         1079 :         if (*s == '\r') s++; /* DOS */
     168         1079 :         if (*s == '\n') {
     169          336 :           if (in_help(F)) break; /* '?...\' */
     170          329 :           t--; s++;
     171          329 :           if (!*s)
     172              :           {
     173          329 :             if (!F->more_input) F->more_input = 3;
     174          329 :             goto END;
     175              :           }
     176              :         } /* skip \<CR> */
     177          743 :         break;
     178              : 
     179      3822483 :       case '"': F->in_string = 1;
     180      3822483 :         break;
     181              : 
     182         3589 :       case LBRACE:
     183         3589 :         t--;
     184         3589 :         if (F->wait_for_brace) pari_err(e_MISC,"nested braces are not allowed");
     185         3589 :         F->more_input = 2;
     186         3589 :         F->wait_for_brace = 1;
     187         3589 :         break;
     188              : 
     189         3589 :       case RBRACE:
     190         3589 :         if (!F->wait_for_brace) pari_err(e_MISC,"unexpected closing brace");
     191         3589 :         F->more_input = 0; t--;
     192         3589 :         F->wait_for_brace = 0;
     193         3589 :         break;
     194              :     }
     195              :   }
     196              : 
     197      1008665 :   if (t != F->t) /* non empty input */
     198              :   {
     199       981589 :     c = t[-1]; /* last char */
     200       981589 :     if (c == '=') { if (!in_help(F)) F->more_input = 2; }
     201       979461 :     else if (! F->wait_for_brace) F->more_input = 0;
     202        43514 :     else if (c == RBRACE)       { F->more_input = 0; t--; F->wait_for_brace--;}
     203              :   }
     204              : 
     205        70590 : END:
     206      1009423 :   F->end = t; *t = 0; return F->t;
     207              : }
     208              : #undef ONE_LINE_COMMENT
     209              : #undef MULTI_LINE_COMMENT
     210              : 
     211              : char *
     212        11039 : gp_filter(const char *s)
     213              : {
     214              :   filtre_t T;
     215        11039 :   T.buf = NULL;
     216        11039 :   T.s = s;
     217        11039 :   T.t = (char*)stack_malloc(strlen(s)+1);
     218        11039 :   T.in_string = 0; T.more_input = 0;
     219        11039 :   T.in_comment= 0; T.wait_for_brace = 0;
     220        11039 :   return filtre0(&T);
     221              : }
     222              : 
     223              : void
     224       806552 : init_filtre(filtre_t *F, Buffer *buf)
     225              : {
     226       806552 :   F->buf = buf;
     227       806552 :   F->in_string  = 0;
     228       806552 :   F->in_comment = 0;
     229       806552 : }
     230              : 
     231              : /********************************************************************/
     232              : /**                                                                **/
     233              : /**                        INPUT METHODS                           **/
     234              : /**                                                                **/
     235              : /********************************************************************/
     236              : /* create */
     237              : Buffer *
     238        11267 : new_buffer(void)
     239              : {
     240        11267 :   Buffer *b = (Buffer*) pari_malloc(sizeof(Buffer));
     241        11267 :   b->len = 1024;
     242        11267 :   b->buf = (char*)pari_malloc(b->len);
     243        11267 :   return b;
     244              : }
     245              : /* delete */
     246              : void
     247        11267 : delete_buffer(Buffer *b)
     248              : {
     249        11267 :   if (!b) return;
     250        11267 :   pari_free((void*)b->buf); pari_free((void*)b);
     251              : }
     252              : /* resize */
     253              : void
     254         7420 : fix_buffer(Buffer *b, long newlbuf)
     255              : {
     256         7420 :   b->len = newlbuf;
     257         7420 :   pari_realloc_ip((void**)&b->buf, b->len);
     258         7420 : }
     259              : 
     260              : static int
     261       804589 : gp_read_stream_buf(FILE *fi, Buffer *b)
     262              : {
     263              :   input_method IM;
     264              :   filtre_t F;
     265              : 
     266       804589 :   init_filtre(&F, b);
     267              : 
     268       804589 :   IM.file = (void*)fi;
     269       804589 :   IM.myfgets = (fgets_t)&fgets;
     270       804589 :   IM.getline = &file_input;
     271       804589 :   IM.free = 0;
     272       804589 :   return input_loop(&F,&IM);
     273              : }
     274              : 
     275              : GEN
     276         8887 : gp_read_stream(FILE *fi)
     277              : {
     278         8887 :   Buffer *b = new_buffer();
     279         8887 :   GEN x = NULL;
     280         8887 :   while (gp_read_stream_buf(fi, b))
     281              :   {
     282         8887 :     if (*(b->buf)) { x = readseq(b->buf); break; }
     283              :   }
     284         8887 :   delete_buffer(b); return x;
     285              : }
     286              : 
     287              : static GEN
     288            0 : gp_read_from_input(input_method* IM, int loop, char *last)
     289              : {
     290            0 :   Buffer *b = new_buffer();
     291            0 :   GEN x = NULL;
     292              :   filtre_t F;
     293            0 :   if (last) *last = 0;
     294              :   for (;;)
     295            0 :   {
     296              :     char *s;
     297            0 :     init_filtre(&F, b);
     298            0 :     if (!input_loop(&F, IM)) break;
     299            0 :     s = b->buf;
     300            0 :     if (s[0])
     301              :     {
     302            0 :       if (gp_meta(s,0)) continue;
     303            0 :       x = closure_evalres(pari_compile_str(s));
     304            0 :       if (last) *last = s[strlen(s) - 1];
     305              :     }
     306            0 :     if (!loop) break;
     307              :   }
     308            0 :   delete_buffer(b);
     309            0 :   return x;
     310              : }
     311              : 
     312              : GEN
     313           19 : gp_read_file(const char *s)
     314              : {
     315           19 :   GEN x = gnil;
     316           19 :   FILE *f = switchin(s);
     317           12 :   if (file_is_binary(f))
     318              :   {
     319           12 :     x = readbin(s,f, NULL);
     320           12 :     if (!x) pari_err_FILE("input file",s);
     321              :   }
     322              :   else {
     323            0 :     pari_sp av = avma;
     324            0 :     Buffer *b = new_buffer();
     325            0 :     x = gnil;
     326              :     for (;;) {
     327            0 :       if (!gp_read_stream_buf(f, b)) break;
     328            0 :       if (!strcmp(b->buf,"\\qf")) break;
     329            0 :       if (*(b->buf)) { set_avma(av); x = readseq(b->buf); }
     330              :     }
     331            0 :     delete_buffer(b);
     332              :   }
     333           12 :   popinfile(); return x;
     334              : }
     335              : 
     336              : static char*
     337            0 : string_gets(char *s, int size, const char **ptr)
     338              : {
     339              :   /* f is actually a const char** */
     340            0 :   const char *in = *ptr;
     341              :   int i;
     342              :   char c;
     343              : 
     344              :   /* Copy from in to s */
     345            0 :   for (i = 0; i+1 < size && in[i] != 0;)
     346              :   {
     347            0 :     s[i] = c = in[i]; i++;
     348            0 :     if (c == '\n') break;
     349              :   }
     350            0 :   s[i] = 0;  /* Terminating 0 byte */
     351            0 :   if (i == 0) return NULL;
     352              : 
     353            0 :   *ptr += i;
     354            0 :   return s;
     355              : }
     356              : 
     357              : GEN
     358            0 : gp_read_str_multiline(const char *s, char *last)
     359              : {
     360              :   input_method IM;
     361            0 :   const char *ptr = s;
     362              :   GEN z;
     363              : 
     364            0 :   IM.file = (void*)(&ptr);
     365            0 :   IM.myfgets = (fgets_t)&string_gets;
     366            0 :   IM.getline = &file_input;
     367            0 :   IM.free = 0;
     368              : 
     369            0 :   z = gp_read_from_input(&IM, 1, last);
     370            0 :   return z ? z: gnil;
     371              : }
     372              : 
     373              : static void
     374            0 : gp_read_str_history(const char *s)
     375              : {
     376              :   input_method IM;
     377            0 :   const char *ptr = s;
     378            0 :   char last = 0;
     379            0 :   pari_sp av = avma;
     380            0 :   IM.file = (void*)(&ptr);
     381            0 :   IM.myfgets = (fgets_t)&string_gets;
     382            0 :   IM.getline = &file_input;
     383            0 :   IM.free = 0;
     384            0 :   for(;ptr[0];)
     385              :   {
     386              :     GEN z;
     387            0 :     timer_start(GP_DATA->T);
     388            0 :     walltimer_start(GP_DATA->Tw);
     389            0 :     pari_set_last_newline(1);
     390            0 :     z = gp_read_from_input(&IM, 0, &last);
     391            0 :     pari_alarm(0);
     392            0 :     if (!pari_last_was_newline()) pari_putc('\n');
     393            0 :     if (z)
     394              :     {
     395            0 :       long t = timer_delay(GP_DATA->T);
     396            0 :       long r = walltimer_delay(GP_DATA->Tw);
     397            0 :       if (t && GP_DATA->chrono)
     398              :       {
     399            0 :         if (pari_mt_nbthreads==1)
     400              :         {
     401            0 :           pari_puts("time = ");
     402            0 :           pari_puts(gp_format_time(t));
     403              :         }
     404              :         else
     405              :         {
     406            0 :           pari_puts("cpu time = ");
     407            0 :           pari_puts(gp_format_time(t));
     408            0 :           pari_puts(", real time = ");
     409            0 :           pari_puts(gp_format_time(r));
     410              :         }
     411            0 :         pari_puts(".\n");
     412              :       }
     413            0 :       if (GP_DATA->simplify) z = simplify_shallow(z);
     414            0 :       pari_add_hist(z, t, r);
     415            0 :       if (z != gnil && last!=';')
     416            0 :         gp_display_hist(pari_nb_hist());
     417              :     }
     418            0 :     set_avma(av);
     419            0 :     parivstack_reset();
     420              :   }
     421            0 : }
     422              : 
     423              : void
     424            0 : gp_embedded_init(long rsize, long vsize)
     425              : {
     426            0 :   pari_init(rsize, 1UL<<20);
     427            0 :   paristack_setsize(rsize, vsize);
     428            0 : }
     429              : 
     430              : long
     431            0 : gp_embedded(const char *s)
     432              : {
     433            0 :   long err = 0;
     434              :   struct gp_context state;
     435            0 :   gp_context_save(&state);
     436            0 :   timer_start(GP_DATA->T);
     437            0 :   timer_start(GP_DATA->Tw);
     438            0 :   pari_set_last_newline(1);
     439            0 :   pari_CATCH(CATCH_ALL)
     440              :   {
     441            0 :     pari_err_display(pari_err_last());
     442            0 :     err_printf("\n");
     443            0 :     gp_context_restore(&state);
     444            0 :     err = 1;
     445              :   } pari_TRY {
     446            0 :     gp_read_str_history(s);
     447            0 :   } pari_ENDCATCH;
     448            0 :   if (!pari_last_was_newline()) pari_putc('\n');
     449            0 :   set_avma(pari_mainstack->top);
     450            0 :   return err;
     451              : }
     452              : 
     453              : GEN
     454          305 : gp_readvec_stream(FILE *fi)
     455              : {
     456          305 :   pari_sp ltop = avma;
     457          305 :   Buffer *b = new_buffer();
     458          305 :   long i = 1, n = 16;
     459          305 :   GEN z = cgetg(n+1,t_VEC);
     460              :   for(;;)
     461              :   {
     462       795646 :     if (!gp_read_stream_buf(fi, b)) break;
     463       795341 :     if (!*(b->buf)) continue;
     464       795341 :     if (i>n)
     465              :     {
     466         2149 :       if (DEBUGLEVEL) err_printf("gp_readvec_stream: reaching %ld entries\n",n);
     467         2149 :       n <<= 1;
     468         2149 :       z = vec_lengthen(z,n);
     469              :     }
     470       795341 :     gel(z,i++) = readseq(b->buf);
     471              :   }
     472          305 :   if (DEBUGLEVEL) err_printf("gp_readvec_stream: found %ld entries\n",i-1);
     473          305 :   setlg(z,i); delete_buffer(b);
     474          305 :   return gc_GEN(ltop,z);
     475              : }
     476              : 
     477              : GEN
     478            4 : gp_readvec_file(const char *s)
     479              : {
     480            4 :   GEN x = NULL;
     481            4 :   FILE *f = switchin(s);
     482            4 :   if (file_is_binary(f)) {
     483              :     int junk;
     484            0 :     x = readbin(s,f,&junk);
     485            0 :     if (!x) pari_err_FILE("input file",s);
     486              :   } else
     487            4 :     x = gp_readvec_stream(f);
     488            4 :   popinfile(); return x;
     489              : }
     490              : 
     491              : char *
     492      1000666 : file_getline(Buffer *b, char **s0, input_method *IM)
     493              : {
     494      1000666 :   const ulong MAX = (1UL << 31) - 1;
     495              :   ulong used0, used;
     496              : 
     497      1000666 :   **s0 = 0; /* paranoia */
     498      1000666 :   used0 = used = *s0 - b->buf;
     499              :   for(;;)
     500         7007 :   {
     501      1007673 :     ulong left = b->len - used, l, read;
     502              :     char *s;
     503              : 
     504              :     /* If little space left, double the buffer size before next read. */
     505      1007673 :     if (left < 512)
     506              :     {
     507         7406 :       fix_buffer(b, b->len << 1);
     508         7406 :       left = b->len - used;
     509         7406 :       *s0 = b->buf + used0;
     510              :     }
     511              :     /* # of chars read by fgets is an int; be careful */
     512      1007673 :     read = minuu(left, MAX);
     513      1007673 :     s = b->buf + used;
     514      1007673 :     if (! IM->myfgets(s, (int)read, IM->file)) return **s0? *s0: NULL; /* EOF */
     515              : 
     516      1005455 :     l = strlen(s);
     517      1005455 :     if (l+1 < read || s[l-1] == '\n') return *s0; /* \n */
     518         7007 :     used += l;
     519              :   }
     520              : }
     521              : 
     522              : /* Read from file (up to '\n' or EOF) and copy at s0 (points in b->buf) */
     523              : char *
     524      1000590 : file_input(char **s0, int junk, input_method *IM, filtre_t *F)
     525              : {
     526              :   (void)junk;
     527      1000590 :   return file_getline(F->buf, s0, IM);
     528              : }
     529              : 
     530              : static void
     531         2206 : runaway_close(filtre_t *F)
     532              : {
     533         2206 :   if (F->in_string)
     534              :   {
     535            0 :     pari_warn(warner,"run-away string. Closing it");
     536            0 :     F->in_string = 0;
     537              :   }
     538         2206 :   if (F->in_comment)
     539              :   {
     540            0 :     pari_warn(warner,"run-away comment. Closing it");
     541            0 :     F->in_comment = 0;
     542              :   }
     543         2206 : }
     544              : /* Read a "complete line" and filter it. Return: 0 if EOF, 1 otherwise */
     545              : int
     546       951028 : input_loop(filtre_t *F, input_method *IM)
     547              : {
     548       951028 :   Buffer *b = (Buffer*)F->buf;
     549       951028 :   char *to_read, *s = b->buf;
     550              : 
     551              :   /* read first line */
     552       951028 :   if (! (to_read = IM->getline(&s,1, IM, F)) ) { runaway_close(F); return 0; }
     553              : 
     554              :   /* buffer is not empty, init filter */
     555       948822 :   F->in_string = 0;
     556       948822 :   F->more_input= 0;
     557       948822 :   F->wait_for_brace = 0;
     558              :   for(;;)
     559              :   {
     560       998384 :     if (GP_DATA->echo == 2) gp_echo_and_log("", strip_last_nl(to_read));
     561       998384 :     F->s = to_read;
     562       998384 :     F->t = s;
     563       998384 :     (void)filtre0(F); /* pre-processing of line, read by previous call to IM->getline */
     564       998384 :     if (IM->free) pari_free(to_read);
     565       998384 :     if (! F->more_input) break;
     566              : 
     567              :     /* read continuation line */
     568        49562 :     s = F->end;
     569        49562 :     to_read = IM->getline(&s,0, IM, F);
     570        49562 :     if (!to_read)
     571              :     {
     572            0 :       if (!*(b->buf)) runaway_close(F);
     573            0 :       break;
     574              :     }
     575              :   }
     576       948822 :   return 1;
     577              : }
     578              : 
     579              : /********************************************************************/
     580              : /**                                                                **/
     581              : /**                  GENERAL PURPOSE PRINTING                      **/
     582              : /**                                                                **/
     583              : /********************************************************************/
     584              : PariOUT *pariOut, *pariErr;
     585              : static void
     586       311491 : _fputs(const char *s, FILE *f ) {
     587              : #ifdef _WIN32
     588              :    win32_ansi_fputs(s, f);
     589              : #else
     590       311491 :   fputs(s, f);
     591              : #endif
     592       311491 : }
     593              : static void
     594     10854086 : _putc_log(char c) { if (pari_logfile) (void)putc(c, pari_logfile); }
     595              : static void
     596       311491 : _puts_log(const char *s)
     597              : {
     598       311491 :   FILE *f = pari_logfile;
     599              :   const char *p;
     600       311491 :   if (!f) return;
     601           90 :   if (pari_logstyle != logstyle_color)
     602          108 :     while ( (p = strchr(s, '\x1b')) )
     603              :     { /* skip ANSI color escape sequence */
     604           18 :       if ( p!=s ) fwrite(s, 1, p-s, f);
     605           18 :       s = strchr(p, 'm');
     606           18 :       if (!s) return;
     607           18 :       s++;
     608              :     }
     609           90 :   fputs(s, f);
     610              : }
     611              : static void
     612       261132 : _flush_log(void)
     613       261132 : { if (pari_logfile != NULL) (void)fflush(pari_logfile); }
     614              : 
     615              : static void
     616     10229330 : normalOutC(char c) { putc(c, pari_outfile); _putc_log(c); }
     617              : static void
     618           93 : normalOutS(const char *s) { _fputs(s, pari_outfile); _puts_log(s); }
     619              : static void
     620       219978 : normalOutF(void) { fflush(pari_outfile); _flush_log(); }
     621              : static PariOUT defaultOut = {normalOutC, normalOutS, normalOutF};
     622              : 
     623              : static void
     624       624756 : normalErrC(char c) { putc(c, pari_errfile); _putc_log(c); }
     625              : static void
     626       311398 : normalErrS(const char *s) { _fputs(s, pari_errfile); _puts_log(s); }
     627              : static void
     628        41154 : normalErrF(void) { fflush(pari_errfile); _flush_log(); }
     629              : static PariOUT defaultErr = {normalErrC, normalErrS, normalErrF};
     630              : 
     631              : /**                         GENERIC PRINTING                       **/
     632              : void
     633         1895 : resetout(int initerr)
     634              : {
     635         1895 :   pariOut = &defaultOut;
     636         1895 :   if (initerr) pariErr = &defaultErr;
     637         1895 : }
     638              : void
     639         1895 : initout(int initerr)
     640              : {
     641         1895 :   pari_infile = stdin;
     642         1895 :   pari_outfile = stdout;
     643         1895 :   pari_errfile = stderr;
     644         1895 :   resetout(initerr);
     645         1895 : }
     646              : 
     647              : static int last_was_newline = 1;
     648              : 
     649              : static void
     650      1164147 : set_last_newline(char c) { last_was_newline = (c == '\n'); }
     651              : 
     652              : void
     653       731216 : out_putc(PariOUT *out, char c) { set_last_newline(c); out->putch(c); }
     654              : void
     655       104877 : pari_putc(char c) { out_putc(pariOut, c); }
     656              : 
     657              : void
     658       435612 : out_puts(PariOUT *out, const char *s) {
     659       435612 :   if (*s) { set_last_newline(s[strlen(s)-1]); out->puts(s); }
     660       435612 : }
     661              : void
     662        62465 : pari_puts(const char *s) { out_puts(pariOut, s); }
     663              : 
     664              : int
     665       122635 : pari_last_was_newline(void) { return last_was_newline; }
     666              : void
     667       151103 : pari_set_last_newline(int last) { last_was_newline = last; }
     668              : 
     669              : void
     670       205939 : pari_flush(void) { pariOut->flush(); }
     671              : 
     672              : void
     673            0 : err_flush(void) { pariErr->flush(); }
     674              : 
     675              : static GEN
     676           12 : log10_2(void)
     677           12 : { return divrr(mplog2(LOWDEFAULTPREC), mplog(utor(10,LOWDEFAULTPREC))); }
     678              : 
     679              : /* e binary exponent, return exponent in base ten */
     680              : static long
     681       177729 : ex10(long e) {
     682              :   pari_sp av;
     683              :   GEN z;
     684       177729 :   if (e >= 0) {
     685       172454 :     if (e < 1e15) return (long)(e*LOG10_2);
     686            6 :     av = avma; z = mulur(e, log10_2());
     687            6 :     z = floorr(z); e = itos(z);
     688              :   }
     689              :   else /* e < 0 */
     690              :   {
     691         5275 :     if (e > -1e15) return (long)(-(-e*LOG10_2)-1);
     692            6 :     av = avma; z = mulsr(e, log10_2());
     693            6 :     z = floorr(z); e = itos(z) - 1;
     694              :   }
     695           12 :   return gc_long(av, e);
     696              : }
     697              : 
     698              : static char *
     699        23408 : zeros(char *b, long nb) { while (nb-- > 0) *b++ = '0'; *b = 0; return b; }
     700              : 
     701              : /* # of decimal digits, assume l > 0 */
     702              : static long
     703       770045 : numdig(ulong l)
     704              : {
     705       770045 :   if (l < 100000)
     706              :   {
     707       720276 :     if (l < 100)    return (l < 10)? 1: 2;
     708       323830 :     if (l < 10000)  return (l < 1000)? 3: 4;
     709       121450 :     return 5;
     710              :   }
     711        49769 :   if (l < 10000000)   return (l < 1000000)? 6: 7;
     712        17879 :   if (l < 1000000000) return (l < 100000000)? 8: 9;
     713            0 :   return 10;
     714              : }
     715              : 
     716              : /* let ndig <= 9, x < 10^ndig, write in p[-ndig..-1] the decimal digits of x */
     717              : static void
     718      1167420 : utodec(char *p, ulong x, long ndig)
     719              : {
     720      1167420 :   switch(ndig)
     721              :   {
     722       404940 :     case  9: *--p = x % 10 + '0'; x = x/10;
     723       415254 :     case  8: *--p = x % 10 + '0'; x = x/10;
     724       429676 :     case  7: *--p = x % 10 + '0'; x = x/10;
     725       447144 :     case  6: *--p = x % 10 + '0'; x = x/10;
     726       568594 :     case  5: *--p = x % 10 + '0'; x = x/10;
     727       661521 :     case  4: *--p = x % 10 + '0'; x = x/10;
     728       770974 :     case  3: *--p = x % 10 + '0'; x = x/10;
     729       907560 :     case  2: *--p = x % 10 + '0'; x = x/10;
     730      1167420 :     case  1: *--p = x % 10 + '0'; x = x/10;
     731              :   }
     732      1167420 : }
     733              : 
     734              : /* convert abs(x) != 0 to str. Prepend '-' if (sx < 0) */
     735              : static char *
     736       770045 : itostr_sign(GEN x, int sx, long *len)
     737              : {
     738              :   long l, d;
     739       770045 :   ulong *res = convi(x, &l);
     740              :   /* l 9-digits words (< 10^9) + (optional) sign + \0 */
     741       770045 :   char *s = (char*)new_chunk(nchar2nlong(l*9 + 1 + 1)), *t = s;
     742              : 
     743       770045 :   if (sx < 0) *t++ = '-';
     744       770045 :   d = numdig(*--res); t += d; utodec(t, *res, d);
     745      1167420 :   while (--l > 0) { t += 9; utodec(t, *--res, 9); }
     746       770045 :   *t = 0; *len = t - s; return s;
     747              : }
     748              : 
     749              : /********************************************************************/
     750              : /**                                                                **/
     751              : /**                        WRITE A REAL NUMBER                     **/
     752              : /**                                                                **/
     753              : /********************************************************************/
     754              : /* 19 digits (if 64 bits, at most 2^60-1) + 1 sign */
     755              : static const long MAX_EXPO_LEN = 20;
     756              : 
     757              : /* write z to buf, inserting '.' at 'point', 0 < point < strlen(z) */
     758              : static void
     759       160464 : wr_dec(char *buf, char *z, long point)
     760              : {
     761       160464 :   char *s = buf + point;
     762       160464 :   strncpy(buf, z, point); /* integer part */
     763       160464 :   *s++ = '.'; z += point;
     764      1281664 :   while ( (*s++ = *z++) ) /* empty */;
     765       160464 : }
     766              : 
     767              : static char *
     768          126 : zerotostr(void)
     769              : {
     770          126 :   char *s = (char*)new_chunk(1);
     771          126 :   s[0] = '0';
     772          126 :   s[1] = 0; return s;
     773              : }
     774              : 
     775              : /* write a real 0 of exponent ex in format f */
     776              : static char *
     777          661 : real0tostr_width_frac(long width_frac)
     778              : {
     779              :   char *buf, *s;
     780          661 :   if (width_frac == 0) return zerotostr();
     781          654 :   buf = s = stack_malloc(width_frac + 3);
     782          654 :   *s++ = '0';
     783          654 :   *s++ = '.';
     784          654 :   (void)zeros(s, width_frac);
     785          654 :   return buf;
     786              : }
     787              : 
     788              : /* write a real 0 of exponent ex */
     789              : static char *
     790         1756 : real0tostr(long ex, char format, char exp_char, long wanted_dec)
     791              : {
     792              :   char *buf, *buf0;
     793              : 
     794         1756 :   if (format == 'f') {
     795            0 :     long width_frac = wanted_dec;
     796            0 :     if (width_frac < 0) width_frac = (ex >= 0)? 0: (long)(-ex * LOG10_2);
     797            0 :     return real0tostr_width_frac(width_frac);
     798              :   } else {
     799         1756 :     buf0 = buf = stack_malloc(3 + MAX_EXPO_LEN + 1);
     800         1756 :     *buf++ = '0';
     801         1756 :     *buf++ = '.';
     802         1756 :     *buf++ = exp_char;
     803         1756 :     sprintf(buf, "%ld", ex10(ex) + 1);
     804              :   }
     805         1756 :   return buf0;
     806              : }
     807              : 
     808              : /* format f, width_frac >= 0: number of digits in fractional part, */
     809              : static char *
     810       142743 : absrtostr_width_frac(GEN x, int width_frac)
     811              : {
     812       142743 :   long beta, ls, point, lx, sx = signe(x);
     813              :   char *s, *buf;
     814              :   GEN z;
     815              : 
     816       142743 :   if (!sx) return real0tostr_width_frac(width_frac);
     817              : 
     818              :   /* x != 0 */
     819       142126 :   lx = realprec(x);
     820       142126 :   beta = width_frac;
     821       142126 :   if (beta) /* >= 0 */
     822              :   { /* z = |x| 10^beta, 10^b = 5^b * 2^b, 2^b goes into exponent */
     823       123988 :     if (beta > 4e9) lx++;
     824       142126 :     z = mulrr(x, rpowuu(5UL, (ulong)beta, lx+1));
     825       142126 :     setsigne(z, 1);
     826       142126 :     shiftr_inplace(z, beta);
     827              :   }
     828              :   else
     829            0 :     z = mpabs(x);
     830       142126 :   z = roundr_safe(z);
     831       142126 :   if (!signe(z)) return real0tostr_width_frac(width_frac);
     832              : 
     833       142082 :   s = itostr_sign(z, 1, &ls); /* ls > 0, number of digits in s */
     834       142082 :   point = ls - beta; /* position of . in s; <= ls, may be < 0 */
     835       142082 :   if (point > 0) /* write integer_part.fractional_part */
     836              :   {
     837              :     /* '.', trailing \0 */
     838       141582 :     buf = stack_malloc( ls + 1+1 );
     839       141582 :     if (ls == point)
     840            0 :       strcpy(buf, s); /* no '.' */
     841              :     else
     842       141582 :       wr_dec(buf, s, point);
     843              :   } else { /* point <= 0, fractional part must be written */
     844              :     char *t;
     845              :     /* '0', '.', zeroes, trailing \0 */
     846          500 :     buf = t = stack_malloc( 1 + 1 - point + ls + 1 );
     847          500 :     *t++ = '0';
     848          500 :     *t++ = '.';
     849          500 :     t = zeros(t, -point);
     850          500 :     strcpy(t, s);
     851              :   }
     852       142082 :   return buf;
     853              : }
     854              : 
     855              : /* Return t_REAL |x| in floating point format.
     856              :  * Allocate freely, the caller must clean the stack.
     857              :  *   FORMAT: E/e (exponential), F/f (floating point), G/g
     858              :  *   wanted_dec: number of significant digits to print (all if < 0).
     859              :  */
     860              : static char *
     861        35021 : absrtostr(GEN x, int sp, char FORMAT, long wanted_dec)
     862              : {
     863        35021 :   const char format = (char)tolower((unsigned char)FORMAT), exp_char = (format == FORMAT)? 'e': 'E';
     864        35021 :   long beta, ls, point, lx, sx = signe(x), ex = expo(x);
     865              :   char *s, *buf, *buf0;
     866              :   GEN z;
     867              : 
     868        35021 :   if (!sx) return real0tostr(ex, format, exp_char, wanted_dec);
     869              : 
     870              :   /* x != 0 */
     871        33265 :   lx = realprec(x);
     872        33265 :   if (wanted_dec >= 0)
     873              :   { /* reduce precision if possible */
     874        33265 :     long w = ndec2prec(wanted_dec); /* digits -> pari precision in words */
     875        33265 :     if (lx > w) lx = w; /* truncature with guard, no rounding */
     876              :   }
     877        33265 :   beta = ex10(lx - ex);
     878        33265 :   if (beta)
     879              :   { /* z = |x| 10^beta, 10^b = 5^b * 2^b, 2^b goes into exponent */
     880        33251 :     if (beta > 0)
     881              :     {
     882        30823 :       if (beta > 18) { lx++; x = rtor(x, lx); }
     883        30823 :       z = mulrr(x, rpowuu(5UL, (ulong)beta, lx+1));
     884              :     }
     885              :     else
     886              :     {
     887         2428 :       if (beta < -18) { lx++; x = rtor(x, lx); }
     888         2428 :       z = divrr(x, rpowuu(5UL, (ulong)-beta, lx+1));
     889              :     }
     890        33251 :     setsigne(z, 1);
     891        33251 :     shiftr_inplace(z, beta);
     892              :   }
     893              :   else
     894           14 :     z = x;
     895        33265 :   z = roundr_safe(z);
     896        33265 :   if (!signe(z)) return real0tostr(ex, format, exp_char, wanted_dec);
     897              : 
     898        33265 :   s = itostr_sign(z, 1, &ls); /* ls > 0, number of digits in s */
     899        33265 :   if (wanted_dec < 0)
     900            0 :     wanted_dec = ls;
     901        33265 :   else if (ls > wanted_dec)
     902              :   {
     903        25026 :     beta -= ls - wanted_dec;
     904        25026 :     ls = wanted_dec;
     905        25026 :     if (s[ls] >= '5') /* round up */
     906              :     {
     907              :       long i;
     908        17997 :       for (i = ls-1; i >= 0; s[i--] = '0')
     909        17990 :         if (++s[i] <= '9') break;
     910        11617 :       if (i < 0) { s[0] = '1'; beta--; }
     911              :     }
     912        25026 :     s[ls] = 0;
     913              :   }
     914              : 
     915              :   /* '.', " E", exponent, trailing \0 */
     916        33265 :   point = ls - beta; /* position of . in s; < 0 or > 0 */
     917        33265 :   if (beta <= 0 || format == 'e' || (format == 'g' && point-1 < -4))
     918              :   { /* e format */
     919         4163 :     buf0 = buf = stack_malloc(ls+1+2+MAX_EXPO_LEN + 1);
     920         4163 :     wr_dec(buf, s, 1); buf += ls + 1;
     921         4163 :     if (sp) *buf++ = ' ';
     922         4163 :     *buf++ = exp_char;
     923         4163 :     sprintf(buf, "%ld", point-1);
     924              :   }
     925        29102 :   else if (point > 0) /* f format, write integer_part.fractional_part */
     926              :   {
     927        14719 :     buf0 = buf = stack_malloc(ls+1 + 1);
     928        14719 :     wr_dec(buf, s, point); /* point < ls since beta > 0 */
     929              :   }
     930              :   else /* f format, point <= 0, write fractional part */
     931              :   {
     932        14383 :     buf0 = buf = stack_malloc(2-point+ls + 1);
     933        14383 :     *buf++ = '0';
     934        14383 :     *buf++ = '.';
     935        14383 :     buf = zeros(buf, -point);
     936        14383 :     strcpy(buf, s);
     937              :   }
     938        33265 :   return buf0;
     939              : }
     940              : 
     941              : /* vsnprintf implementation rewritten from snprintf.c to be found at
     942              :  *
     943              :  * http://www.nersc.gov/~scottc/misc/docs/snort-2.1.1-RC1/snprintf_8c-source.html
     944              :  * The original code was
     945              :  *   Copyright (C) 1998-2002 Martin Roesch <roesch@sourcefire.com>
     946              :  * available under the terms of the GNU GPL version 2 or later. It
     947              :  * was itself adapted from an original version by Patrick Powell. */
     948              : 
     949              : /* Modifications for format %Ps: R.Butel IMB/CNRS 2007/12/03 */
     950              : 
     951              : /* l = old len, L = new len */
     952              : static void
     953         2128 : str_alloc0(pari_str *S, long l, long L)
     954              : {
     955         2128 :   if (S->use_stack)
     956         2100 :     S->string = (char*) memcpy(stack_malloc(L), S->string, l);
     957              :   else
     958           28 :     pari_realloc_ip((void**)&S->string, L);
     959         2128 :   S->cur = S->string + l;
     960         2128 :   S->end = S->string + L;
     961         2128 :   S->size = L;
     962         2128 : }
     963              : /* make sure S is large enough to write l further words (<= l * 20 chars).
     964              :  * To avoid automatic extension in between av = avma / set_avma(av) pairs
     965              :  * [ would destroy S->string if (S->use_stack) ] */
     966              : static void
     967       629404 : str_alloc(pari_str *S, long l)
     968              : {
     969       629404 :   l *= 20;
     970       629404 :   if (S->end - S->cur <= l)
     971         1397 :     str_alloc0(S, S->cur - S->string, S->size + maxss(S->size, l));
     972       629404 : }
     973              : void
     974     16220581 : str_putc(pari_str *S, char c)
     975              : {
     976     16220581 :   *S->cur++ = c;
     977     16220581 :   if (S->cur == S->end) str_alloc0(S, S->size, S->size << 1);
     978     16220581 : }
     979              : 
     980              : void
     981       305959 : str_init(pari_str *S, int use_stack)
     982              : {
     983              :   char *s;
     984       305959 :   S->size = 1024;
     985       305959 :   S->use_stack = use_stack;
     986       305959 :   if (S->use_stack)
     987       213974 :     s = (char*)stack_malloc(S->size);
     988              :   else
     989        91985 :     s = (char*)pari_malloc(S->size);
     990       305957 :   *s = 0;
     991       305957 :   S->string = S->cur = s;
     992       305957 :   S->end = S->string + S->size;
     993       305957 : }
     994              : void
     995     15025474 : str_puts(pari_str *S, const char *s) { while (*s) str_putc(S, *s++); }
     996              : 
     997              : static void
     998       159396 : str_putscut(pari_str *S, const char *s, int cut)
     999              : {
    1000       159396 :   if (cut < 0) str_puts(S, s);
    1001              :   else {
    1002          140 :     while (*s && cut-- > 0) str_putc(S, *s++);
    1003              :   }
    1004       159396 : }
    1005              : 
    1006              : /* lbuf = strlen(buf), len < 0: unset */
    1007              : static void
    1008       289241 : outpad(pari_str *S, const char *buf, long lbuf, int sign, long ljust, long len, long zpad)
    1009              : {
    1010       289241 :   long padlen = len - lbuf;
    1011       289241 :   if (padlen < 0) padlen = 0;
    1012       289241 :   if (ljust) padlen = -padlen;
    1013       289241 :   if (padlen > 0)
    1014              :   {
    1015          357 :     if (zpad) {
    1016           56 :       if (sign) { str_putc(S, sign); --padlen; }
    1017          252 :       while (padlen > 0) { str_putc(S, '0'); --padlen; }
    1018              :     }
    1019              :     else
    1020              :     {
    1021          301 :       if (sign) --padlen;
    1022         1106 :       while (padlen > 0) { str_putc(S, ' '); --padlen; }
    1023          301 :       if (sign) str_putc(S, sign);
    1024              :     }
    1025              :   } else
    1026       288884 :     if (sign) str_putc(S, sign);
    1027       289241 :   str_puts(S, buf);
    1028       289598 :   while (padlen < 0) { str_putc(S, ' '); ++padlen; }
    1029       289241 : }
    1030              : 
    1031              : /* len < 0 or maxwidth < 0: unset */
    1032              : static void
    1033       159395 : fmtstr(pari_str *S, const char *buf, int ljust, int len, int maxwidth)
    1034              : {
    1035       159395 :   int padlen, lbuf = strlen(buf);
    1036              : 
    1037       159395 :   if (maxwidth >= 0 && lbuf > maxwidth) lbuf = maxwidth;
    1038              : 
    1039       159395 :   padlen = len - lbuf;
    1040       159395 :   if (padlen < 0) padlen = 0;
    1041       159395 :   if (ljust) padlen = -padlen;
    1042       159514 :   while (padlen > 0) { str_putc(S, ' '); --padlen; }
    1043       159395 :   str_putscut(S, buf, maxwidth);
    1044       159396 :   while (padlen < 0) { str_putc(S, ' '); ++padlen; }
    1045       159396 : }
    1046              : 
    1047              : /* abs(base) is 8, 10, 16. If base < 0, some "alternate" form
    1048              :  * -- print hex in uppercase
    1049              :  * -- prefix octal with 0
    1050              :  * signvalue = -1: unsigned, otherwise ' ' or '+'. Leaves a messy stack if
    1051              :  * S->use_stack */
    1052              : static void
    1053       146267 : fmtnum(pari_str *S, long lvalue, GEN gvalue, int base, int signvalue,
    1054              :        int ljust, int len, int zpad)
    1055              : {
    1056              :   int caps;
    1057              :   char *buf0, *buf;
    1058              :   long lbuf, mxl;
    1059       146267 :   GEN uvalue = NULL;
    1060       146267 :   ulong ulvalue = 0;
    1061       146267 :   pari_sp av = avma;
    1062              : 
    1063       146267 :   if (gvalue)
    1064              :   {
    1065              :     long s, l;
    1066         2254 :     if (typ(gvalue) != t_INT) {
    1067              :       long i, j, h;
    1068           70 :       l = lg(gvalue);
    1069           70 :       switch(typ(gvalue))
    1070              :       {
    1071           56 :         case t_COMPLEX:
    1072           56 :           fmtnum(S, 0, gel(gvalue,1), base, signvalue, ljust,len,zpad);
    1073           56 :           if (gsigne(gel(gvalue,2)) >= 0) str_putc(S, '+');
    1074           56 :           fmtnum(S, 0, gel(gvalue,2), base, signvalue, ljust,len,zpad);
    1075           56 :           str_putc(S, '*');
    1076           56 :           str_putc(S, 'I');
    1077           56 :           return;
    1078            0 :         case t_VEC:
    1079            0 :           str_putc(S, '[');
    1080            0 :           for (i = 1; i < l; i++)
    1081              :           {
    1082            0 :             fmtnum(S, 0, gel(gvalue,i), base, signvalue, ljust,len,zpad);
    1083            0 :             if (i < l-1) str_putc(S, ',');
    1084              :           }
    1085            0 :           str_putc(S, ']');
    1086            0 :           return;
    1087            0 :         case t_COL:
    1088            0 :           str_putc(S, '[');
    1089            0 :           for (i = 1; i < l; i++)
    1090              :           {
    1091            0 :             fmtnum(S, 0, gel(gvalue,i), base, signvalue, ljust,len,zpad);
    1092            0 :             if (i < l-1) str_putc(S, ',');
    1093              :           }
    1094            0 :           str_putc(S, ']');
    1095            0 :           str_putc(S, '~');
    1096            0 :           return;
    1097           14 :         case t_MAT:
    1098           14 :           if (l == 1)
    1099            0 :             str_puts(S, "[;]");
    1100              :           else
    1101              :           {
    1102           14 :             h = lgcols(gvalue);
    1103           63 :             for (i=1; i<h; i++)
    1104              :             {
    1105           49 :               str_putc(S, '[');
    1106          168 :               for (j=1; j<l; j++)
    1107              :               {
    1108          119 :                 fmtnum(S, 0, gcoeff(gvalue,i,j), base, signvalue, ljust,len,zpad);
    1109          119 :                 if (j<l-1) str_putc(S, ' ');
    1110              :               }
    1111           49 :               str_putc(S, ']');
    1112           49 :               str_putc(S, '\n');
    1113           49 :               if (i<h-1) str_putc(S, '\n');
    1114              :             }
    1115              :           }
    1116           14 :           return;
    1117              :       }
    1118            0 :       gvalue = gfloor( simplify_shallow(gvalue) );
    1119            0 :       if (typ(gvalue) != t_INT)
    1120            0 :         pari_err(e_MISC,"not a t_INT in integer format conversion: %Ps", gvalue);
    1121              :     }
    1122         2184 :     s = signe(gvalue);
    1123         2184 :     if (!s) { lbuf = 1; buf = zerotostr(); signvalue = 0; goto END; }
    1124              : 
    1125         2065 :     l = lgefint(gvalue);
    1126         2065 :     uvalue = gvalue;
    1127         2065 :     if (signvalue < 0)
    1128              :     {
    1129          651 :       if (s < 0) uvalue = addii(int2n(bit_accuracy(l)), gvalue);
    1130          651 :       signvalue = 0;
    1131              :     }
    1132              :     else
    1133              :     {
    1134         1414 :       if (s < 0) { signvalue = '-'; uvalue = absi(uvalue); }
    1135              :     }
    1136         2065 :     mxl = (l-2)* 22 + 1; /* octal at worst; 22 octal chars per 64bit word */
    1137              :   } else {
    1138       144013 :     ulvalue = lvalue;
    1139       144013 :     if (signvalue < 0)
    1140          756 :       signvalue = 0;
    1141              :     else
    1142       143257 :       if (lvalue < 0) { signvalue = '-'; ulvalue = - lvalue; }
    1143       144013 :     mxl = 22 + 1; /* octal at worst; 22 octal chars to write down 2^64 - 1 */
    1144              :   }
    1145       146078 :   if (base > 0) caps = 0; else { caps = 1; base = -base; }
    1146              : 
    1147       146078 :   buf0 = buf = stack_malloc(mxl) + mxl; /* fill from the right */
    1148       146078 :   *--buf = 0; /* trailing \0 */
    1149       146078 :   if (gvalue) {
    1150         2065 :     if (base == 10) {
    1151              :       long i, l, cnt;
    1152         1414 :       ulong *larray = convi(uvalue, &l);
    1153         1414 :       larray -= l;
    1154        10073 :       for (i = 0; i < l; i++) {
    1155         8659 :         cnt = 0;
    1156         8659 :         ulvalue = larray[i];
    1157              :         do {
    1158        66262 :           *--buf = '0' + ulvalue%10;
    1159        66262 :           ulvalue = ulvalue / 10;
    1160        66262 :           cnt++;
    1161        66262 :         } while (ulvalue);
    1162         8659 :         if (i + 1 < l)
    1163         8372 :           for (;cnt<9;cnt++) *--buf = '0';
    1164              :       }
    1165          651 :     } else if (base == 16) {
    1166          651 :       long i, l = lgefint(uvalue);
    1167          651 :       GEN up = int_LSW(uvalue);
    1168         2963 :       for (i = 2; i < l; i++, up = int_nextW(up)) {
    1169         2312 :         ulong ucp = (ulong)*up;
    1170              :         long j;
    1171        29703 :         for (j=0; j < BITS_IN_LONG/4; j++) {
    1172        28042 :           unsigned char cv = ucp & 0xF;
    1173        28042 :           *--buf = (caps? "0123456789ABCDEF":"0123456789abcdef")[cv];
    1174        28042 :           ucp >>= 4;
    1175        28042 :           if (ucp == 0 && i+1 == l) break;
    1176              :         }
    1177              :       } /* loop on hex digits in word */
    1178            0 :     } else if (base == 8) {
    1179            0 :       long i, l = lgefint(uvalue);
    1180            0 :       GEN up = int_LSW(uvalue);
    1181            0 :       ulong rem = 0;
    1182            0 :       int shift = 0;
    1183            0 :       int mask[3] = {0, 1, 3};
    1184            0 :       for (i = 2; i < l; i++, up = int_nextW(up)) {
    1185            0 :         ulong ucp = (ulong)*up;
    1186            0 :         long j, ldispo = BITS_IN_LONG;
    1187            0 :         if (shift) { /* 0, 1 or 2 */
    1188            0 :           unsigned char cv = ((ucp & mask[shift]) <<(3-shift)) + rem;
    1189            0 :           *--buf = "01234567"[cv];
    1190            0 :           ucp >>= shift;
    1191            0 :           ldispo -= shift;
    1192              :         };
    1193            0 :         shift = (shift + 3 - BITS_IN_LONG % 3) % 3;
    1194            0 :         for (j=0; j < BITS_IN_LONG/3; j++) {
    1195            0 :           unsigned char cv = ucp & 0x7;
    1196            0 :           if (ucp == 0 && i+1 == l) { rem = 0; break; };
    1197            0 :           *--buf = "01234567"[cv];
    1198            0 :           ucp >>= 3;
    1199            0 :           ldispo -= 3;
    1200            0 :           rem = ucp;
    1201            0 :           if (ldispo < 3) break;
    1202              :         }
    1203              :       } /* loop on hex digits in word */
    1204            0 :       if (rem) *--buf = "01234567"[rem];
    1205              :     }
    1206              :   } else { /* not a gvalue, thus a standard integer */
    1207              :     do {
    1208       357506 :       *--buf = (caps? "0123456789ABCDEF":"0123456789abcdef")[ulvalue % (unsigned)base ];
    1209       357506 :       ulvalue /= (unsigned)base;
    1210       357506 :     } while (ulvalue);
    1211              :   }
    1212              :   /* leading 0 if octal and alternate # form */
    1213       146078 :   if (caps && base == 8) *--buf = '0';
    1214       146078 :   lbuf = (buf0 - buf) - 1;
    1215       146197 : END:
    1216       146197 :   outpad(S, buf, lbuf, signvalue, ljust, len, zpad);
    1217       146197 :   if (!S->use_stack) set_avma(av);
    1218              : }
    1219              : 
    1220              : static GEN
    1221         1876 : v_get_arg(pari_str *S, GEN arg_vector, int *index, const char *save_fmt)
    1222              : {
    1223         1876 :   if (*index >= lg(arg_vector))
    1224              :   {
    1225            7 :     if (!S->use_stack) pari_free(S->string);
    1226            7 :     pari_err(e_MISC, "missing arg %d for printf format '%s'", *index, save_fmt);  }
    1227         1869 :   return gel(arg_vector, (*index)++);
    1228              : }
    1229              : 
    1230              : static int
    1231       287421 : dosign(int blank, int plus)
    1232              : {
    1233       287421 :   if (plus) return('+');
    1234       287407 :   if (blank) return(' ');
    1235       287407 :   return 0;
    1236              : }
    1237              : 
    1238              : /* x * 10 + 'digit whose char value is ch'. Do not check for overflow */
    1239              : static int
    1240       143485 : shift_add(int x, int ch)
    1241              : {
    1242       143485 :   if (x < 0) /* was unset */
    1243       143282 :     x = ch - '0';
    1244              :   else
    1245          203 :     x = x*10 + ch - '0';
    1246       143485 :   return x;
    1247              : }
    1248              : 
    1249              : static long
    1250       143044 : get_sigd(GEN gvalue, char ch, int maxwidth)
    1251              : {
    1252              :   long e;
    1253       143044 :   if (maxwidth < 0) return nbits2ndec(precreal);
    1254       143030 :   switch(ch)
    1255              :   {
    1256          147 :     case 'E': case 'e': return maxwidth+1;
    1257       142743 :     case 'F': case 'f':
    1258       142743 :       e = gexpo(gvalue);
    1259       142743 :       if (e == -(long)HIGHEXPOBIT) return 0;
    1260       142708 :       e = ex10(e); if (e < 0) e = 0;
    1261       142708 :       return e + 1 + maxwidth;
    1262              :   }
    1263          140 :   return maxwidth? maxwidth: 1; /* 'g', 'G' */
    1264              : }
    1265              : 
    1266              : static void
    1267       143128 : fmtreal(pari_str *S, GEN gvalue, int space, int signvalue, int FORMAT,
    1268              :         int maxwidth, int ljust, int len, int zpad)
    1269              : {
    1270       143128 :   pari_sp av = avma;
    1271              :   long sigd;
    1272              :   char *buf;
    1273              : 
    1274       143128 :   if (typ(gvalue) == t_REAL)
    1275       142841 :     sigd = get_sigd(gvalue, FORMAT, maxwidth);
    1276              :   else
    1277              :   {
    1278          287 :     long i, j, h, l = lg(gvalue);
    1279          287 :     switch(typ(gvalue))
    1280              :     {
    1281           42 :       case t_COMPLEX:
    1282           42 :         fmtreal(S, gel(gvalue,1), space, signvalue, FORMAT, maxwidth,
    1283              :                 ljust,len,zpad);
    1284           42 :         if (gsigne(gel(gvalue,2)) >= 0) str_putc(S, '+');
    1285           42 :         fmtreal(S, gel(gvalue,2), space, signvalue, FORMAT, maxwidth,
    1286              :                 ljust,len,zpad);
    1287           42 :         str_putc(S, 'I');
    1288           42 :         return;
    1289              : 
    1290           28 :       case t_VEC:
    1291           28 :         str_putc(S, '[');
    1292           84 :         for (i = 1; i < l; i++)
    1293              :         {
    1294           56 :           fmtreal(S, gel(gvalue,i), space, signvalue, FORMAT, maxwidth,
    1295              :                   ljust,len,zpad);
    1296           56 :           if (i < l-1) str_putc(S, ',');
    1297              :         }
    1298           28 :         str_putc(S, ']');
    1299           28 :         return;
    1300            0 :       case t_COL:
    1301            0 :         str_putc(S, '[');
    1302            0 :         for (i = 1; i < l; i++)
    1303              :         {
    1304            0 :           fmtreal(S, gel(gvalue,i), space, signvalue, FORMAT, maxwidth,
    1305              :                   ljust,len,zpad);
    1306            0 :           if (i < l-1) str_putc(S, ',');
    1307              :         }
    1308            0 :         str_putc(S, ']');
    1309            0 :         str_putc(S, '~');
    1310            0 :         return;
    1311           14 :       case t_MAT:
    1312           14 :         if (l == 1)
    1313            0 :           str_puts(S, "[;]");
    1314              :         else
    1315              :         {
    1316           14 :           h = lgcols(gvalue);
    1317           42 :           for (j=1; j<h; j++)
    1318              :           {
    1319           28 :             str_putc(S, '[');
    1320          105 :             for (i=1; i<l; i++)
    1321              :             {
    1322           77 :               fmtreal(S, gcoeff(gvalue,j,i), space, signvalue, FORMAT, maxwidth,
    1323              :                       ljust,len,zpad);
    1324           77 :               if (i<l-1) str_putc(S, ' ');
    1325              :             }
    1326           28 :             str_putc(S, ']');
    1327           28 :             str_putc(S, '\n');
    1328           28 :             if (j<h-1) str_putc(S, '\n');
    1329              :           }
    1330              :         }
    1331           14 :         return;
    1332              :     }
    1333          203 :     sigd = get_sigd(gvalue, FORMAT, maxwidth);
    1334          203 :     gvalue = gtofp(gvalue, maxss(ndec2prec(sigd), LOWDEFAULTPREC));
    1335          203 :     if (typ(gvalue) != t_REAL)
    1336              :     {
    1337            0 :       if (!S->use_stack) free(S->string);
    1338            0 :       pari_err(e_MISC,"impossible conversion to t_REAL: %Ps",gvalue);
    1339              :     }
    1340              :   }
    1341       143044 :   if ((FORMAT == 'f' || FORMAT == 'F') && maxwidth >= 0)
    1342       142743 :     buf = absrtostr_width_frac(gvalue, maxwidth);
    1343              :   else
    1344          301 :     buf = absrtostr(gvalue, space, FORMAT, sigd);
    1345       143044 :   if (signe(gvalue) < 0) signvalue = '-';
    1346       143044 :   outpad(S, buf, strlen(buf), signvalue, ljust, len, zpad);
    1347       143044 :   if (!S->use_stack) set_avma(av);
    1348              : }
    1349              : static long
    1350           77 : gtolong_OK(GEN x)
    1351              : {
    1352           77 :   switch(typ(x))
    1353              :   {
    1354           56 :     case t_INT: case t_REAL: case t_FRAC: return 1;
    1355            7 :     case t_COMPLEX: return gequal0(gel(x,2)) && gtolong_OK(gel(x,1));
    1356            7 :     case t_QUAD: return gequal0(gel(x,3)) && gtolong_OK(gel(x,2));
    1357              :   }
    1358            7 :   return 0;
    1359              : }
    1360              : /* Format handling "inspired" by the standard draft at
    1361              : -- http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf pages 274ff
    1362              :  * fmt is a standard printf format, except 'P' is a "length modifier"
    1363              :  * allowing GEN arguments. Use either the arg_vector or (if NULL) the va_list.
    1364              :  * Appent output to the pari_str S, which must be initialized; clean if
    1365              :  * !S->use_stack, else leaves objects of stack. */
    1366              : static void
    1367       228131 : str_arg_vprintf(pari_str *S, const char *fmt, GEN arg_vector, va_list args)
    1368              : {
    1369       228131 :   int GENflag = 0, longflag = 0, pointflag = 0;
    1370              :   int print_plus, print_blank, with_sharp, ch, ljust, len, maxwidth, zpad;
    1371              :   long lvalue;
    1372       228131 :   int index = 1;
    1373              :   GEN gvalue;
    1374       228131 :   const char *save_fmt = fmt;
    1375              : 
    1376      2342320 :   while ((ch = *fmt++) != '\0') {
    1377      2114210 :     switch(ch) {
    1378       448777 :       case '%':
    1379       448777 :         ljust = zpad = 0;
    1380       448777 :         len = maxwidth = -1;
    1381       448777 :         GENflag = longflag = pointflag = 0;
    1382       448777 :         print_plus = print_blank = with_sharp = 0;
    1383       901698 : nextch:
    1384       901698 :         ch = *fmt++;
    1385       901698 :         switch(ch) {
    1386            0 :           case 0:
    1387            0 :             pari_err(e_MISC, "printf: end of format");
    1388              : /*------------------------------------------------------------------------
    1389              :                              -- flags
    1390              : ------------------------------------------------------------------------*/
    1391           42 :           case '-':
    1392           42 :             ljust = 1;
    1393           42 :             goto nextch;
    1394           14 :           case '+':
    1395           14 :             print_plus = 1;
    1396           14 :             goto nextch;
    1397           14 :           case '#':
    1398           14 :             with_sharp = 1;
    1399           14 :             goto nextch;
    1400            0 :           case ' ':
    1401            0 :             print_blank = 1;
    1402            0 :             goto nextch;
    1403          952 :           case '0':
    1404              :             /* appears as a flag: set zero padding */
    1405          952 :             if (len < 0 && !pointflag) { zpad = '0'; goto nextch; }
    1406              : 
    1407              :             /* else part of a field width or precision */
    1408              :             /* fall through */
    1409              : /*------------------------------------------------------------------------
    1410              :                        -- maxwidth or precision
    1411              : ------------------------------------------------------------------------*/
    1412              :           case '1':
    1413              :           case '2':
    1414              :           case '3':
    1415              :           case '4':
    1416              :           case '5':
    1417              :           case '6':
    1418              :           case '7':
    1419              :           case '8':
    1420              :           case '9':
    1421       143485 :             if (pointflag)
    1422       143037 :               maxwidth = shift_add(maxwidth, ch);
    1423              :             else
    1424          448 :               len = shift_add(len, ch);
    1425       143485 :             goto nextch;
    1426              : 
    1427           28 :           case '*':
    1428              :           {
    1429           28 :             int *t = pointflag? &maxwidth: &len;
    1430           28 :             if (arg_vector)
    1431              :             {
    1432           28 :               gvalue = v_get_arg(S, arg_vector, &index, save_fmt);
    1433           28 :               if (!gtolong_OK(gvalue) && !S->use_stack) pari_free(S->string);
    1434           28 :               *t = (int)gtolong(gvalue);
    1435              :             }
    1436              :             else
    1437            0 :               *t = va_arg(args, int);
    1438           28 :             goto nextch;
    1439              :           }
    1440       142939 :           case '.':
    1441       142939 :             if (pointflag)
    1442            0 :               pari_err(e_MISC, "two '.' in conversion specification");
    1443       142939 :             pointflag = 1;
    1444       142939 :             goto nextch;
    1445              : /*------------------------------------------------------------------------
    1446              :                        -- length modifiers
    1447              : ------------------------------------------------------------------------*/
    1448       144900 :           case 'l':
    1449       144900 :             if (GENflag)
    1450            0 :               pari_err(e_MISC, "P/l length modifiers in the same conversion");
    1451              : #if !defined(_WIN64)
    1452       144900 :             if (longflag)
    1453            0 :               pari_err_IMPL( "ll length modifier in printf");
    1454              : #endif
    1455       144900 :             longflag = 1;
    1456       144900 :             goto nextch;
    1457        20729 :           case 'P':
    1458        20729 :             if (longflag)
    1459            0 :               pari_err(e_MISC, "P/l length modifiers in the same conversion");
    1460        20729 :             if (GENflag)
    1461            0 :               pari_err(e_MISC, "'P' length modifier appears twice");
    1462        20729 :             GENflag = 1;
    1463        20729 :             goto nextch;
    1464            0 :           case 'h': /* dummy: va_arg promotes short into int */
    1465            0 :             goto nextch;
    1466              : /*------------------------------------------------------------------------
    1467              :                        -- conversions
    1468              : ------------------------------------------------------------------------*/
    1469          756 :           case 'u': /* not a signed conversion: print_(blank|plus) ignored */
    1470              : #define get_num_arg() \
    1471              :   if (arg_vector) { \
    1472              :     lvalue = 0; \
    1473              :     gvalue = v_get_arg(S, arg_vector, &index, save_fmt); \
    1474              :   } else { \
    1475              :     if (GENflag) { \
    1476              :       lvalue = 0; \
    1477              :       gvalue = va_arg(args, GEN); \
    1478              :     } else { \
    1479              :       lvalue = longflag? va_arg(args, long): va_arg(args, int); \
    1480              :       gvalue = NULL; \
    1481              :     } \
    1482              :   }
    1483          756 :             get_num_arg();
    1484          756 :             fmtnum(S, lvalue, gvalue, 10, -1, ljust, len, zpad);
    1485          756 :             break;
    1486            0 :           case 'o': /* not a signed conversion: print_(blank|plus) ignored */
    1487            0 :             get_num_arg();
    1488            0 :             fmtnum(S, lvalue, gvalue, with_sharp? -8: 8, -1, ljust, len, zpad);
    1489            0 :             break;
    1490       144517 :           case 'd':
    1491              :           case 'i':
    1492       144517 :             get_num_arg();
    1493       144510 :             fmtnum(S, lvalue, gvalue, 10,
    1494              :                    dosign(print_blank, print_plus), ljust, len, zpad);
    1495       144510 :             break;
    1496            0 :           case 'p':
    1497            0 :             str_putc(S, '0'); str_putc(S, 'x');
    1498            0 :             if (arg_vector)
    1499            0 :               lvalue = (long)v_get_arg(S, arg_vector, &index, save_fmt);
    1500              :             else
    1501            0 :               lvalue = (long)va_arg(args, void*);
    1502            0 :             fmtnum(S, lvalue, NULL, 16, -1, ljust, len, zpad);
    1503            0 :             break;
    1504           14 :           case 'x': /* not a signed conversion: print_(blank|plus) ignored */
    1505           14 :             if (with_sharp) { str_putc(S, '0'); str_putc(S, 'x'); }
    1506           14 :             get_num_arg();
    1507           14 :             fmtnum(S, lvalue, gvalue, 16, -1, ljust, len, zpad);
    1508           14 :             break;
    1509          756 :           case 'X': /* not a signed conversion: print_(blank|plus) ignored */
    1510          756 :             if (with_sharp) { str_putc(S, '0'); str_putc(S, 'X'); }
    1511          756 :             get_num_arg();
    1512          756 :             fmtnum(S, lvalue, gvalue,-16, -1, ljust, len, zpad);
    1513          756 :             break;
    1514       159396 :           case 's':
    1515              :           {
    1516              :             char *strvalue;
    1517       159396 :             pari_sp av = avma;
    1518              : 
    1519       159396 :             if (arg_vector) {
    1520          126 :               gvalue = v_get_arg(S, arg_vector, &index, save_fmt);
    1521          126 :               strvalue = NULL;
    1522              :             } else {
    1523       159270 :               if (GENflag) {
    1524        19980 :                 gvalue = va_arg(args, GEN);
    1525        19980 :                 strvalue = NULL;
    1526              :               } else {
    1527       139290 :                 gvalue = NULL;
    1528       139290 :                 strvalue = va_arg(args, char *);
    1529              :               }
    1530              :             }
    1531       159396 :             if (gvalue) strvalue = GENtostr_unquoted(gvalue);
    1532       159396 :             fmtstr(S, strvalue, ljust, len, maxwidth);
    1533       159396 :             if (!S->use_stack) set_avma(av);
    1534       159396 :             break;
    1535              :           }
    1536           42 :           case 'c':
    1537           42 :             gvalue = NULL;
    1538           42 :             if (arg_vector)
    1539           35 :               gvalue = v_get_arg(S, arg_vector, &index, save_fmt);
    1540            7 :             else if (GENflag)
    1541            0 :               gvalue = va_arg(args,GEN);
    1542              :             else
    1543              :             {
    1544            7 :               ch = va_arg(args, int);
    1545            7 :               str_putc(S, ch); break;
    1546              :             }
    1547           35 :             if (!gtolong_OK(gvalue) && !S->use_stack) free(S->string);
    1548           35 :             str_putc(S, (int)gtolong(gvalue));
    1549           28 :             break;
    1550              : 
    1551          378 :           case '%':
    1552          378 :             str_putc(S, ch);
    1553          378 :             continue;
    1554       142911 :           case 'g':
    1555              :           case 'G':
    1556              :           case 'e':
    1557              :           case 'E':
    1558              :           case 'f':
    1559              :           case 'F':
    1560              :           {
    1561       142911 :             pari_sp av = avma;
    1562       142911 :             if (arg_vector)
    1563          392 :               gvalue = simplify_shallow(v_get_arg(S, arg_vector, &index, save_fmt));
    1564              :             else {
    1565       142519 :               if (GENflag)
    1566            0 :                 gvalue = simplify_shallow( va_arg(args, GEN) );
    1567              :               else
    1568       142519 :                 gvalue = dbltor( va_arg(args, double) );
    1569              :             }
    1570       142911 :             fmtreal(S, gvalue, GP_DATA->fmt->sp, dosign(print_blank,print_plus),
    1571              :                     ch, maxwidth, ljust, len, zpad);
    1572       142911 :             if (!S->use_stack) set_avma(av);
    1573       142911 :             break;
    1574              :           }
    1575            7 :           default:
    1576            7 :             if (!S->use_stack) free(S->string);
    1577            7 :             pari_err(e_MISC, "invalid conversion or specification %c in format `%s'", ch, save_fmt);
    1578              :         } /* second switch on ch */
    1579       448378 :         break;
    1580      1665433 :       default:
    1581      1665433 :         str_putc(S, ch);
    1582      1665433 :         break;
    1583              :     } /* first switch on ch */
    1584              :   } /* while loop on ch */
    1585       228110 :   *S->cur = 0;
    1586       228110 : }
    1587              : 
    1588              : void
    1589           12 : decode_color(long n, long *c)
    1590              : {
    1591           12 :   c[1] = n & 0xf; n >>= 4; /* foreground */
    1592           12 :   c[2] = n & 0xf; n >>= 4; /* background */
    1593           12 :   c[0] = n & 0xf; /* attribute */
    1594           12 : }
    1595              : 
    1596              : #define COLOR_LEN 16
    1597              : /* start printing in "color" c */
    1598              : /* terminal has to support ANSI color escape sequences */
    1599              : void
    1600        68398 : out_term_color(PariOUT *out, long c)
    1601              : {
    1602              :   static char s[COLOR_LEN];
    1603        68398 :   out->puts(term_get_color(s, c));
    1604        68398 : }
    1605              : void
    1606          693 : term_color(long c) { out_term_color(pariOut, c); }
    1607              : 
    1608              : /* s must be able to store 12 chars (including final \0) */
    1609              : char *
    1610        83210 : term_get_color(char *s, long n)
    1611              : {
    1612              :   long c[3], a;
    1613        83210 :   if (!s) s = stack_malloc(COLOR_LEN);
    1614              : 
    1615        83210 :   if (disable_color) { *s = 0; return s; }
    1616           20 :   if (n == c_NONE || (a = gp_colors[n]) == c_NONE)
    1617            8 :     strcpy(s, "\x1b[0m"); /* reset */
    1618              :   else
    1619              :   {
    1620           12 :     decode_color(a,c);
    1621           12 :     if (c[1]<8) c[1] += 30; else c[1] += 82;
    1622           12 :     if (a & (1L<<12)) /* transparent background */
    1623           12 :       sprintf(s, "\x1b[%ld;%ldm", c[0], c[1]);
    1624              :     else
    1625              :     {
    1626            0 :       if (c[2]<8) c[2] += 40; else c[2] += 92;
    1627            0 :       sprintf(s, "\x1b[%ld;%ld;%ldm", c[0], c[1], c[2]);
    1628              :     }
    1629              :   }
    1630           20 :   return s;
    1631              : }
    1632              : 
    1633              : static long
    1634       173691 : strlen_real(const char *s)
    1635              : {
    1636       173691 :   const char *t = s;
    1637       173691 :   long len = 0;
    1638      1310352 :   while (*t)
    1639              :   {
    1640      1136661 :     if (t[0] == '\x1b' && t[1] == '[')
    1641              :     { /* skip ANSI escape sequence */
    1642            2 :       t += 2;
    1643           10 :       while (*t && *t++ != 'm') /* empty */;
    1644            2 :       continue;
    1645              :     }
    1646      1136659 :     t++; len++;
    1647              :   }
    1648       173691 :   return len;
    1649              : }
    1650              : 
    1651              : #undef COLOR_LEN
    1652              : 
    1653              : /********************************************************************/
    1654              : /**                                                                **/
    1655              : /**                  PRINTING BASED ON SCREEN WIDTH                **/
    1656              : /**                                                                **/
    1657              : /********************************************************************/
    1658              : #undef larg /* problems with SCO Unix headers (ioctl_arg) */
    1659              : #ifdef HAS_TIOCGWINSZ
    1660              : #  ifdef __sun
    1661              : #    include <sys/termios.h>
    1662              : #  endif
    1663              : #  include <sys/ioctl.h>
    1664              : #endif
    1665              : 
    1666              : static int
    1667        22957 : term_width_intern(void)
    1668              : {
    1669              : #ifdef _WIN32
    1670              :   return win32_terminal_width();
    1671              : #endif
    1672              : #ifdef HAS_TIOCGWINSZ
    1673              :   {
    1674              :     struct winsize s;
    1675        22957 :     if (!(GP_DATA->flags & (gpd_EMACS|gpd_TEXMACS))
    1676        22957 :      && !ioctl(0, TIOCGWINSZ, &s)) return s.ws_col;
    1677              :   }
    1678              : #endif
    1679              :   {
    1680              :     char *str;
    1681        22945 :     if ((str = os_getenv("COLUMNS"))) return atoi(str);
    1682              :   }
    1683              : #ifdef __EMX__
    1684              :   {
    1685              :     int scrsize[2];
    1686              :     _scrsize(scrsize); return scrsize[0];
    1687              :   }
    1688              : #endif
    1689        22945 :   return 0;
    1690              : }
    1691              : 
    1692              : static int
    1693            7 : term_height_intern(void)
    1694              : {
    1695              : #ifdef _WIN32
    1696              :   return win32_terminal_height();
    1697              : #endif
    1698              : #ifdef HAS_TIOCGWINSZ
    1699              :   {
    1700              :     struct winsize s;
    1701            7 :     if (!(GP_DATA->flags & (gpd_EMACS|gpd_TEXMACS))
    1702            7 :      && !ioctl(0, TIOCGWINSZ, &s)) return s.ws_row;
    1703              :   }
    1704              : #endif
    1705              :   {
    1706              :     char *str;
    1707            7 :     if ((str = os_getenv("LINES"))) return atoi(str);
    1708              :   }
    1709              : #ifdef __EMX__
    1710              :   {
    1711              :     int scrsize[2];
    1712              :     _scrsize(scrsize); return scrsize[1];
    1713              :   }
    1714              : #endif
    1715            7 :   return 0;
    1716              : }
    1717              : 
    1718              : #define DFT_TERM_WIDTH  80
    1719              : #define DFT_TERM_HEIGHT 20
    1720              : 
    1721              : int
    1722        22957 : term_width(void)
    1723              : {
    1724        22957 :   int n = term_width_intern();
    1725        22957 :   return (n>1)? n: DFT_TERM_WIDTH;
    1726              : }
    1727              : 
    1728              : int
    1729            7 : term_height(void)
    1730              : {
    1731            7 :   int n = term_height_intern();
    1732            7 :   return (n>1)? n: DFT_TERM_HEIGHT;
    1733              : }
    1734              : 
    1735              : static ulong col_index;
    1736              : 
    1737              : /* output string wrapped after MAX_WIDTH characters (for gp -test) */
    1738              : static void
    1739     10149036 : putc_lw(char c)
    1740              : {
    1741     10149036 :   if (c == '\n') col_index = 0;
    1742      9941163 :   else if (col_index >= GP_DATA->linewrap) { normalOutC('\n'); col_index = 1; }
    1743      9860915 :   else col_index++;
    1744     10149036 :   normalOutC(c);
    1745     10149036 : }
    1746              : static void
    1747     10245429 : puts_lw(const char *s) { while (*s) putc_lw(*s++); }
    1748              : 
    1749              : static PariOUT pariOut_lw= {putc_lw, puts_lw, normalOutF};
    1750              : 
    1751              : void
    1752        62766 : init_linewrap(long w) { col_index=0; GP_DATA->linewrap=w; pariOut=&pariOut_lw; }
    1753              : 
    1754              : static void
    1755         7919 : new_line(PariOUT *out, const char *prefix)
    1756              : {
    1757         7919 :   out_putc(out, '\n'); if (prefix) out_puts(out, prefix);
    1758         7919 : }
    1759              : 
    1760              : #define is_blank(c) ((c) == ' ' || (c) == '\n' || (c) == '\t')
    1761              : /* output: <prefix>< s wrapped at EOL >
    1762              :  *         <prefix>< ... > <str>
    1763              :  *                         ^---  (no \n at the end)
    1764              :  * If str is NULL, omit the arrow, end the text with '\n'.
    1765              :  * If prefix is NULL, use "" */
    1766              : void
    1767        18825 : print_prefixed_text(PariOUT *out, const char *s, const char *prefix,
    1768              :                     const char *str)
    1769              : {
    1770        18825 :   const long prelen = prefix? strlen_real(prefix): 0;
    1771        18825 :   const long W = term_width(), ls = strlen(s);
    1772        18825 :   long linelen = prelen;
    1773        18825 :   char *word = (char*)pari_malloc(ls + 3);
    1774              : 
    1775        18825 :   if (prefix) out_puts(out, prefix);
    1776              :   for(;;)
    1777       128077 :   {
    1778              :     long len;
    1779       146902 :     int blank = 0;
    1780       146902 :     char *u = word;
    1781       930726 :     while (*s && !is_blank(*s)) *u++ = *s++;
    1782       146902 :     *u = 0; /* finish "word" */
    1783       146902 :     len = strlen_real(word);
    1784       146902 :     linelen += len;
    1785       146902 :     if (linelen >= W) { new_line(out, prefix); linelen = prelen + len; }
    1786       146902 :     out_puts(out, word);
    1787       286970 :     while (is_blank(*s)) {
    1788       140068 :       switch (*s) {
    1789       137415 :         case ' ': break;
    1790            0 :         case '\t':
    1791            0 :           linelen = (linelen & ~7UL) + 8; out_putc(out, '\t');
    1792            0 :           blank = 1; break;
    1793         2653 :         case '\n':
    1794         2653 :           linelen = W;
    1795         2653 :           blank = 1; break;
    1796              :       }
    1797       140068 :       if (linelen >= W) { new_line(out, prefix); linelen = prelen; }
    1798       140068 :       s++;
    1799              :     }
    1800       146902 :     if (!*s) break;
    1801       128077 :     if (!blank) { out_putc(out, ' '); linelen++; }
    1802              :   }
    1803        18825 :   if (!str)
    1804         5462 :     out_putc(out, '\n');
    1805              :   else
    1806              :   {
    1807        13363 :     long i,len = strlen_real(str);
    1808        13363 :     int space = (*str == ' ' && str[1]);
    1809        13363 :     if (linelen + len >= W)
    1810              :     {
    1811           21 :       new_line(out, prefix); linelen = prelen;
    1812           21 :       if (space) { str++; len--; space = 0; }
    1813              :     }
    1814        13363 :     out_term_color(out, c_OUTPUT);
    1815        13363 :     out_puts(out, str);
    1816        13363 :     if (!len || str[len-1] != '\n') out_putc(out, '\n');
    1817        13363 :     if (space) { linelen++; len--; }
    1818        13363 :     out_term_color(out, c_ERR);
    1819        13363 :     if (prefix) { out_puts(out, prefix); linelen -= prelen; }
    1820       220275 :     for (i=0; i<linelen; i++) out_putc(out, ' ');
    1821        13363 :     out_putc(out, '^');
    1822       246862 :     for (i=0; i<len; i++) out_putc(out, '-');
    1823              :   }
    1824        18825 :   pari_free(word);
    1825        18825 : }
    1826              : 
    1827              : #define CONTEXT_LEN 46
    1828              : #define MAX_TERM_COLOR 16
    1829              : /* Outputs a beautiful error message (not \n terminated)
    1830              :  *   msg is errmessage to print.
    1831              :  *   s points to the offending chars.
    1832              :  *   entry tells how much we can go back from s[0] */
    1833              : void
    1834        13426 : print_errcontext(PariOUT *out,
    1835              :                  const char *msg, const char *s, const char *entry)
    1836              : {
    1837        13426 :   const long MAX_PAST = 25;
    1838        13426 :   long past = s - entry, future, lmsg;
    1839              :   char str[CONTEXT_LEN + 1 + 1], pre[MAX_TERM_COLOR + 8 + 1];
    1840              :   char *buf, *t;
    1841              : 
    1842        13426 :   if (!s || !entry) { print_prefixed_text(out, msg,"  ***   ",NULL); return; }
    1843              : 
    1844              :   /* message + context */
    1845        13363 :   lmsg = strlen(msg);
    1846              :   /* msg + past + ': ' + '...' + term_get_color + \0 */
    1847        13363 :   t = buf = (char*)pari_malloc(lmsg + MAX_PAST + 2 + 3 + MAX_TERM_COLOR + 1);
    1848        13363 :   memcpy(t, msg, lmsg); t += lmsg;
    1849        13363 :   strcpy(t, ": "); t += 2;
    1850        13363 :   if (past <= 0) past = 0;
    1851              :   else
    1852              :   {
    1853         1435 :     if (past > MAX_PAST) { past = MAX_PAST; strcpy(t, "..."); t += 3; }
    1854         1435 :     term_get_color(t, c_OUTPUT);
    1855         1435 :     t += strlen(t);
    1856         1435 :     memcpy(t, s - past, past); t[past] = 0;
    1857              :   }
    1858              : 
    1859              :   /* suffix (past arrow) */
    1860        13363 :   t = str; if (!past) *t++ = ' ';
    1861        13363 :   future = CONTEXT_LEN - past;
    1862        13363 :   strncpy(t, s, future); t[future] = 0;
    1863              :   /* prefix '***' */
    1864        13363 :   term_get_color(pre, c_ERR);
    1865        13363 :   strcat(pre, "  ***   ");
    1866              :   /* now print */
    1867        13363 :   print_prefixed_text(out, buf, pre, str);
    1868        13363 :   pari_free(buf);
    1869              : }
    1870              : 
    1871              : /********************************************************************/
    1872              : /**                                                                **/
    1873              : /**                    GEN <---> CHARACTER STRINGS                 **/
    1874              : /**                                                                **/
    1875              : /********************************************************************/
    1876              : static OUT_FUN
    1877       209602 : get_fun(long flag)
    1878              : {
    1879       209602 :   switch(flag) {
    1880       148424 :     case f_RAW : return bruti;
    1881          172 :     case f_TEX : return texi;
    1882        61006 :     default: return matbruti;
    1883              :   }
    1884              : }
    1885              : 
    1886              : /* not stack clean */
    1887              : static char *
    1888        72299 : stack_GENtostr_fun(GEN x, pariout_t *T, OUT_FUN out)
    1889              : {
    1890        72299 :   pari_str S; str_init(&S, 1);
    1891        72299 :   out(x, T, &S); *S.cur = 0;
    1892        72299 :   return S.string;
    1893              : }
    1894              : /* same but remove quotes "" around t_STR */
    1895              : static char *
    1896        26348 : stack_GENtostr_fun_unquoted(GEN x, pariout_t *T, OUT_FUN out)
    1897        26348 : { return (typ(x)==t_STR)? GSTR(x): stack_GENtostr_fun(x, T, out); }
    1898              : 
    1899              : /* stack-clean: pari-malloc'ed */
    1900              : static char *
    1901          746 : GENtostr_fun(GEN x, pariout_t *T, OUT_FUN out)
    1902              : {
    1903          746 :   pari_sp av = avma;
    1904          746 :   pari_str S; str_init(&S, 0);
    1905          746 :   out(x, T, &S); *S.cur = 0;
    1906          746 :   set_avma(av); return S.string;
    1907              : }
    1908              : /* returns a malloc-ed string, which should be freed after usage */
    1909              : /* Returns pari_malloc()ed string */
    1910              : char *
    1911            4 : GENtostr(GEN x)
    1912            4 : { return GENtostr_fun(x, GP_DATA->fmt, get_fun(GP_DATA->fmt->prettyp)); }
    1913              : char *
    1914            0 : GENtoTeXstr(GEN x) { return GENtostr_fun(x, GP_DATA->fmt, &texi); }
    1915              : char *
    1916        26348 : GENtostr_unquoted(GEN x)
    1917        26348 : { return stack_GENtostr_fun_unquoted(x, GP_DATA->fmt, &bruti); }
    1918              : /* alloc-ed on PARI stack */
    1919              : char *
    1920         3717 : GENtostr_raw(GEN x) { return stack_GENtostr_fun(x,GP_DATA->fmt,&bruti); }
    1921              : 
    1922              : GEN
    1923          742 : GENtoGENstr(GEN x)
    1924              : {
    1925          742 :   char *s = GENtostr_fun(x, GP_DATA->fmt, &bruti);
    1926          742 :   GEN z = strtoGENstr(s); pari_free(s); return z;
    1927              : }
    1928              : GEN
    1929            0 : GENtoGENstr_nospace(GEN x)
    1930              : {
    1931            0 :   pariout_t T = *(GP_DATA->fmt);
    1932              :   char *s;
    1933              :   GEN z;
    1934            0 :   T.sp = 0;
    1935            0 :   s = GENtostr_fun(x, &T, &bruti);
    1936            0 :   z = strtoGENstr(s); pari_free(s); return z;
    1937              : }
    1938              : 
    1939              : /********************************************************************/
    1940              : /**                                                                **/
    1941              : /**                         WRITE AN INTEGER                       **/
    1942              : /**                                                                **/
    1943              : /********************************************************************/
    1944              : char *
    1945         6804 : itostr(GEN x) {
    1946         6804 :   long sx = signe(x), l;
    1947         6804 :   return sx? itostr_sign(x, sx, &l): zerotostr();
    1948              : }
    1949              : 
    1950              : /* x != 0 t_INT, write abs(x) to S */
    1951              : static void
    1952       587894 : str_absint(pari_str *S, GEN x)
    1953              : {
    1954              :   pari_sp av;
    1955              :   long l;
    1956       587894 :   str_alloc(S, lgefint(x)); /* careful ! */
    1957       587894 :   av = avma;
    1958       587894 :   str_puts(S, itostr_sign(x, 1, &l)); set_avma(av);
    1959       587894 : }
    1960              : 
    1961              : #define putsigne_nosp(S, x) str_putc(S, (x>0)? '+' : '-')
    1962              : #define putsigne(S, x) str_puts(S, (x>0)? " + " : " - ")
    1963              : #define sp_sign_sp(T,S, x) ((T)->sp? putsigne(S,x): putsigne_nosp(S,x))
    1964              : #define semicolon_sp(T,S)  ((T)->sp? str_puts(S, "; "): str_putc(S, ';'))
    1965              : #define comma_sp(T,S)      ((T)->sp? str_puts(S, ", "): str_putc(S, ','))
    1966              : 
    1967              : /* print e to S (more efficient than sprintf) */
    1968              : static void
    1969       187493 : str_ulong(pari_str *S, ulong e)
    1970              : {
    1971       187493 :   if (e == 0) str_putc(S, '0');
    1972              :   else
    1973              :   {
    1974       180913 :     char buf[21], *p = buf + numberof(buf);
    1975       180913 :     *--p = 0;
    1976       180913 :     if (e > 9) {
    1977              :       do
    1978        38342 :         *--p = "0123456789"[e % 10];
    1979        38342 :       while ((e /= 10) > 9);
    1980              :     }
    1981       180913 :     *--p = "0123456789"[e];
    1982       180913 :     str_puts(S, p);
    1983              :   }
    1984       187493 : }
    1985              : static void
    1986       187493 : str_long(pari_str *S, long e)
    1987              : {
    1988       187493 :   if (e >= 0) str_ulong(S, (ulong)e);
    1989         2401 :   else { str_putc(S, '-'); str_ulong(S, -(ulong)e); }
    1990       187493 : }
    1991              : 
    1992              : static void
    1993         8082 : wr_vecsmall(pariout_t *T, pari_str *S, GEN g)
    1994              : {
    1995              :   long i, l;
    1996         8082 :   str_puts(S, "Vecsmall(["); l = lg(g);
    1997        40399 :   for (i=1; i<l; i++)
    1998              :   {
    1999        32317 :     str_long(S, g[i]);
    2000        32317 :     if (i<l-1) comma_sp(T,S);
    2001              :   }
    2002         8082 :   str_puts(S, "])");
    2003         8082 : }
    2004              : 
    2005              : /********************************************************************/
    2006              : /**                                                                **/
    2007              : /**                       HEXADECIMAL OUTPUT                       **/
    2008              : /**                                                                **/
    2009              : /********************************************************************/
    2010              : /* English ordinal numbers */
    2011              : char *
    2012            0 : uordinal(ulong i)
    2013              : {
    2014            0 :   const char *suff[] = {"st","nd","rd","th"};
    2015            0 :   char *s = stack_malloc(23);
    2016            0 :   long k = 3;
    2017            0 :   switch (i%10)
    2018              :   {
    2019            0 :     case 1: if (i%100!=11) k = 0;
    2020            0 :             break;
    2021            0 :     case 2: if (i%100!=12) k = 1;
    2022            0 :             break;
    2023            0 :     case 3: if (i%100!=13) k = 2;
    2024            0 :             break;
    2025              :   }
    2026            0 :   sprintf(s, "%lu%s", i, suff[k]); return s;
    2027              : }
    2028              : 
    2029              : static char
    2030            0 : vsigne(GEN x)
    2031              : {
    2032            0 :   long s = signe(x);
    2033            0 :   if (!s) return '0';
    2034            0 :   return (s > 0) ? '+' : '-';
    2035              : }
    2036              : 
    2037              : static void
    2038            0 : blancs(long nb) { while (nb-- > 0) pari_putc(' '); }
    2039              : 
    2040              : /* write an "address" */
    2041              : static void
    2042            0 : str_addr(pari_str *S, ulong x)
    2043            0 : { char s[128]; sprintf(s,"%0*lx", BITS_IN_LONG/4, x); str_puts(S, s); }
    2044              : static void
    2045            0 : dbg_addr(ulong x) { pari_printf("[&=%0*lx] ", BITS_IN_LONG/4, x); }
    2046              : /* write a "word" */
    2047              : static void
    2048            0 : dbg_word(ulong x) { pari_printf("%0*lx ", BITS_IN_LONG/4, x); }
    2049              : 
    2050              : /* bl: indent level */
    2051              : static void
    2052            0 : dbg(GEN x, long nb, long bl)
    2053              : {
    2054              :   long tx,i,j,e,dx,lx;
    2055              : 
    2056            0 :   if (!x) { pari_puts("NULL\n"); return; }
    2057            0 :   tx = typ(x);
    2058            0 :   if (tx == t_INT && x == gen_0) { pari_puts("gen_0\n"); return; }
    2059            0 :   dbg_addr((ulong)x);
    2060              : 
    2061            0 :   lx = lg(x);
    2062            0 :   pari_printf("%s(lg=%ld%s):",type_name(tx)+2,lx,isclone(x)? ",CLONE" : "");
    2063            0 :   dbg_word(x[0]);
    2064            0 :   if (! is_recursive_t(tx)) /* t_INT, t_REAL, t_STR, t_VECSMALL */
    2065              :   {
    2066            0 :     if (tx == t_STR)
    2067            0 :       pari_puts("chars:");
    2068            0 :     else if (tx == t_INT)
    2069              :     {
    2070            0 :       lx = lgefint(x);
    2071            0 :       pari_printf("(%c,lgefint=%ld):", vsigne(x), lx);
    2072              :     }
    2073            0 :     else if (tx == t_REAL)
    2074            0 :       pari_printf("(%c,expo=%ld):", vsigne(x), expo(x));
    2075            0 :     if (nb < 0) nb = lx;
    2076            0 :     for (i=1; i < nb; i++) dbg_word(x[i]);
    2077            0 :     pari_putc('\n'); return;
    2078              :   }
    2079              : 
    2080            0 :   if (tx == t_PADIC)
    2081            0 :     pari_printf("(precp=%ld,valp=%ld):", precp(x), valp(x));
    2082            0 :   else if (tx == t_POL)
    2083            0 :     pari_printf("(%c,varn=%ld):", vsigne(x), varn(x));
    2084            0 :   else if (tx == t_SER)
    2085            0 :     pari_printf("(%c,varn=%ld,prec=%ld,valser=%ld):",
    2086            0 :                vsigne(x), varn(x), lg(x)-2, valser(x));
    2087            0 :   else if (tx == t_LIST)
    2088              :   {
    2089            0 :     pari_printf("(subtyp=%ld,lmax=%ld):", list_typ(x), list_nmax(x));
    2090            0 :     x = list_data(x); lx = x? lg(x): 1;
    2091            0 :     tx = t_VEC; /* print list_data as vec */
    2092            0 :   } else if (tx == t_CLOSURE)
    2093            0 :     pari_printf("(arity=%ld%s):", closure_arity(x),
    2094            0 :                                   closure_is_variadic(x)?"+":"");
    2095            0 :   for (i=1; i<lx; i++) dbg_word(x[i]);
    2096            0 :   bl+=2; pari_putc('\n');
    2097            0 :   switch(tx)
    2098              :   {
    2099            0 :     case t_INTMOD: case t_POLMOD:
    2100              :     {
    2101            0 :       const char *s = (tx==t_INTMOD)? "int = ": "pol = ";
    2102            0 :       blancs(bl); pari_puts("mod = "); dbg(gel(x,1),nb,bl);
    2103            0 :       blancs(bl); pari_puts(s);        dbg(gel(x,2),nb,bl);
    2104            0 :       break;
    2105              :     }
    2106            0 :     case t_FRAC: case t_RFRAC:
    2107            0 :       blancs(bl); pari_puts("num = "); dbg(gel(x,1),nb,bl);
    2108            0 :       blancs(bl); pari_puts("den = "); dbg(gel(x,2),nb,bl);
    2109            0 :       break;
    2110              : 
    2111            0 :     case t_FFELT:
    2112            0 :       blancs(bl); pari_puts("pol = "); dbg(gel(x,2),nb,bl);
    2113            0 :       blancs(bl); pari_puts("mod = "); dbg(gel(x,3),nb,bl);
    2114            0 :       blancs(bl); pari_puts("p   = "); dbg(gel(x,4),nb,bl);
    2115            0 :       break;
    2116              : 
    2117            0 :     case t_COMPLEX:
    2118            0 :       blancs(bl); pari_puts("real = "); dbg(gel(x,1),nb,bl);
    2119            0 :       blancs(bl); pari_puts("imag = "); dbg(gel(x,2),nb,bl);
    2120            0 :       break;
    2121              : 
    2122            0 :     case t_PADIC:
    2123            0 :       blancs(bl); pari_puts("  p : "); dbg(padic_p(x),nb,bl);
    2124            0 :       blancs(bl); pari_puts("p^l : "); dbg(padic_pd(x),nb,bl);
    2125            0 :       blancs(bl); pari_puts("  I : "); dbg(padic_u(x),nb,bl);
    2126            0 :       break;
    2127              : 
    2128            0 :     case t_QUAD:
    2129            0 :       blancs(bl); pari_puts("pol = ");  dbg(gel(x,1),nb,bl);
    2130            0 :       blancs(bl); pari_puts("real = "); dbg(gel(x,2),nb,bl);
    2131            0 :       blancs(bl); pari_puts("imag = "); dbg(gel(x,3),nb,bl);
    2132            0 :       break;
    2133              : 
    2134            0 :     case t_POL: case t_SER:
    2135            0 :       e = (tx==t_SER)? valser(x): 0;
    2136            0 :       for (i=2; i<lx; i++)
    2137              :       {
    2138            0 :         blancs(bl); pari_printf("coef of degree %ld = ",e);
    2139            0 :         e++; dbg(gel(x,i),nb,bl);
    2140              :       }
    2141            0 :       break;
    2142              : 
    2143            0 :     case t_QFB: case t_VEC: case t_COL:
    2144            0 :       for (i=1; i<lx; i++)
    2145              :       {
    2146            0 :         blancs(bl); pari_printf("%s component = ",uordinal(i));
    2147            0 :         dbg(gel(x,i),nb,bl);
    2148              :       }
    2149            0 :       break;
    2150              : 
    2151            0 :     case t_CLOSURE:
    2152            0 :       blancs(bl); pari_puts("code = "); dbg(closure_get_code(x),nb,bl);
    2153            0 :       blancs(bl); pari_puts("operand = "); dbg(closure_get_oper(x),nb,bl);
    2154            0 :       blancs(bl); pari_puts("data = "); dbg(closure_get_data(x),nb,bl);
    2155            0 :       blancs(bl); pari_puts("dbg/frpc/fram = "); dbg(closure_get_dbg(x),nb,bl);
    2156            0 :       if (lg(x)>=7)
    2157              :       {
    2158            0 :         blancs(bl); pari_puts("text = "); dbg(closure_get_text(x),nb,bl);
    2159            0 :         if (lg(x)>=8)
    2160              :         {
    2161            0 :           blancs(bl); pari_puts("frame = "); dbg(closure_get_frame(x),nb,bl);
    2162              :         }
    2163              :       }
    2164            0 :       break;
    2165              : 
    2166            0 :     case t_ERROR:
    2167            0 :       blancs(bl);
    2168            0 :       pari_printf("error type = %s\n", numerr_name(err_get_num(x)));
    2169            0 :       for (i=2; i<lx; i++)
    2170              :       {
    2171            0 :         blancs(bl); pari_printf("%s component = ",uordinal(i-1));
    2172            0 :         dbg(gel(x,i),nb,bl);
    2173              :       }
    2174            0 :       break;
    2175              : 
    2176            0 :     case t_INFINITY:
    2177            0 :       blancs(bl); pari_printf("1st component = ");
    2178            0 :       dbg(gel(x,1),nb,bl);
    2179            0 :       break;
    2180              : 
    2181            0 :     case t_MAT:
    2182              :     {
    2183            0 :       GEN c = gel(x,1);
    2184            0 :       if (lx == 1) return;
    2185            0 :       if (typ(c) == t_VECSMALL)
    2186              :       {
    2187            0 :         for (i = 1; i < lx; i++)
    2188              :         {
    2189            0 :           blancs(bl); pari_printf("%s column = ",uordinal(i));
    2190            0 :           dbg(gel(x,i),nb,bl);
    2191              :         }
    2192              :       }
    2193              :       else
    2194              :       {
    2195            0 :         dx = lg(c);
    2196            0 :         for (i=1; i<dx; i++)
    2197            0 :           for (j=1; j<lx; j++)
    2198              :           {
    2199            0 :             blancs(bl); pari_printf("mat(%ld,%ld) = ",i,j);
    2200            0 :             dbg(gcoeff(x,i,j),nb,bl);
    2201              :           }
    2202              :       }
    2203              :     }
    2204              :   }
    2205              : }
    2206              : 
    2207              : void
    2208            0 : dbgGEN(GEN x, long nb) { dbg(x,nb,0); }
    2209              : 
    2210              : static void
    2211            0 : print_entree(entree *ep)
    2212              : {
    2213            0 :   pari_printf(" %s ",ep->name); dbg_addr((ulong)ep);
    2214            0 :   pari_printf(": hash = %ld [%ld]\n", ep->hash % functions_tblsz, ep->hash);
    2215            0 :   pari_printf("   menu = %2ld, code = %-10s",
    2216            0 :               ep->menu, ep->code? ep->code: "NULL");
    2217            0 :   if (ep->next)
    2218              :   {
    2219            0 :     pari_printf("next = %s ",(ep->next)->name);
    2220            0 :     dbg_addr((ulong)ep->next);
    2221              :   }
    2222            0 :   pari_puts("\n");
    2223            0 : }
    2224              : 
    2225              : /* s = digit n : list of entrees in functions_hash[n] (s = $: last entry)
    2226              :  *   = range m-n: functions_hash[m..n]
    2227              :  *   = identifier: entree for that identifier */
    2228              : void
    2229            0 : print_functions_hash(const char *s)
    2230              : {
    2231              :   long m, n, Max, Total;
    2232              :   entree *ep;
    2233              : 
    2234            0 :   if (isdigit((unsigned char)*s) || *s == '$')
    2235              :   {
    2236            0 :     m = functions_tblsz-1; n = atol(s);
    2237            0 :     if (*s=='$') n = m;
    2238            0 :     if (m<n) pari_err(e_MISC,"invalid range in print_functions_hash");
    2239            0 :     while (isdigit((unsigned char)*s)) s++;
    2240              : 
    2241            0 :     if (*s++ != '-') m = n;
    2242              :     else
    2243              :     {
    2244            0 :       if (*s !='$') m = minss(atol(s),m);
    2245            0 :       if (m<n) pari_err(e_MISC,"invalid range in print_functions_hash");
    2246              :     }
    2247              : 
    2248            0 :     for(; n<=m; n++)
    2249              :     {
    2250            0 :       pari_printf("*** hashcode = %lu\n",n);
    2251            0 :       for (ep=functions_hash[n]; ep; ep=ep->next) print_entree(ep);
    2252              :     }
    2253            0 :     return;
    2254              :   }
    2255            0 :   if (is_keyword_char(*s))
    2256              :   {
    2257            0 :     ep = is_entry(s);
    2258            0 :     if (!ep) pari_err(e_MISC,"no such function");
    2259            0 :     print_entree(ep); return;
    2260              :   }
    2261            0 :   if (*s=='-')
    2262              :   {
    2263            0 :     for (n=0; n<functions_tblsz; n++)
    2264              :     {
    2265            0 :       m=0;
    2266            0 :       for (ep=functions_hash[n]; ep; ep=ep->next) m++;
    2267            0 :       pari_printf("%3ld:%3ld ",n,m);
    2268            0 :       if (n%9 == 8) pari_putc('\n');
    2269              :     }
    2270            0 :     pari_putc('\n'); return;
    2271              :   }
    2272            0 :   Max = Total = 0;
    2273            0 :   for (n=0; n<functions_tblsz; n++)
    2274              :   {
    2275            0 :     long cnt = 0;
    2276            0 :     for (ep=functions_hash[n]; ep; ep=ep->next) { print_entree(ep); cnt++; }
    2277            0 :     Total += cnt;
    2278            0 :     if (cnt > Max) Max = cnt;
    2279              :   }
    2280            0 :   pari_printf("Total: %ld, Max: %ld\n", Total, Max);
    2281              : }
    2282              : 
    2283              : /********************************************************************/
    2284              : /**                                                                **/
    2285              : /**                        FORMATTED OUTPUT                        **/
    2286              : /**                                                                **/
    2287              : /********************************************************************/
    2288              : static const char *
    2289       101646 : get_var(long v, char *buf)
    2290              : {
    2291       101646 :   entree *ep = varentries[v];
    2292       101646 :   if (ep) return (char*)ep->name;
    2293            0 :   sprintf(buf,"t%d",(int)v); return buf;
    2294              : }
    2295              : 
    2296              : static void
    2297            0 : do_append(char **sp, char c, char *last, int count)
    2298              : {
    2299            0 :   if (*sp + count > last)
    2300            0 :     pari_err(e_MISC, "TeX variable name too long");
    2301            0 :   while (count--)
    2302            0 :     *(*sp)++ = c;
    2303            0 : }
    2304              : 
    2305              : static char *
    2306          105 : get_texvar(long v, char *buf, unsigned int len)
    2307              : {
    2308          105 :   entree *ep = varentries[v];
    2309          105 :   char *t = buf, *e = buf + len - 1;
    2310              :   const char *s;
    2311              : 
    2312          105 :   if (!ep) pari_err(e_MISC, "this object uses debugging variables");
    2313          105 :   s = ep->name;
    2314          105 :   if (strlen(s) >= len) pari_err(e_MISC, "TeX variable name too long");
    2315          210 :   while (isalpha((unsigned char)*s)) *t++ = *s++;
    2316          105 :   *t = 0;
    2317          105 :   if (isdigit((unsigned char)*s) || *s == '_') {
    2318            0 :     int seen1 = 0, seen = 0;
    2319              : 
    2320              :     /* Skip until the first non-underscore */
    2321            0 :     while (*s == '_') s++, seen++;
    2322              : 
    2323              :     /* Special-case integers and empty subscript */
    2324            0 :     if (*s == 0 || isdigit((unsigned char)*s))
    2325            0 :       seen++;
    2326              : 
    2327            0 :     do_append(&t, '_', e, 1);
    2328            0 :     do_append(&t, '{', e, 1);
    2329            0 :     do_append(&t, '[', e, seen - 1);
    2330              :     while (1) {
    2331            0 :       if (*s == '_')
    2332            0 :         seen1++, s++;
    2333              :       else {
    2334            0 :         if (seen1) {
    2335            0 :           do_append(&t, ']', e, (seen >= seen1 ? seen1 : seen) - 1);
    2336            0 :           do_append(&t, ',', e, 1);
    2337            0 :           do_append(&t, '[', e, seen1 - 1);
    2338            0 :           if (seen1 > seen)
    2339            0 :             seen = seen1;
    2340            0 :           seen1 = 0;
    2341              :         }
    2342            0 :         if (*s == 0)
    2343            0 :           break;
    2344            0 :         do_append(&t, *s++, e, 1);
    2345              :       }
    2346              :     }
    2347            0 :     do_append(&t, ']', e, seen - 1);
    2348            0 :     do_append(&t, '}', e, 1);
    2349            0 :     *t = 0;
    2350              :   }
    2351          105 :   return buf;
    2352              : }
    2353              : 
    2354              : void
    2355            0 : dbg_pari_heap(void)
    2356              : {
    2357              :   long nu, l, u, s;
    2358            0 :   pari_sp av = avma;
    2359            0 :   GEN adr = getheap();
    2360            0 :   pari_sp top = pari_mainstack->top, bot = pari_mainstack->bot;
    2361              : 
    2362            0 :   nu = (top-avma)/sizeof(long);
    2363            0 :   l = pari_mainstack->size/sizeof(long);
    2364            0 :   pari_printf("\n Top : %lx   Bottom : %lx   Current stack : %lx\n",
    2365              :               top, bot, avma);
    2366            0 :   pari_printf(" Used :                         %ld  long words  (%ld K)\n",
    2367            0 :               nu, nu/1024*sizeof(long));
    2368            0 :   pari_printf(" Available :                    %ld  long words  (%ld K)\n",
    2369            0 :               (l-nu), (l-nu)/1024*sizeof(long));
    2370            0 :   pari_printf(" Occupation of the PARI stack : %6.2f percent\n", 100.0*nu/l);
    2371            0 :   pari_printf(" %ld objects on heap occupy %ld long words\n\n",
    2372            0 :               itos(gel(adr,1)), itos(gel(adr,2)));
    2373            0 :   u = pari_var_next();
    2374            0 :   s = MAXVARN - pari_var_next_temp();
    2375            0 :   pari_printf(" %ld variable names used (%ld user + %ld private) out of %d\n\n",
    2376              :               u+s, u, s, MAXVARN);
    2377            0 :   set_avma(av);
    2378            0 : }
    2379              : 
    2380              : /* is to be printed as '0' */
    2381              : static long
    2382      3727091 : isnull(GEN g)
    2383              : {
    2384              :   long i;
    2385      3727091 :   switch (typ(g))
    2386              :   {
    2387      3093533 :     case t_INT:
    2388      3093533 :       return !signe(g);
    2389        12670 :     case t_COMPLEX:
    2390        12670 :       return isnull(gel(g,1)) && isnull(gel(g,2));
    2391        15939 :     case t_FFELT:
    2392        15939 :       return FF_equal0(g);
    2393         2093 :     case t_QUAD:
    2394         2093 :       return isnull(gel(g,2)) && isnull(gel(g,3));
    2395       102141 :     case t_FRAC: case t_RFRAC:
    2396       102141 :       return isnull(gel(g,1));
    2397       175405 :     case t_POL:
    2398       175503 :       for (i=lg(g)-1; i>1; i--)
    2399       162126 :         if (!isnull(gel(g,i))) return 0;
    2400        13377 :       return 1;
    2401              :   }
    2402       325310 :   return 0;
    2403              : }
    2404              : /* 0 coeff to be omitted in t_POL ? */
    2405              : static int
    2406      1761542 : isnull_for_pol(GEN g)
    2407              : {
    2408      1761542 :   switch(typ(g))
    2409              :   {
    2410         8253 :     case t_INTMOD: return !signe(gel(g,2));
    2411         5418 :     case t_POLMOD: return isnull_for_pol(gel(g,2));
    2412      1747871 :     default:       return isnull(g);
    2413              :   }
    2414              : }
    2415              : 
    2416              : /* return 1 or -1 if g is 1 or -1, 0 otherwise*/
    2417              : static long
    2418      1658231 : isone(GEN g)
    2419              : {
    2420              :   long i;
    2421      1658231 :   switch (typ(g))
    2422              :   {
    2423      1135497 :     case t_INT:
    2424      1135497 :       return (signe(g) && is_pm1(g))? signe(g): 0;
    2425         9093 :     case t_FFELT:
    2426         9093 :       return FF_equal1(g);
    2427        12257 :     case t_COMPLEX:
    2428        12257 :       return isnull(gel(g,2))? isone(gel(g,1)): 0;
    2429         1519 :     case t_QUAD:
    2430         1519 :       return isnull(gel(g,3))? isone(gel(g,2)): 0;
    2431        79783 :     case t_FRAC: case t_RFRAC:
    2432        79783 :       return isone(gel(g,1)) * isone(gel(g,2));
    2433       124501 :     case t_POL:
    2434       124501 :       if (!signe(g)) return 0;
    2435       123661 :       for (i=lg(g)-1; i>2; i--)
    2436       115205 :         if (!isnull(gel(g,i))) return 0;
    2437         8456 :       return isone(gel(g,2));
    2438              :   }
    2439       295581 :   return 0;
    2440              : }
    2441              : 
    2442              : /* if g is a "monomial", return its sign, 0 otherwise */
    2443              : static long
    2444       298162 : isfactor(GEN g)
    2445              : {
    2446              :   long i,deja,sig;
    2447       298162 :   switch(typ(g))
    2448              :   {
    2449       223318 :     case t_INT: case t_REAL:
    2450       223318 :       return (signe(g)<0)? -1: 1;
    2451        28063 :     case t_FRAC: case t_RFRAC:
    2452        28063 :       return isfactor(gel(g,1));
    2453         2366 :     case t_FFELT:
    2454         2366 :       return isfactor(FF_to_FpXQ_i(g));
    2455         2114 :     case t_COMPLEX:
    2456         2114 :       if (isnull(gel(g,1))) return isfactor(gel(g,2));
    2457         1442 :       if (isnull(gel(g,2))) return isfactor(gel(g,1));
    2458         1442 :       return 0;
    2459         1960 :     case t_PADIC:
    2460         1960 :       return !signe(padic_u(g));
    2461          532 :     case t_QUAD:
    2462          532 :       if (isnull(gel(g,2))) return isfactor(gel(g,3));
    2463          385 :       if (isnull(gel(g,3))) return isfactor(gel(g,2));
    2464          385 :       return 0;
    2465        27587 :     case t_POL: deja = 0; sig = 1;
    2466        77861 :       for (i=lg(g)-1; i>1; i--)
    2467        65100 :         if (!isnull_for_pol(gel(g,i)))
    2468              :         {
    2469        42161 :           if (deja) return 0;
    2470        27335 :           sig=isfactor(gel(g,i)); deja=1;
    2471              :         }
    2472        12761 :       return sig? sig: 1;
    2473          105 :     case t_SER:
    2474          490 :       for (i=lg(g)-1; i>1; i--)
    2475          469 :         if (!isnull(gel(g,i))) return 0;
    2476           21 :       return 1;
    2477            0 :     case t_CLOSURE:
    2478            0 :       return 0;
    2479              :   }
    2480        12117 :   return 1;
    2481              : }
    2482              : 
    2483              : /* return 1 if g is a "truc" (see anal.c) */
    2484              : static long
    2485        53256 : isdenom(GEN g)
    2486              : {
    2487              :   long i,deja;
    2488        53256 :   switch(typ(g))
    2489              :   {
    2490            0 :     case t_FRAC: case t_RFRAC:
    2491            0 :       return 0;
    2492            0 :     case t_COMPLEX: return isnull(gel(g,2));
    2493            0 :     case t_PADIC: return !signe(padic_u(g));
    2494            0 :     case t_QUAD: return isnull(gel(g,3));
    2495              : 
    2496         1785 :     case t_POL: deja = 0;
    2497        18368 :       for (i=lg(g)-1; i>1; i--)
    2498        17843 :         if (!isnull(gel(g,i)))
    2499              :         {
    2500         2415 :           if (deja) return 0;
    2501         1785 :           if (i==2) return isdenom(gel(g,2));
    2502         1785 :           if (!isone(gel(g,i))) return 0;
    2503         1155 :           deja=1;
    2504              :         }
    2505          525 :       return 1;
    2506            0 :     case t_SER:
    2507            0 :       for (i=lg(g)-1; i>1; i--)
    2508            0 :         if (!isnull(gel(g,i))) return 0;
    2509              :   }
    2510        51471 :   return 1;
    2511              : }
    2512              : 
    2513              : /********************************************************************/
    2514              : /**                                                                **/
    2515              : /**                           RAW OUTPUT                           **/
    2516              : /**                                                                **/
    2517              : /********************************************************************/
    2518              : /* ^e */
    2519              : static void
    2520          210 : texexpo(pari_str *S, long e)
    2521              : {
    2522          210 :   if (e != 1) {
    2523          105 :     str_putc(S, '^');
    2524          105 :     if (e >= 0 && e < 10)
    2525          105 :     { str_putc(S, '0' + e); }
    2526              :     else
    2527              :     {
    2528            0 :       str_putc(S, '{'); str_long(S, e); str_putc(S, '}');
    2529              :     }
    2530              :   }
    2531          210 : }
    2532              : static void
    2533       240169 : wrexpo(pari_str *S, long e)
    2534       240169 : { if (e != 1) { str_putc(S, '^'); str_long(S, e); } }
    2535              : 
    2536              : /* v^e */
    2537              : static void
    2538       240169 : VpowE(pari_str *S, const char *v, long e) { str_puts(S, v); wrexpo(S,e); }
    2539              : static void
    2540          210 : texVpowE(pari_str *S, const char *v, long e) { str_puts(S, v); texexpo(S,e); }
    2541              : static void
    2542       225266 : monome(pari_str *S, const char *v, long e)
    2543       225266 : { if (e) VpowE(S, v, e); else str_putc(S, '1'); }
    2544              : static void
    2545          203 : texnome(pari_str *S, const char *v, long e)
    2546          203 : { if (e) texVpowE(S, v, e); else str_putc(S, '1'); }
    2547              : 
    2548              : /* ( a ) */
    2549              : static void
    2550        15995 : paren(pariout_t *T, pari_str *S, GEN a)
    2551        15995 : { str_putc(S, '('); bruti(a,T,S); str_putc(S, ')'); }
    2552              : static void
    2553            0 : texparen(pariout_t *T, pari_str *S, GEN a)
    2554              : {
    2555            0 :   if (T->TeXstyle & TEXSTYLE_PAREN)
    2556            0 :     str_puts(S, " (");
    2557              :   else
    2558            0 :     str_puts(S, " \\left(");
    2559            0 :   texi(a,T,S);
    2560            0 :   if (T->TeXstyle & TEXSTYLE_PAREN)
    2561            0 :     str_puts(S, ") ");
    2562              :   else
    2563            0 :     str_puts(S, "\\right) ");
    2564            0 : }
    2565              : 
    2566              : /* * v^d */
    2567              : static void
    2568          140 : times_texnome(pari_str *S, const char *v, long d)
    2569          140 : { if (d) { str_puts(S, "\\*"); texnome(S,v,d); } }
    2570              : static void
    2571       186172 : times_monome(pari_str *S, const char *v, long d)
    2572       186172 : { if (d) { str_putc(S, '*'); monome(S,v,d); } }
    2573              : 
    2574              : /* write a * v^d */
    2575              : static void
    2576       180516 : wr_monome(pariout_t *T, pari_str *S, GEN a, const char *v, long d)
    2577              : {
    2578       180516 :   long sig = isone(a);
    2579              : 
    2580       180516 :   if (sig) {
    2581        31913 :     sp_sign_sp(T,S,sig); monome(S,v,d);
    2582              :   } else {
    2583       148603 :     sig = isfactor(a);
    2584       148603 :     if (sig) { sp_sign_sp(T,S,sig); bruti_sign(a,T,S,0); }
    2585        13055 :     else { sp_sign_sp(T,S,1); paren(T,S, a); }
    2586       148603 :     times_monome(S, v, d);
    2587              :   }
    2588       180516 : }
    2589              : static void
    2590          105 : wr_texnome(pariout_t *T, pari_str *S, GEN a, const char *v, long d)
    2591              : {
    2592          105 :   long sig = isone(a);
    2593              : 
    2594          105 :   str_putc(S, '\n'); /* Avoid TeX buffer overflow */
    2595          105 :   if (T->TeXstyle & TEXSTYLE_BREAK) str_puts(S, "\\PARIbreak ");
    2596              : 
    2597          105 :   if (sig) {
    2598           14 :     putsigne(S,sig); texnome(S,v,d);
    2599              :   } else {
    2600           91 :     sig = isfactor(a);
    2601           91 :     if (sig) { putsigne(S,sig); texi_sign(a,T,S,0); }
    2602            0 :     else { str_puts(S, " +"); texparen(T,S, a); }
    2603           91 :     times_texnome(S, v, d);
    2604              :   }
    2605          105 : }
    2606              : 
    2607              : static void
    2608       102493 : wr_lead_monome(pariout_t *T, pari_str *S, GEN a,const char *v, long d, int addsign)
    2609              : {
    2610       102493 :   long sig = isone(a);
    2611       102493 :   if (sig) {
    2612        64924 :     if (addsign && sig<0) str_putc(S, '-');
    2613        64924 :     monome(S,v,d);
    2614              :   } else {
    2615        37569 :     if (isfactor(a)) bruti_sign(a,T,S,addsign);
    2616         2940 :     else paren(T,S, a);
    2617        37569 :     times_monome(S, v, d);
    2618              :   }
    2619       102493 : }
    2620              : static void
    2621          119 : wr_lead_texnome(pariout_t *T, pari_str *S, GEN a,const char *v, long d, int addsign)
    2622              : {
    2623          119 :   long sig = isone(a);
    2624          119 :   if (sig) {
    2625           70 :     if (addsign && sig<0) str_putc(S, '-');
    2626           70 :     texnome(S,v,d);
    2627              :   } else {
    2628           49 :     if (isfactor(a)) texi_sign(a,T,S,addsign);
    2629            0 :     else texparen(T,S, a);
    2630           49 :     times_texnome(S, v, d);
    2631              :   }
    2632          119 : }
    2633              : 
    2634              : static void
    2635            0 : prints(GEN g, pariout_t *T, pari_str *S)
    2636            0 : { (void)T; str_long(S, (long)g); }
    2637              : 
    2638              : static void
    2639        14942 : quote_string(pari_str *S, char *s)
    2640              : {
    2641        14942 :   str_putc(S, '"');
    2642       513244 :   while (*s)
    2643              :   {
    2644       498302 :     char c=*s++;
    2645       498302 :     if (c=='\\' || c=='"' || c=='\033' || c=='\n' || c=='\t')
    2646              :     {
    2647         2454 :       str_putc(S, '\\');
    2648         2454 :       switch(c)
    2649              :       {
    2650         2146 :       case '\\': case '"': break;
    2651          308 :       case '\n':   c='n'; break;
    2652            0 :       case '\033': c='e'; break;
    2653            0 :       case '\t':   c='t'; break;
    2654              :       }
    2655              :     }
    2656       498302 :     str_putc(S, c);
    2657              :   }
    2658        14942 :   str_putc(S, '"');
    2659        14942 : }
    2660              : 
    2661              : static int
    2662      1428431 : print_0_or_pm1(GEN g, pari_str *S, int addsign)
    2663              : {
    2664              :   long r;
    2665      1428431 :   if (!g) { str_puts(S, "NULL"); return 1; }
    2666      1428431 :   if (isnull(g)) { str_putc(S, '0'); return 1; }
    2667      1205114 :   r = isone(g);
    2668      1205114 :   if (r)
    2669              :   {
    2670       196098 :     if (addsign && r<0) str_putc(S, '-');
    2671       196098 :     str_putc(S, '1'); return 1;
    2672              :   }
    2673      1009016 :   return 0;
    2674              : }
    2675              : 
    2676              : static void
    2677         4613 : print_precontext(GEN g, pari_str *S, long tex)
    2678              : {
    2679         4613 :   if (lg(g)<8 || lg(gel(g,7))==1) return;
    2680              :   else
    2681              :   {
    2682            0 :     long i, n  = closure_arity(g);
    2683            0 :     str_puts(S,"(");
    2684            0 :     for(i=1; i<=n; i++)
    2685              :     {
    2686            0 :       str_puts(S,"v");
    2687            0 :       if (tex) str_puts(S,"_{");
    2688            0 :       str_ulong(S,i);
    2689            0 :       if (tex) str_puts(S,"}");
    2690            0 :       if (i < n) str_puts(S,",");
    2691              :     }
    2692            0 :     str_puts(S,")->");
    2693              :   }
    2694              : }
    2695              : 
    2696              : static void
    2697         5410 : print_context(GEN g, pariout_t *T, pari_str *S, long tex)
    2698              : {
    2699         5410 :   GEN str = closure_get_text(g);
    2700         5410 :   if (lg(g)<8 || lg(gel(g,7))==1) return;
    2701           83 :   if (typ(str)==t_VEC && lg(gel(closure_get_dbg(g),3)) >= 2)
    2702           83 :   {
    2703           83 :     GEN v = closure_get_frame(g), d = gmael(closure_get_dbg(g),3,1);
    2704           83 :     long i, l = lg(v), n=0;
    2705          186 :     for(i=1; i<l; i++)
    2706          103 :       if (gel(d,i))
    2707          103 :         n++;
    2708           83 :     if (n==0) return;
    2709           83 :     str_puts(S,"my(");
    2710          186 :     for(i=1; i<l; i++)
    2711          103 :       if (gel(d,i))
    2712              :       {
    2713          103 :         entree *ep = (entree*) gel(d,i);
    2714          103 :         GEN vi = gel(v,l-i);
    2715          103 :         str_puts(S,ep->name);
    2716          103 :         if (!isintzero(vi))
    2717              :         {
    2718          103 :           str_putc(S,'=');
    2719          103 :           if (tex) texi(gel(v,l-i),T,S); else bruti(gel(v,l-i),T,S);
    2720              :         }
    2721          103 :         if (--n)
    2722           20 :           str_putc(S,',');
    2723              :       }
    2724           83 :     str_puts(S,");");
    2725              :   }
    2726              :   else
    2727              :   {
    2728            0 :     GEN v = closure_get_frame(g);
    2729            0 :     long i, l = lg(v), n  = closure_arity(g);
    2730            0 :     str_puts(S,"(");
    2731            0 :     for(i=1; i<=n; i++)
    2732              :     {
    2733            0 :       str_puts(S,"v");
    2734            0 :       if (tex) str_puts(S,"_{");
    2735            0 :       str_ulong(S,i);
    2736            0 :       if (tex) str_puts(S,"}");
    2737            0 :       str_puts(S,",");
    2738              :     }
    2739            0 :     for(i=1; i<l; i++)
    2740              :     {
    2741            0 :       if (tex) texi(gel(v,i),T,S); else bruti(gel(v,i),T,S);
    2742            0 :       if (i<l-1)
    2743            0 :         str_putc(S,',');
    2744              :     }
    2745            0 :     str_puts(S,")");
    2746              :   }
    2747              : }
    2748              : static void
    2749          392 : mat0n(pari_str *S, long n)
    2750          392 : { str_puts(S, "matrix(0,"); str_long(S, n); str_putc(S, ')'); }
    2751              : 
    2752              : static const char *
    2753        11088 : cxq_init(GEN g, long tg, GEN *a, GEN *b, char *buf)
    2754              : {
    2755        11088 :   int r = (tg==t_QUAD);
    2756        11088 :   *a = gel(g,r+1);
    2757        11088 :   *b = gel(g,r+2); return r? get_var(varn(gel(g,1)), buf): "I";
    2758              : }
    2759              : 
    2760              : static void
    2761            0 : print_coef(GEN g, long i, long j, pariout_t *T, pari_str *S)
    2762            0 : { (void)T; str_long(S, coeff(g,i,j)); }
    2763              : static void
    2764       239788 : print_gcoef(GEN g, long i, long j, pariout_t *T, pari_str *S)
    2765              : {
    2766       239788 :   GEN gij = gcoeff(g, i, j);
    2767       239788 :   if (typ(gij)==t_CLOSURE)
    2768           28 :   { str_putc(S, '('); bruti(gij, T, S); str_putc(S, ')'); }
    2769              :   else
    2770       239760 :     bruti(gij, T, S);
    2771       239788 : }
    2772              : 
    2773              : static void
    2774      1008739 : bruti_intern(GEN g, pariout_t *T, pari_str *S, int addsign)
    2775              : {
    2776      1008739 :   long l,i,j,r, tg = typ(g);
    2777              :   GEN a,b;
    2778              :   const char *v;
    2779              :   char buf[32];
    2780              : 
    2781      1008739 :   switch(tg)
    2782              :   {
    2783       573838 :     case t_INT:
    2784       573838 :       if (addsign && signe(g) < 0) str_putc(S, '-');
    2785       573838 :       str_absint(S, g); break;
    2786        34720 :     case t_REAL:
    2787              :     {
    2788              :       pari_sp av;
    2789        34720 :       str_alloc(S, lg(g)); /* careful! */
    2790        34720 :       av = avma;
    2791        34720 :       if (addsign && signe(g) < 0) str_putc(S, '-');
    2792        34720 :       str_puts(S, absrtostr(g, T->sp, (char)toupper((unsigned char)T->format), T->sigd) );
    2793        34720 :       set_avma(av); break;
    2794              :     }
    2795              : 
    2796        28819 :     case t_INTMOD: case t_POLMOD:
    2797        28819 :       str_puts(S, "Mod(");
    2798        28819 :       bruti(gel(g,2),T,S); comma_sp(T,S);
    2799        28819 :       bruti(gel(g,1),T,S); str_putc(S, ')'); break;
    2800              : 
    2801         4431 :     case t_FFELT:
    2802         4431 :       bruti_sign(FF_to_FpXQ_i(g),T,S,addsign);
    2803         4431 :       break;
    2804              : 
    2805        53256 :     case t_FRAC: case t_RFRAC:
    2806        53256 :       r = isfactor(gel(g,1)); if (!r) str_putc(S, '(');
    2807        53256 :       bruti_sign(gel(g,1),T,S,addsign);
    2808        53256 :       if (!r) str_putc(S, ')');
    2809        53256 :       str_putc(S, '/');
    2810        53256 :       r = isdenom(gel(g,2)); if (!r) str_putc(S, '(');
    2811        53256 :       bruti(gel(g,2),T,S);
    2812        53256 :       if (!r) str_putc(S, ')');
    2813        53256 :       break;
    2814              : 
    2815        11039 :     case t_COMPLEX: case t_QUAD: r = (tg==t_QUAD);
    2816        11039 :       v = cxq_init(g, tg, &a, &b, buf);
    2817        11039 :       if (isnull(a))
    2818              :       {
    2819         2254 :         wr_lead_monome(T,S,b,v,1,addsign);
    2820         5418 :         return;
    2821              :       }
    2822         8785 :       bruti_sign(a,T,S,addsign);
    2823         8785 :       if (!isnull(b)) wr_monome(T,S,b,v,1);
    2824         8785 :       break;
    2825              : 
    2826        96487 :     case t_POL: v = get_var(varn(g), buf);
    2827              :       /* hack: we want g[i] = coeff of degree i. */
    2828        96508 :       i = degpol(g); g += 2; while (isnull(gel(g,i))) i--;
    2829        96487 :       wr_lead_monome(T,S,gel(g,i),v,i,addsign);
    2830      1762682 :       while (i--)
    2831              :       {
    2832      1666195 :         a = gel(g,i);
    2833      1666195 :         if (!isnull_for_pol(a)) wr_monome(T,S,a,v,i);
    2834              :       }
    2835        96487 :       break;
    2836              : 
    2837         4151 :     case t_SER: v = get_var(varn(g), buf);
    2838         4151 :       i = valser(g);
    2839         4151 :       l = lg(g)-2;
    2840         4151 :       if (l)
    2841              :       {
    2842              :         /* See normalizeser(): Mod(0,2)*x^i*(1+O(x)), has valser = i+1 */
    2843         3752 :         if (l == 1 && !signe(g) && isexactzero(gel(g,2))) i--;
    2844              :         /* hack: we want g[i] = coeff of degree i */
    2845         3752 :         l += i; g -= i-2;
    2846         3752 :         wr_lead_monome(T,S,gel(g,i),v,i,addsign);
    2847        28378 :         while (++i < l)
    2848              :         {
    2849        24626 :           a = gel(g,i);
    2850        24626 :           if (!isnull_for_pol(a)) wr_monome(T,S,a,v,i);
    2851              :         }
    2852         3752 :         sp_sign_sp(T,S,1);
    2853              :       }
    2854         4151 :       str_puts(S, "O("); VpowE(S, v, i); str_putc(S, ')'); break;
    2855              : 
    2856         6783 :     case t_PADIC:
    2857              :     {
    2858         6783 :       GEN p = padic_p(g);
    2859              :       pari_sp av, av0;
    2860              :       char *ev;
    2861         6783 :       str_alloc(S, (precp(g)+1) * lgefint(p)); /* careful! */
    2862         6783 :       av0 = avma;
    2863         6783 :       ev = itostr(p);
    2864         6783 :       av = avma;
    2865         6783 :       i = valp(g); l = precp(g)+i;
    2866         6783 :       g = padic_u(g);
    2867        40075 :       for (; i<l; i++)
    2868              :       {
    2869        33292 :         g = dvmdii(g,p,&a);
    2870        33292 :         if (signe(a))
    2871              :         {
    2872        23100 :           if (!i || !is_pm1(a))
    2873              :           {
    2874        14049 :             str_absint(S, a); if (i) str_putc(S, '*');
    2875              :           }
    2876        23100 :           if (i) VpowE(S, ev,i);
    2877        23100 :           sp_sign_sp(T,S,1);
    2878              :         }
    2879        33292 :         if ((i & 0xff) == 0) g = gc_INT(av,g);
    2880              :       }
    2881         6783 :       str_puts(S, "O("); VpowE(S, ev,i); str_putc(S, ')');
    2882         6783 :       set_avma(av0); break;
    2883              :     }
    2884              : 
    2885          651 :     case t_QFB:
    2886          651 :       str_puts(S, "Qfb(");
    2887          651 :       bruti(gel(g,1),T,S); comma_sp(T,S);
    2888          651 :       bruti(gel(g,2),T,S); comma_sp(T,S);
    2889          651 :       bruti(gel(g,3),T,S);
    2890          651 :       str_putc(S, ')'); break;
    2891              : 
    2892       145327 :     case t_VEC: case t_COL:
    2893       145327 :       str_putc(S, '['); l = lg(g);
    2894       618316 :       for (i=1; i<l; i++)
    2895              :       {
    2896       472989 :         bruti(gel(g,i),T,S);
    2897       472989 :         if (i<l-1) comma_sp(T,S);
    2898              :       }
    2899       145327 :       str_putc(S, ']'); if (tg==t_COL) str_putc(S, '~');
    2900       145327 :       break;
    2901         8082 :     case t_VECSMALL: wr_vecsmall(T,S,g); break;
    2902              : 
    2903          711 :     case t_LIST:
    2904          711 :       switch (list_typ(g))
    2905              :       {
    2906          599 :       case t_LIST_RAW:
    2907          599 :         str_puts(S, "List([");
    2908          599 :         g = list_data(g);
    2909          599 :         l = g? lg(g): 1;
    2910         1929 :         for (i=1; i<l; i++)
    2911              :         {
    2912         1330 :           bruti(gel(g,i),T,S);
    2913         1330 :           if (i<l-1) comma_sp(T,S);
    2914              :         }
    2915          599 :         str_puts(S, "])"); break;
    2916          112 :       case t_LIST_MAP:
    2917          112 :         str_puts(S, "Map(");
    2918          112 :         bruti(maptomat_shallow(g),T,S);
    2919          112 :         str_puts(S, ")"); break;
    2920              :       }
    2921          711 :       break;
    2922         6024 :     case t_STR:
    2923         6024 :       quote_string(S, GSTR(g)); break;
    2924         8918 :     case t_ERROR:
    2925              :       {
    2926         8918 :         char *s = pari_err2str(g);
    2927         8918 :         str_puts(S, "error(");
    2928         8918 :         quote_string(S, s); pari_free(s);
    2929         8918 :         str_puts(S, ")"); break;
    2930              :       }
    2931         5403 :     case t_CLOSURE:
    2932         5403 :       if (lg(g)>=7)
    2933              :       {
    2934         5403 :         GEN str = closure_get_text(g);
    2935         5403 :         if (typ(str)==t_STR)
    2936              :         {
    2937         4613 :           print_precontext(g, S, 0);
    2938         4613 :           str_puts(S, GSTR(str));
    2939         4613 :           print_context(g, T, S, 0);
    2940              :         }
    2941              :         else
    2942              :         {
    2943          790 :           str_putc(S,'(');   str_puts(S,GSTR(gel(str,1)));
    2944          790 :           str_puts(S,")->");
    2945          790 :           print_context(g, T, S, 0);
    2946          790 :           str_puts(S,GSTR(gel(str,2)));
    2947              :         }
    2948              :       }
    2949              :       else
    2950              :       {
    2951            0 :         str_puts(S,"{\""); str_puts(S,GSTR(closure_get_code(g)));
    2952            0 :         str_puts(S,"\","); wr_vecsmall(T,S,closure_get_oper(g));
    2953            0 :         str_putc(S,',');   bruti(gel(g,4),T,S);
    2954            0 :         str_putc(S,',');   bruti(gel(g,5),T,S);
    2955            0 :         str_putc(S,'}');
    2956              :       }
    2957         5403 :       break;
    2958          763 :     case t_INFINITY: str_puts(S, inf_get_sign(g) == 1? "+oo": "-oo");
    2959          763 :       break;
    2960              : 
    2961        19336 :     case t_MAT:
    2962              :     {
    2963              :       void (*print)(GEN,long,long,pariout_t *,pari_str *);
    2964              : 
    2965        19336 :       r = lg(g); if (r==1) { str_puts(S, "[;]"); return; }
    2966        18391 :       l = lgcols(g); if (l==1) { mat0n(S, r-1); return; }
    2967        18118 :       print = (typ(gel(g,1)) == t_VECSMALL)? print_coef: print_gcoef;
    2968        18118 :       if (l==2)
    2969              :       {
    2970         5369 :         str_puts(S, "Mat(");
    2971         5369 :         if (r == 2 && (print != print_gcoef || typ(gcoeff(g,1,1)) != t_MAT))
    2972         1946 :         { print(g, 1, 1,T, S); str_putc(S, ')'); return; }
    2973              :       }
    2974        16172 :       str_putc(S, '[');
    2975        70763 :       for (i=1; i<l; i++)
    2976              :       {
    2977       292433 :         for (j=1; j<r; j++)
    2978              :         {
    2979       237842 :           print(g, i, j, T, S);
    2980       237842 :           if (j<r-1) comma_sp(T,S);
    2981              :         }
    2982        54591 :         if (i<l-1) semicolon_sp(T,S);
    2983              :       }
    2984        16172 :       str_putc(S, ']'); if (l==2) str_putc(S, ')');
    2985        16172 :       break;
    2986              :     }
    2987              : 
    2988            0 :     default: str_addr(S, *g);
    2989              :   }
    2990              : }
    2991              : 
    2992              : static void
    2993      1427915 : bruti_sign(GEN g, pariout_t *T, pari_str *S, int addsign)
    2994              : {
    2995      1427915 :   if (!print_0_or_pm1(g, S, addsign))
    2996      1008602 :     bruti_intern(g, T, S, addsign);
    2997      1427915 : }
    2998              : 
    2999              : static void
    3000        61006 : matbruti(GEN g, pariout_t *T, pari_str *S)
    3001              : {
    3002        61006 :   long i, j, r, w, l, *pad = NULL;
    3003              :   pari_sp av;
    3004              :   OUT_FUN print;
    3005              : 
    3006        61006 :   if (typ(g) != t_MAT) { bruti(g,T,S); return; }
    3007              : 
    3008         4451 :   r=lg(g); if (r==1) { str_puts(S, "[;]"); return; }
    3009         4220 :   l = lgcols(g); if (l==1) { mat0n(S, r-1); return; }
    3010         4101 :   str_putc(S, '\n');
    3011         4101 :   print = (typ(gel(g,1)) == t_VECSMALL)? prints: bruti;
    3012         4101 :   av = avma;
    3013         4101 :   w = term_width();
    3014         4101 :   if (2*r < w)
    3015              :   {
    3016         4094 :     long lgall = 2; /* opening [ and closing ] */
    3017              :     pari_sp av2;
    3018              :     pari_str str;
    3019         4094 :     pad = cgetg(l*r+1, t_VECSMALL); /* left on stack if (S->use_stack)*/
    3020         4094 :     av2 = avma;
    3021         4094 :     str_init(&str, 1);
    3022        14832 :     for (j=1; j<r; j++)
    3023              :     {
    3024        11052 :       GEN col = gel(g,j);
    3025        11052 :       long maxc = 0;
    3026        56529 :       for (i=1; i<l; i++)
    3027              :       {
    3028              :         long lgs;
    3029        45477 :         str.cur = str.string;
    3030        45477 :         print(gel(col,i),T,&str);
    3031        45477 :         lgs = str.cur - str.string;
    3032        45477 :         pad[j*l+i] = -lgs;
    3033        45477 :         if (maxc < lgs) maxc = lgs;
    3034              :       }
    3035        56529 :       for (i=1; i<l; i++) pad[j*l+i] += maxc;
    3036        11052 :       lgall += maxc + 1; /* column width, including separating space */
    3037        11052 :       if (lgall > w) { pad = NULL; break; } /* doesn't fit, abort padding */
    3038              :     }
    3039         4094 :     set_avma(av2);
    3040              :   }
    3041        16748 :   for (i=1; i<l; i++)
    3042              :   {
    3043        12647 :     str_putc(S, '[');
    3044        65668 :     for (j=1; j<r; j++)
    3045              :     {
    3046        53021 :       if (pad) {
    3047        40005 :         long white = pad[j*l+i];
    3048        79422 :         while (white-- > 0) str_putc(S, ' ');
    3049              :       }
    3050        53021 :       print(gcoeff(g,i,j),T,S); if (j<r-1) str_putc(S, ' ');
    3051              :     }
    3052        12647 :     if (i<l-1) str_puts(S, "]\n\n"); else str_puts(S, "]\n");
    3053              :   }
    3054         4101 :   if (!S->use_stack) set_avma(av);
    3055              : }
    3056              : 
    3057              : /********************************************************************/
    3058              : /**                                                                **/
    3059              : /**                           TeX OUTPUT                           **/
    3060              : /**                                                                **/
    3061              : /********************************************************************/
    3062              : /* this follows bruti_sign */
    3063              : static void
    3064          516 : texi_sign(GEN g, pariout_t *T, pari_str *S, int addsign)
    3065              : {
    3066              :   long tg,i,j,l,r;
    3067              :   GEN a,b;
    3068              :   const char *v;
    3069              :   char buf[67];
    3070              : 
    3071          516 :   if (print_0_or_pm1(g, S, addsign)) return;
    3072              : 
    3073          414 :   tg = typ(g);
    3074          414 :   switch(tg)
    3075              :   {
    3076          137 :     case t_INT: case t_REAL: case t_QFB:
    3077          137 :       bruti_intern(g, T, S, addsign); break;
    3078              : 
    3079            7 :     case t_INTMOD: case t_POLMOD:
    3080            7 :       texi(gel(g,2),T,S); str_puts(S, " mod ");
    3081            7 :       texi(gel(g,1),T,S); break;
    3082              : 
    3083           11 :     case t_FRAC:
    3084           11 :       if (addsign && isfactor(gel(g,1)) < 0) str_putc(S, '-');
    3085           11 :       str_puts(S, "\\frac{");
    3086           11 :       texi_sign(gel(g,1),T,S,0);
    3087           11 :       str_puts(S, "}{");
    3088           11 :       texi_sign(gel(g,2),T,S,0);
    3089           11 :       str_puts(S, "}"); break;
    3090              : 
    3091           14 :     case t_RFRAC:
    3092           14 :       str_puts(S, "\\frac{");
    3093           14 :       texi(gel(g,1),T,S); /* too complicated otherwise */
    3094           14 :       str_puts(S, "}{");
    3095           14 :       texi(gel(g,2),T,S);
    3096           14 :       str_puts(S, "}"); break;
    3097              : 
    3098            7 :     case t_FFELT:
    3099            7 :       bruti_sign(FF_to_FpXQ_i(g),T,S,addsign);
    3100            7 :       break;
    3101              : 
    3102           49 :     case t_COMPLEX: case t_QUAD: r = (tg==t_QUAD);
    3103           49 :       v = cxq_init(g, tg, &a, &b, buf);
    3104           49 :       if (isnull(a))
    3105              :       {
    3106           14 :         wr_lead_texnome(T,S,b,v,1,addsign);
    3107           14 :         break;
    3108              :       }
    3109           35 :       texi_sign(a,T,S,addsign);
    3110           35 :       if (!isnull(b)) wr_texnome(T,S,b,v,1);
    3111           35 :       break;
    3112              : 
    3113           98 :     case t_POL: v = get_texvar(varn(g), buf, sizeof(buf));
    3114              :       /* hack: we want g[i] = coeff of degree i. */
    3115           98 :       i = degpol(g); g += 2; while (isnull(gel(g,i))) i--;
    3116           98 :       wr_lead_texnome(T,S,gel(g,i),v,i,addsign);
    3117          294 :       while (i--)
    3118              :       {
    3119          196 :         a = gel(g,i);
    3120          196 :         if (!isnull_for_pol(a)) wr_texnome(T,S,a,v,i);
    3121              :       }
    3122           98 :       break;
    3123              : 
    3124            7 :     case t_SER: v = get_texvar(varn(g), buf, sizeof(buf));
    3125            7 :       i = valser(g);
    3126            7 :       if (lg(g)-2)
    3127              :       { /* hack: we want g[i] = coeff of degree i. */
    3128            7 :         l = i + lg(g)-2; g -= i-2;
    3129            7 :         wr_lead_texnome(T,S,gel(g,i),v,i,addsign);
    3130           14 :         while (++i < l)
    3131              :         {
    3132            7 :           a = gel(g,i);
    3133            7 :           if (!isnull_for_pol(a)) wr_texnome(T,S,a,v,i);
    3134              :         }
    3135            7 :         str_puts(S, "+ ");
    3136              :       }
    3137            7 :       str_puts(S, "O("); texnome(S,v,i); str_putc(S, ')'); break;
    3138              : 
    3139            7 :     case t_PADIC:
    3140              :     {
    3141            7 :       GEN p = padic_p(g);
    3142              :       pari_sp av;
    3143              :       char *ev;
    3144            7 :       str_alloc(S, (precp(g)+1) * lgefint(p)); /* careful! */
    3145            7 :       av = avma;
    3146            7 :       i = valp(g); l = precp(g)+i;
    3147            7 :       g = padic_u(g); ev = itostr(p);
    3148           21 :       for (; i<l; i++)
    3149              :       {
    3150           14 :         g = dvmdii(g,p,&a);
    3151           14 :         if (signe(a))
    3152              :         {
    3153            7 :           if (!i || !is_pm1(a))
    3154              :           {
    3155            7 :             str_absint(S, a); if (i) str_puts(S, "\\cdot");
    3156              :           }
    3157            7 :           if (i) texVpowE(S, ev,i);
    3158            7 :           str_putc(S, '+');
    3159              :         }
    3160              :       }
    3161            7 :       str_puts(S, "O("); texVpowE(S, ev,i); str_putc(S, ')');
    3162            7 :       set_avma(av); break;
    3163              :     }
    3164              : 
    3165            7 :     case t_VEC:
    3166            7 :       str_puts(S, "\\pmatrix{ "); l = lg(g);
    3167           21 :       for (i=1; i<l; i++)
    3168              :       {
    3169           14 :         texi(gel(g,i),T,S); if (i < l-1) str_putc(S, '&');
    3170              :       }
    3171            7 :       str_puts(S, "\\cr}\n"); break;
    3172              : 
    3173           14 :     case t_LIST:
    3174           14 :       switch(list_typ(g))
    3175              :       {
    3176            7 :       case t_LIST_RAW:
    3177            7 :         str_puts(S, "\\pmatrix{ ");
    3178            7 :         g = list_data(g);
    3179            7 :         l = g? lg(g): 1;
    3180           21 :         for (i=1; i<l; i++)
    3181              :         {
    3182           14 :           texi(gel(g,i),T,S); if (i < l-1) str_putc(S, '&');
    3183              :         }
    3184            7 :         str_puts(S, "\\cr}\n"); break;
    3185            7 :       case t_LIST_MAP:
    3186              :         {
    3187            7 :           pari_sp av = avma;
    3188            7 :           texi(maptomat_shallow(g),T,S);
    3189            7 :           set_avma(av);
    3190            7 :           break;
    3191              :         }
    3192              :       }
    3193           14 :       break;
    3194            7 :     case t_COL:
    3195            7 :       str_puts(S, "\\pmatrix{ "); l = lg(g);
    3196           21 :       for (i=1; i<l; i++)
    3197              :       {
    3198           14 :         texi(gel(g,i),T,S); str_puts(S, "\\cr\n");
    3199              :       }
    3200            7 :       str_putc(S, '}'); break;
    3201              : 
    3202            7 :     case t_VECSMALL:
    3203            7 :       str_puts(S, "\\pmatrix{ "); l = lg(g);
    3204           21 :       for (i=1; i<l; i++)
    3205              :       {
    3206           14 :         str_long(S, g[i]);
    3207           14 :         if (i < l-1) str_putc(S, '&');
    3208              :       }
    3209            7 :       str_puts(S, "\\cr}\n"); break;
    3210              : 
    3211            0 :     case t_STR:
    3212            0 :       str_puts(S, GSTR(g)); break;
    3213              : 
    3214            7 :     case t_CLOSURE:
    3215            7 :       if (lg(g)>=6)
    3216              :       {
    3217            7 :         GEN str = closure_get_text(g);
    3218            7 :         if (typ(str)==t_STR)
    3219              :         {
    3220            0 :           print_precontext(g, S, 1);
    3221            0 :           str_puts(S, GSTR(str));
    3222            0 :           print_context(g, T, S, 1);
    3223              :         }
    3224              :         else
    3225              :         {
    3226            7 :           str_putc(S,'(');          str_puts(S,GSTR(gel(str,1)));
    3227            7 :           str_puts(S,")\\mapsto ");
    3228            7 :           print_context(g, T, S, 1); str_puts(S,GSTR(gel(str,2)));
    3229              :         }
    3230              :       }
    3231              :       else
    3232              :       {
    3233            0 :         str_puts(S,"\\{\""); str_puts(S,GSTR(closure_get_code(g)));
    3234            0 :         str_puts(S,"\","); texi(gel(g,3),T,S);
    3235            0 :         str_putc(S,',');   texi(gel(g,4),T,S);
    3236            0 :         str_putc(S,',');   texi(gel(g,5),T,S); str_puts(S,"\\}");
    3237              :       }
    3238            7 :       break;
    3239           14 :     case t_INFINITY: str_puts(S, inf_get_sign(g) == 1? "+\\infty": "-\\infty");
    3240           14 :       break;
    3241              : 
    3242           21 :     case t_MAT:
    3243              :     {
    3244           21 :       str_puts(S, "\\pmatrix{\n "); r = lg(g);
    3245           21 :       if (r>1)
    3246              :       {
    3247           21 :         OUT_FUN print = (typ(gel(g,1)) == t_VECSMALL)? prints: texi;
    3248              : 
    3249           21 :         l = lgcols(g);
    3250           56 :         for (i=1; i<l; i++)
    3251              :         {
    3252           98 :           for (j=1; j<r; j++)
    3253              :           {
    3254           63 :             print(gcoeff(g,i,j),T,S); if (j<r-1) str_putc(S, '&');
    3255              :           }
    3256           35 :           str_puts(S, "\\cr\n ");
    3257              :         }
    3258              :       }
    3259           21 :       str_putc(S, '}'); break;
    3260              :     }
    3261              :   }
    3262              : }
    3263              : 
    3264              : /*******************************************************************/
    3265              : /**                                                               **/
    3266              : /**                        USER OUTPUT FUNCTIONS                  **/
    3267              : /**                                                               **/
    3268              : /*******************************************************************/
    3269              : static void
    3270            0 : _initout(pariout_t *T, char f, long sigd, long sp)
    3271              : {
    3272            0 :   T->format = f;
    3273            0 :   T->sigd = sigd;
    3274            0 :   T->sp = sp;
    3275            0 : }
    3276              : 
    3277              : static void
    3278        60995 : gen_output_fun(GEN x, pariout_t *T, OUT_FUN out)
    3279        60995 : { pari_sp av = avma; pari_puts( stack_GENtostr_fun(x,T,out) ); set_avma(av); }
    3280              : 
    3281              : void
    3282            0 : fputGEN_pariout(GEN x, pariout_t *T, FILE *out)
    3283              : {
    3284            0 :   pari_sp av = avma;
    3285            0 :   char *s = stack_GENtostr_fun(x, T, get_fun(T->prettyp));
    3286            0 :   if (*s) { set_last_newline(s[strlen(s)-1]); fputs(s, out); }
    3287            0 :   set_avma(av);
    3288            0 : }
    3289              : 
    3290              : void
    3291            0 : brute(GEN g, char f, long d)
    3292              : {
    3293            0 :   pariout_t T; _initout(&T,f,d,0);
    3294            0 :   gen_output_fun(g, &T, &bruti);
    3295            0 : }
    3296              : void
    3297            0 : matbrute(GEN g, char f, long d)
    3298              : {
    3299            0 :   pariout_t T; _initout(&T,f,d,1);
    3300            0 :   gen_output_fun(g, &T, &matbruti);
    3301            0 : }
    3302              : void
    3303            0 : texe(GEN g, char f, long d)
    3304              : {
    3305            0 :   pariout_t T; _initout(&T,f,d,0);
    3306            0 :   gen_output_fun(g, &T, &texi);
    3307            0 : }
    3308              : 
    3309              : void
    3310        60995 : gen_output(GEN x)
    3311              : {
    3312        60995 :   gen_output_fun(x, GP_DATA->fmt, get_fun(GP_DATA->fmt->prettyp));
    3313        60995 :   pari_putc('\n'); pari_flush();
    3314        60995 : }
    3315              : void
    3316            0 : output(GEN x)
    3317            0 : { brute(x,'g',-1); pari_putc('\n'); pari_flush(); }
    3318              : void
    3319            0 : outmat(GEN x)
    3320            0 : { matbrute(x,'g',-1); pari_putc('\n'); pari_flush(); }
    3321              : 
    3322              : /*******************************************************************/
    3323              : /**                            FILES                              **/
    3324              : /*******************************************************************/
    3325              : /* to cache '~' expansion */
    3326              : static char *homedir;
    3327              : /* last file read successfully from try_name() */
    3328              : static THREAD char *last_filename;
    3329              : /* stack of temporary files (includes all infiles + some output) */
    3330              : static THREAD pariFILE *last_tmp_file;
    3331              : /* stack of "permanent" (output) files */
    3332              : static THREAD pariFILE *last_file;
    3333              : 
    3334              : typedef struct gpfile
    3335              : {
    3336              :   const char *name;
    3337              :   FILE *fp;
    3338              :   int type;
    3339              :   long serial;
    3340              : } gpfile;
    3341              : 
    3342              : static THREAD gpfile *gp_file;
    3343              : static THREAD pari_stack s_gp_file;
    3344              : static THREAD long gp_file_serial;
    3345              : 
    3346              : #if defined(UNIX) || defined(__EMX__)
    3347              : #  include <fcntl.h>
    3348              : #  include <sys/stat.h> /* for open */
    3349              : #  ifdef __EMX__
    3350              : #    include <process.h>
    3351              : #  endif
    3352              : #  define HAVE_PIPES
    3353              : #endif
    3354              : #if defined(_WIN32)
    3355              : #  define HAVE_PIPES
    3356              : #endif
    3357              : #ifndef O_RDONLY
    3358              : #  define O_RDONLY 0
    3359              : #endif
    3360              : 
    3361              : pariFILE *
    3362        40462 : newfile(FILE *f, const char *name, int type)
    3363              : {
    3364        40462 :   pariFILE *file = (pariFILE*) pari_malloc(strlen(name) + 1 + sizeof(pariFILE));
    3365        40462 :   file->type = type;
    3366        40462 :   file->name = strcpy((char*)(file+1), name);
    3367        40462 :   file->file = f;
    3368        40462 :   file->next = NULL;
    3369        40462 :   if (type & mf_PERM)
    3370              :   {
    3371            0 :     file->prev = last_file;
    3372            0 :     last_file = file;
    3373              :   }
    3374              :   else
    3375              :   {
    3376        40462 :     file->prev = last_tmp_file;
    3377        40462 :     last_tmp_file = file;
    3378              :   }
    3379        40462 :   if (file->prev) (file->prev)->next = file;
    3380        40462 :   if (DEBUGLEVEL)
    3381            0 :     if (strcmp(name,"stdin") || DEBUGLEVEL > 9)
    3382            0 :       err_printf("I/O: new pariFILE %s (code %d) \n",name,type);
    3383        40462 :   return file;
    3384              : }
    3385              : 
    3386              : static void
    3387        40462 : pari_kill_file(pariFILE *f)
    3388              : {
    3389        40462 :   if ((f->type & mf_PIPE) == 0)
    3390              :   {
    3391        40454 :     if (f->file != stdin && fclose(f->file))
    3392            0 :       pari_warn(warnfile, "close", f->name);
    3393              :   }
    3394              : #ifdef HAVE_PIPES
    3395              :   else
    3396              :   {
    3397            8 :     if (f->type & mf_FALSE)
    3398              :     {
    3399            0 :       if (f->file != stdin && fclose(f->file))
    3400            0 :         pari_warn(warnfile, "close", f->name);
    3401            0 :       if (unlink(f->name)) pari_warn(warnfile, "delete", f->name);
    3402              :     }
    3403              :     else
    3404            8 :       if (pclose(f->file) < 0) pari_warn(warnfile, "close pipe", f->name);
    3405              :   }
    3406              : #endif
    3407        40462 :   if (DEBUGLEVEL)
    3408            0 :     if (strcmp(f->name,"stdin") || DEBUGLEVEL > 9)
    3409            0 :       err_printf("I/O: closing file %s (code %d) \n",f->name,f->type);
    3410        40462 :   pari_free(f);
    3411        40462 : }
    3412              : 
    3413              : void
    3414        40385 : pari_fclose(pariFILE *f)
    3415              : {
    3416        40385 :   if (f->next) (f->next)->prev = f->prev;
    3417        40385 :   else if (f == last_tmp_file) last_tmp_file = f->prev;
    3418            0 :   else if (f == last_file) last_file = f->prev;
    3419        40385 :   if (f->prev) (f->prev)->next = f->next;
    3420        40385 :   pari_kill_file(f);
    3421        40385 : }
    3422              : 
    3423              : static pariFILE *
    3424            0 : pari_open_file(FILE *f, const char *s, const char *mode)
    3425              : {
    3426            0 :   if (!f) pari_err_FILE("requested file", s);
    3427            0 :   if (DEBUGLEVEL)
    3428            0 :     if (strcmp(s,"stdin") || DEBUGLEVEL > 9)
    3429            0 :       err_printf("I/O: opening file %s (mode %s)\n", s, mode);
    3430            0 :   return newfile(f,s,0);
    3431              : }
    3432              : 
    3433              : pariFILE *
    3434            0 : pari_fopen_or_fail(const char *s, const char *mode)
    3435              : {
    3436            0 :   return pari_open_file(fopen(s, mode), s, mode);
    3437              : }
    3438              : pariFILE *
    3439            0 : pari_fopen(const char *s, const char *mode)
    3440              : {
    3441            0 :   FILE *f = fopen(s, mode);
    3442            0 :   return f? pari_open_file(f, s, mode): NULL;
    3443              : }
    3444              : 
    3445              : void
    3446       112212 : pari_fread_chars(void *b, size_t n, FILE *f)
    3447              : {
    3448       112212 :   if (fread(b, sizeof(char), n, f) < n)
    3449            0 :     pari_err_FILE("input file [fread]", "FILE*");
    3450       112212 : }
    3451              : 
    3452              : /* FIXME: HAS_FDOPEN & allow standard open() flags */
    3453              : #ifdef UNIX
    3454              : /* open tmpfile s (a priori for writing) avoiding symlink attacks */
    3455              : pariFILE *
    3456            0 : pari_safefopen(const char *s, const char *mode)
    3457              : {
    3458            0 :   long fd = open(s, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
    3459              : 
    3460            0 :   if (fd == -1) pari_err(e_MISC,"tempfile %s already exists",s);
    3461            0 :   return pari_open_file(fdopen(fd, mode), s, mode);
    3462              : }
    3463              : #else
    3464              : pariFILE *
    3465              : pari_safefopen(const char *s, const char *mode)
    3466              : {
    3467              :   return pari_fopen_or_fail(s, mode);
    3468              : }
    3469              : #endif
    3470              : 
    3471              : void
    3472            0 : pari_unlink(const char *s)
    3473              : {
    3474            0 :   if (unlink(s)) pari_warn(warner, "I/O: can\'t remove file %s", s);
    3475            0 :   else if (DEBUGLEVEL)
    3476            0 :     err_printf("I/O: removed file %s\n", s);
    3477            0 : }
    3478              : 
    3479              : /* Remove one INFILE from the stack. Reset pari_infile (to the most recent
    3480              :  * infile)
    3481              :  * Return -1, if we're trying to pop out stdin itself; 0 otherwise
    3482              :  * Check for leaked file handlers (temporary files) */
    3483              : int
    3484       373466 : popinfile(void)
    3485              : {
    3486       373466 :   pariFILE *f = last_tmp_file, *g;
    3487       373301 :   while (f)
    3488              :   {
    3489           22 :     if (f->type & mf_IN) break;
    3490            0 :     pari_warn(warner, "I/O: leaked file descriptor (%d): %s", f->type, f->name);
    3491            0 :     g = f; f = f->prev; pari_fclose(g);
    3492              :   }
    3493       373301 :   last_tmp_file = f; if (!f) return -1;
    3494           22 :   pari_fclose(last_tmp_file);
    3495           22 :   for (f = last_tmp_file; f; f = f->prev)
    3496            0 :     if (f->type & mf_IN) { pari_infile = f->file; return 0; }
    3497           22 :   pari_infile = stdin; return 0;
    3498              : }
    3499              : 
    3500              : /* delete all "temp" files open since last reference point F */
    3501              : void
    3502        13617 : tmp_restore(pariFILE *F)
    3503              : {
    3504        13617 :   pariFILE *f = last_tmp_file;
    3505        13617 :   int first = 1;
    3506        13631 :   while (f)
    3507              :   {
    3508           35 :     pariFILE *g = f->prev;
    3509           35 :     if (f == F) break;
    3510           14 :     pari_fclose(f); f = g;
    3511              :   }
    3512        13617 :   for (; f; f = f->prev) {
    3513           21 :     if (f->type & mf_IN) {
    3514           21 :       pari_infile = f->file;
    3515           21 :       if (DEBUGLEVEL>1)
    3516              :       {
    3517            0 :         first = 0;
    3518            0 :         err_printf("restoring pari_infile to %s\n", f->name);
    3519              :       }
    3520           21 :       break;
    3521              :     }
    3522              :   }
    3523        13617 :   if (!f) {
    3524        13596 :     pari_infile = stdin;
    3525        13596 :     if (DEBUGLEVEL>1 && (!first || DEBUGLEVEL > 9))
    3526              :     {
    3527            7 :       first = 0;
    3528            7 :       err_printf("gp_context_restore: restoring pari_infile to stdin\n");
    3529              :     }
    3530              :   }
    3531        13617 :   if (!first && DEBUGLEVEL>1) err_printf("done\n");
    3532        13617 : }
    3533              : 
    3534              : void
    3535       146815 : filestate_save(struct pari_filestate *file)
    3536              : {
    3537       146815 :   file->file = last_tmp_file;
    3538       146815 :   file->serial = gp_file_serial;
    3539       146815 : }
    3540              : 
    3541              : static void
    3542       380929 : filestate_close(long serial)
    3543              : {
    3544              :   long i;
    3545       380945 :   for (i = 0; i < s_gp_file.n; i++)
    3546           16 :     if (gp_file[i].fp && gp_file[i].serial >= serial)
    3547           16 :       gp_fileclose(i);
    3548       380929 :   gp_file_serial = serial;
    3549       380929 : }
    3550              : 
    3551              : void
    3552        13165 : filestate_restore(struct pari_filestate *file)
    3553              : {
    3554        13165 :   tmp_restore(file->file);
    3555        13165 :   filestate_close(file->serial);
    3556        13165 : }
    3557              : 
    3558              : static void
    3559       736802 : kill_file_stack(pariFILE **s)
    3560              : {
    3561       736802 :   pariFILE *f = *s;
    3562       736879 :   while (f)
    3563              :   {
    3564           77 :     pariFILE *t = f->prev;
    3565           77 :     pari_kill_file(f);
    3566           77 :     *s = f = t; /* have to update *s in case of ^C */
    3567              :   }
    3568       736802 : }
    3569              : 
    3570              : void
    3571           49 : killallfiles(void)
    3572              : {
    3573           49 :   kill_file_stack(&last_tmp_file);
    3574           49 :   pari_infile = stdin;
    3575           49 : }
    3576              : 
    3577              : void
    3578         1895 : pari_init_homedir(void)
    3579              : {
    3580         1895 :   homedir = NULL;
    3581         1895 : }
    3582              : 
    3583              : void
    3584         1887 : pari_close_homedir(void)
    3585              : {
    3586         1887 :   if (homedir) pari_free(homedir);
    3587         1887 : }
    3588              : 
    3589              : void
    3590       378308 : pari_init_files(void)
    3591              : {
    3592       378308 :   last_filename = NULL;
    3593       378308 :   last_tmp_file = NULL;
    3594       378308 :   last_file=NULL;
    3595       378308 :   pari_stack_init(&s_gp_file, sizeof(*gp_file), (void**)&gp_file);
    3596       378307 :   gp_file_serial = 0;
    3597       378307 : }
    3598              : 
    3599              : void
    3600       371856 : pari_thread_close_files(void)
    3601              : {
    3602       371856 :   popinfile(); /* look for leaks */
    3603       370283 :   kill_file_stack(&last_file);
    3604       369227 :   if (last_filename) pari_free(last_filename);
    3605       369227 :   kill_file_stack(&last_tmp_file);
    3606       367895 :   filestate_close(-1);
    3607       367290 :   pari_stack_delete(&s_gp_file);
    3608       366611 : }
    3609              : 
    3610              : void
    3611         1887 : pari_close_files(void)
    3612              : {
    3613         1887 :   if (pari_logfile) { fclose(pari_logfile); pari_logfile = NULL; }
    3614         1887 :   pari_infile = stdin;
    3615         1887 : }
    3616              : 
    3617              : static int
    3618            0 : ok_pipe(FILE *f)
    3619              : {
    3620            0 :   if (DEBUGLEVEL) err_printf("I/O: checking output pipe...\n");
    3621            0 :   pari_CATCH(CATCH_ALL) {
    3622            0 :     return 0;
    3623              :   }
    3624              :   pari_TRY {
    3625              :     int i;
    3626            0 :     fprintf(f,"\n\n"); fflush(f);
    3627            0 :     for (i=1; i<1000; i++) fprintf(f,"                  \n");
    3628            0 :     fprintf(f,"\n"); fflush(f);
    3629            0 :   } pari_ENDCATCH;
    3630            0 :   return 1;
    3631              : }
    3632              : 
    3633              : pariFILE *
    3634            8 : try_pipe(const char *cmd, int fl)
    3635              : {
    3636              : #ifndef HAVE_PIPES
    3637              :   pari_err(e_ARCH,"pipes");
    3638              :   return NULL;/*LCOV_EXCL_LINE*/
    3639              : #else
    3640              :   FILE *file;
    3641              :   const char *f;
    3642            8 :   VOLATILE int flag = fl;
    3643              : 
    3644              : #  ifdef __EMX__
    3645              :   if (_osmode == DOS_MODE) /* no pipes under DOS */
    3646              :   {
    3647              :     pari_sp av = avma;
    3648              :     char *s;
    3649              :     if (flag & mf_OUT) pari_err(e_ARCH,"pipes");
    3650              :     f = pari_unique_filename("pipe");
    3651              :     s = stack_malloc(strlen(cmd)+strlen(f)+4);
    3652              :     sprintf(s,"%s > %s",cmd,f);
    3653              :     file = system(s)? NULL: fopen(f,"r");
    3654              :     flag |= mf_FALSE; pari_free(f); set_avma(av);
    3655              :   }
    3656              :   else
    3657              : #  endif
    3658              :   {
    3659            8 :     file = (FILE *) popen(cmd, (flag & mf_OUT)? "w": "r");
    3660            8 :     if (flag & mf_OUT) {
    3661            0 :       if (!ok_pipe(file)) return NULL;
    3662            0 :       flag |= mf_PERM;
    3663              :     }
    3664            8 :     f = cmd;
    3665              :   }
    3666            8 :   if (!file) pari_err(e_MISC,"[pipe:] '%s' failed",cmd);
    3667            8 :   return newfile(file, f, mf_PIPE|flag);
    3668              : #endif
    3669              : }
    3670              : 
    3671              : char *
    3672        26752 : os_getenv(const char *s)
    3673              : {
    3674              : #ifdef HAS_GETENV
    3675        26752 :   return getenv(s);
    3676              : #else
    3677              :   (void) s; return NULL;
    3678              : #endif
    3679              : }
    3680              : 
    3681              : GEN
    3682            0 : gp_getenv(const char *s)
    3683              : {
    3684            0 :   char *t = os_getenv(s);
    3685            0 :   return t?strtoGENstr(t):gen_0;
    3686              : }
    3687              : 
    3688              : /* FIXME: HAS_GETPWUID */
    3689              : #if defined(UNIX) || defined(__EMX__)
    3690              : #include <pwd.h>
    3691              : #include <sys/types.h>
    3692              : /* user = "": use current uid */
    3693              : char *
    3694         3804 : pari_get_homedir(const char *user)
    3695              : {
    3696              :   struct passwd *p;
    3697         3804 :   char *dir = NULL;
    3698              : 
    3699         3804 :   if (!*user)
    3700              :   {
    3701         3804 :     if (homedir) dir = homedir;
    3702              :     else
    3703              :     {
    3704         1889 :       p = getpwuid(geteuid());
    3705         1889 :       if (p)
    3706              :       {
    3707         1889 :         dir = p->pw_dir;
    3708         1889 :         homedir = pari_strdup(dir); /* cache result */
    3709              :       }
    3710              :     }
    3711              :   }
    3712              :   else
    3713              :   {
    3714            0 :     p = getpwnam(user);
    3715            0 :     if (p) dir = p->pw_dir;
    3716              :     /* warn, but don't kill session on startup (when expanding path) */
    3717            0 :     if (!dir) pari_warn(warner,"can't expand ~%s", user? user: "");
    3718              :   }
    3719         3804 :   return dir;
    3720              : }
    3721              : #else
    3722              : char *
    3723              : pari_get_homedir(const char *user) { (void) user; return NULL; }
    3724              : #endif
    3725              : 
    3726              : /*******************************************************************/
    3727              : /**                                                               **/
    3728              : /**                   GP STANDARD INPUT AND OUTPUT                **/
    3729              : /**                                                               **/
    3730              : /*******************************************************************/
    3731              : #ifdef HAS_STAT
    3732              : static int
    3733           57 : is_dir_stat(const char *name)
    3734              : {
    3735              :   struct stat buf;
    3736           57 :   if (stat(name, &buf)) return 0;
    3737           57 :   return S_ISDIR(buf.st_mode);
    3738              : }
    3739              : #elif defined(HAS_OPENDIR)
    3740              : /* slow, but more portable than stat + S_ISDIR */
    3741              : static int
    3742              : is_dir_opendir(const char *name)
    3743              : {
    3744              :   DIR *d = opendir(name);
    3745              :   if (d) { (void)closedir(d); return 1; }
    3746              :   return 0;
    3747              : }
    3748              : #endif
    3749              : 
    3750              : 
    3751              : /* Does name point to a directory? */
    3752              : int
    3753           57 : pari_is_dir(const char *name)
    3754              : {
    3755              : #ifdef HAS_STAT
    3756           57 :   return is_dir_stat(name);
    3757              : #elif defined(HAS_OPENDIR)
    3758              :   return is_dir_opendir(name);
    3759              : #else
    3760              :   (void) name; return 0;
    3761              : #endif
    3762              : }
    3763              : 
    3764              : /* Does name point to a regular file? */
    3765              : /* If unknown, assume that it is indeed regular. */
    3766              : int
    3767           94 : pari_is_file(const char *name)
    3768              : {
    3769              : #ifdef HAS_STAT
    3770              :   struct stat buf;
    3771           94 :   if (stat(name, &buf)) return 1;
    3772           67 :   return S_ISREG(buf.st_mode);
    3773              : #else
    3774              :   (void) name; return 1;
    3775              : #endif
    3776              : }
    3777              : 
    3778              : int
    3779         1895 : pari_stdin_isatty(void)
    3780              : {
    3781              : #ifdef HAS_ISATTY
    3782         1895 :   return isatty( fileno(stdin) );
    3783              : #else
    3784              :   return 1;
    3785              : #endif
    3786              : }
    3787              : 
    3788              : /* expand tildes in filenames, return a malloc'ed buffer */
    3789              : static char *
    3790         5830 : _path_expand(const char *s)
    3791              : {
    3792              :   const char *t;
    3793         5830 :   char *ret, *dir = NULL;
    3794              : 
    3795         5830 :   if (*s != '~') return pari_strdup(s);
    3796         3804 :   s++; /* skip ~ */
    3797         3804 :   t = s; while (*t && *t != '/') t++;
    3798         3804 :   if (t == s)
    3799         3804 :     dir = pari_get_homedir("");
    3800              :   else
    3801              :   {
    3802            0 :     char *user = pari_strndup(s, t - s);
    3803            0 :     dir = pari_get_homedir(user);
    3804            0 :     pari_free(user);
    3805              :   }
    3806         3804 :   if (!dir) return pari_strdup(s);
    3807         3804 :   ret = (char*)pari_malloc(strlen(dir) + strlen(t) + 1);
    3808         3804 :   sprintf(ret,"%s%s",dir,t); return ret;
    3809              : }
    3810              : 
    3811              : /* expand environment variables in str, return a malloc'ed buffer
    3812              :  * assume no \ remain and str can be freed */
    3813              : static char *
    3814         5830 : _expand_env(char *str)
    3815              : {
    3816         5830 :   long i, l, len = 0, xlen = 16, xnum = 0;
    3817         5830 :   char *s = str, *s0 = s;
    3818         5830 :   char **x = (char **)pari_malloc(xlen * sizeof(char*));
    3819              : 
    3820        45767 :   while (*s)
    3821              :   {
    3822              :     char *env;
    3823        39937 :     if (*s != '$') { s++; continue; }
    3824            6 :     l = s - s0;
    3825            6 :     if (l) { x[xnum++] = pari_strndup(s0, l); len += l; }
    3826            6 :     if (xnum > xlen - 3) /* need room for possibly two more elts */
    3827              :     {
    3828            0 :       xlen <<= 1;
    3829            0 :       pari_realloc_ip((void**)&x, xlen * sizeof(char*));
    3830              :     }
    3831              : 
    3832            6 :     s0 = ++s; /* skip $ */
    3833           48 :     while (is_keyword_char(*s)) s++;
    3834            6 :     l = s - s0; env = pari_strndup(s0, l);
    3835            6 :     s0 = os_getenv(env);
    3836            6 :     if (!s0) pari_warn(warner,"undefined environment variable: %s",env);
    3837              :     else
    3838              :     {
    3839            6 :       l = strlen(s0);
    3840            6 :       if (l) { x[xnum++] = pari_strndup(s0,l); len += l; }
    3841              :     }
    3842            6 :     pari_free(env); s0 = s;
    3843              :   }
    3844         5830 :   l = s - s0;
    3845         5830 :   if (l) { x[xnum++] = pari_strndup(s0,l); len += l; }
    3846              : 
    3847         5830 :   s = (char*)pari_malloc(len+1); *s = 0;
    3848        11666 :   for (i = 0; i < xnum; i++) { (void)strcat(s, x[i]); pari_free(x[i]); }
    3849         5830 :   pari_free(str); pari_free(x); return s;
    3850              : }
    3851              : 
    3852              : char *
    3853         5830 : path_expand(const char *s)
    3854              : {
    3855              : #ifdef _WIN32
    3856              :   char *ss, *p;
    3857              :   ss = pari_strdup(s);
    3858              :   for (p = ss; *p != 0; ++p)
    3859              :     if (*p == '\\') *p = '/';
    3860              :   p = _expand_env(_path_expand(ss));
    3861              :   pari_free(ss);
    3862              :   return p;
    3863              : #else
    3864         5830 :   return _expand_env(_path_expand(s));
    3865              : #endif
    3866              : }
    3867              : 
    3868              : #ifdef HAS_STRFTIME
    3869              : #  include <time.h>
    3870              : void
    3871           16 : strftime_expand(const char *s, char *buf, long max)
    3872              : {
    3873              :   time_t t;
    3874           16 :   BLOCK_SIGINT_START
    3875           16 :   t = time(NULL);
    3876           16 :   (void)strftime(buf,max,s,localtime(&t));
    3877           16 :   BLOCK_SIGINT_END
    3878           16 : }
    3879              : #else
    3880              : void
    3881              : strftime_expand(const char *s, char *buf, long max)
    3882              : { strcpy(buf,s); }
    3883              : #endif
    3884              : 
    3885              : /* name is a malloc'ed (existing) filename. Accept it as new pari_infile
    3886              :  * (unzip if needed). */
    3887              : static pariFILE *
    3888        40363 : pari_get_infile(const char *name, FILE *file)
    3889              : {
    3890              : #ifdef ZCAT
    3891        40363 :   long l = strlen(name);
    3892        40363 :   const char *end = name + l-1;
    3893              : 
    3894        40363 :   if (l > 2 && (!strncmp(end-1,".Z",2)
    3895              : #ifdef GNUZCAT
    3896        40363 :              || !strncmp(end-2,".gz",3)
    3897              : #endif
    3898              :   ))
    3899              :   { /* compressed file (compress or gzip) */
    3900            0 :     char *cmd = stack_malloc(strlen(ZCAT) + l + 4);
    3901            0 :     sprintf(cmd,"%s \"%s\"",ZCAT,name);
    3902            0 :     fclose(file);
    3903            0 :     return try_pipe(cmd, mf_IN);
    3904              :   }
    3905              : #endif
    3906        40363 :   return newfile(file, name, mf_IN);
    3907              : }
    3908              : 
    3909              : pariFILE *
    3910        40404 : pari_fopengz(const char *s)
    3911              : {
    3912        40404 :   pari_sp av = avma;
    3913              :   char *name;
    3914              :   long l;
    3915        40404 :   FILE *f = fopen(s, "r");
    3916              :   pariFILE *pf;
    3917              : 
    3918        40404 :   if (f) return pari_get_infile(s, f);
    3919              : 
    3920              : #ifdef __EMSCRIPTEN__
    3921              :   if (pari_is_dir(pari_datadir))
    3922              :   {
    3923              :     pari_emscripten_wget(s);
    3924              :     f = fopen(s, "r");
    3925              :     if (f) return pari_get_infile(s, f);
    3926              :   }
    3927              : #endif
    3928           63 :   l = strlen(s);
    3929           63 :   name = stack_malloc(l + 3 + 1);
    3930           63 :   strcpy(name, s); (void)sprintf(name + l, ".gz");
    3931           63 :   f = fopen(name, "r");
    3932           63 :   pf = f ? pari_get_infile(name, f): NULL;
    3933           63 :   set_avma(av); return pf;
    3934              : }
    3935              : 
    3936              : static FILE*
    3937           22 : try_open(char *s)
    3938              : {
    3939           22 :   if (!pari_is_dir(s)) return fopen(s, "r");
    3940            0 :   pari_warn(warner,"skipping directory %s",s);
    3941            0 :   return NULL;
    3942              : }
    3943              : 
    3944              : void
    3945           20 : forpath_init(forpath_t *T, gp_path *path, const char *s)
    3946              : {
    3947           20 :   T->s = s;
    3948           20 :   T->ls = strlen(s);
    3949           20 :   T->dir = path->dirs;
    3950           20 : }
    3951              : char *
    3952           20 : forpath_next(forpath_t *T)
    3953              : {
    3954           20 :   char *t, *dir = T->dir[0];
    3955              : 
    3956           20 :   if (!dir) return NULL; /* done */
    3957              :   /* room for dir + '/' + s + '\0' */
    3958           20 :   t = (char*)pari_malloc(strlen(dir) + T->ls + 2);
    3959           20 :   if (!t) return NULL; /* can't happen but kills a warning */
    3960           20 :   sprintf(t,"%s/%s", dir, T->s);
    3961           20 :   T->dir++; return t;
    3962              : }
    3963              : 
    3964              : /* If a file called "name" exists (possibly after appending ".gp")
    3965              :  * record it in the file_stack (as a pipe if compressed).
    3966              :  * name is malloc'ed, we free it before returning
    3967              :  */
    3968              : static FILE *
    3969           22 : try_name(char *name)
    3970              : {
    3971           22 :   pari_sp av = avma;
    3972           22 :   char *s = name;
    3973           22 :   FILE *file = try_open(name);
    3974              : 
    3975           22 :   if (!file)
    3976              :   { /* try appending ".gp" to name */
    3977            0 :     s = stack_malloc(strlen(name)+4);
    3978            0 :     sprintf(s, "%s.gp", name);
    3979            0 :     file = try_open(s);
    3980              :   }
    3981           22 :   if (file)
    3982              :   {
    3983           22 :     if (! last_tmp_file)
    3984              :     {  /* empty file stack, record this name */
    3985           22 :       if (last_filename) pari_free(last_filename);
    3986           22 :       last_filename = pari_strdup(s);
    3987              :     }
    3988           22 :     file = pari_infile = pari_get_infile(s,file)->file;
    3989              :   }
    3990           22 :   pari_free(name); set_avma(av);
    3991           22 :   return file;
    3992              : }
    3993              : static FILE *
    3994            7 : switchin_last(void)
    3995              : {
    3996            7 :   char *s = last_filename;
    3997              :   FILE *file;
    3998            7 :   if (!s) pari_err(e_MISC,"You never gave me anything to read!");
    3999            0 :   file = try_open(s);
    4000            0 :   if (!file) pari_err_FILE("input file",s);
    4001            0 :   return pari_infile = pari_get_infile(s,file)->file;
    4002              : }
    4003              : 
    4004              : /* return 1 if s starts by '/' or './' or '../' */
    4005              : static int
    4006           22 : path_is_absolute(char *s)
    4007              : {
    4008              : #ifdef _WIN32
    4009              :   if( (*s >= 'A' && *s <= 'Z') ||
    4010              :       (*s >= 'a' && *s <= 'z') )
    4011              :   {
    4012              :       return *(s+1) == ':';
    4013              :   }
    4014              : #endif
    4015           22 :   if (*s == '/') return 1;
    4016           20 :   if (*s++ != '.') return 0;
    4017            0 :   if (*s == '/') return 1;
    4018            0 :   if (*s++ != '.') return 0;
    4019            0 :   return *s == '/';
    4020              : }
    4021              : 
    4022              : /* If name = "", re-read last file */
    4023              : FILE *
    4024           29 : switchin(const char *name)
    4025              : {
    4026              :   FILE *f;
    4027              :   char *s;
    4028              : 
    4029           29 :   if (!*name) return switchin_last();
    4030           22 :   s = path_expand(name);
    4031              :   /* if s is an absolute path, don't use dir_list */
    4032           22 :   if (path_is_absolute(s)) { if ((f = try_name(s))) return f; }
    4033              :   else
    4034              :   {
    4035              :     char *t;
    4036              :     forpath_t T;
    4037           20 :     forpath_init(&T, GP_DATA->path, s);
    4038           20 :     while ( (t = forpath_next(&T)) )
    4039           20 :       if ((f = try_name(t))) { pari_free(s); return f; }
    4040            0 :     pari_free(s);
    4041              :   }
    4042            0 :   pari_err_FILE("input file",name);
    4043              :   return NULL; /*LCOV_EXCL_LINE*/
    4044              : }
    4045              : 
    4046              : static int is_magic_ok(FILE *f);
    4047              : 
    4048              : static FILE *
    4049           94 : switchout_get_FILE(const char *name)
    4050              : {
    4051              :   FILE* f;
    4052              :   /* only for ordinary files (to avoid blocking on pipes). */
    4053           94 :   if (pari_is_file(name))
    4054              :   {
    4055           94 :     f = fopen(name, "r");
    4056           94 :     if (f)
    4057              :     {
    4058           67 :       int magic = is_magic_ok(f);
    4059           67 :       fclose(f);
    4060           67 :       if (magic) pari_err_FILE("binary output file [ use writebin ! ]", name);
    4061              :     }
    4062              :   }
    4063           94 :   f = fopen(name, "a");
    4064           94 :   if (!f) pari_err_FILE("output file",name);
    4065           94 :   return f;
    4066              : }
    4067              : 
    4068              : void
    4069            0 : switchout(const char *name)
    4070              : {
    4071            0 :   if (name)
    4072            0 :     pari_outfile = switchout_get_FILE(name);
    4073            0 :   else if (pari_outfile != stdout)
    4074              :   {
    4075            0 :     fclose(pari_outfile);
    4076            0 :     pari_outfile = stdout;
    4077              :   }
    4078            0 : }
    4079              : 
    4080              : /*******************************************************************/
    4081              : /**                                                               **/
    4082              : /**                SYSTEM, READSTR/EXTERNSTR/EXTERN               **/
    4083              : /**                                                               **/
    4084              : /*******************************************************************/
    4085              : static void
    4086           40 : check_secure(const char *s)
    4087              : {
    4088           40 :   if (GP_DATA->secure)
    4089            0 :     pari_err(e_MISC, "[secure mode]: system commands not allowed\nTried to run '%s'",s);
    4090           40 : }
    4091              : 
    4092              : long
    4093           28 : gpsystem(const char *s)
    4094              : {
    4095           28 :   int x = -1;
    4096              : #ifdef HAS_SYSTEM
    4097           28 :   check_secure(s);
    4098           28 :   x = system(s);
    4099           28 :   if (x < 0) pari_err(e_MISC, "system(\"%s\") failed", s);
    4100              : #if (defined(WIFEXITED)&&defined(WEXITSTATUS))
    4101           28 :   x = WIFEXITED(x)? WEXITSTATUS(x): -1; /* POSIX */
    4102              : #  endif
    4103              : #else
    4104              :   pari_err(e_ARCH,"system");
    4105              : #endif
    4106           28 :   return (long)x;
    4107              : }
    4108              : 
    4109              : static GEN
    4110            8 : get_lines(FILE *F)
    4111              : {
    4112            8 :   pari_sp av = avma;
    4113            8 :   long i, nz = 16;
    4114            8 :   GEN z = cgetg(nz + 1, t_VEC);
    4115            8 :   Buffer *b = new_buffer();
    4116              :   input_method IM;
    4117            8 :   IM.myfgets = (fgets_t)&fgets;
    4118            8 :   IM.file = (void*)F;
    4119            8 :   for(i = 1;;)
    4120           20 :   {
    4121           28 :     char *s = b->buf, *e;
    4122           28 :     if (!file_getline(b, &s, &IM)) break;
    4123           20 :     if (i > nz) { nz <<= 1; z = vec_lengthen(z, nz); }
    4124           20 :     e = s + strlen(s)-1;
    4125           20 :     if (*e == '\n') *e = 0;
    4126           20 :     gel(z,i++) = strtoGENstr(s);
    4127              :   }
    4128            8 :   delete_buffer(b); setlg(z, i);
    4129            8 :   return gc_GEN(av, z);
    4130              : }
    4131              : 
    4132              : GEN
    4133            4 : externstr(const char *s)
    4134              : {
    4135              :   pariFILE *F;
    4136              :   GEN z;
    4137            4 :   check_secure(s);
    4138            4 :   F = try_pipe(s, mf_IN);
    4139            4 :   z = get_lines(F->file);
    4140            4 :   pari_fclose(F); return z;
    4141              : }
    4142              : GEN
    4143            4 : gpextern(const char *s)
    4144              : {
    4145              :   pariFILE *F;
    4146              :   GEN z;
    4147            4 :   check_secure(s);
    4148            4 :   F = try_pipe(s, mf_IN);
    4149            4 :   z = gp_read_stream(F->file);
    4150            4 :   pari_fclose(F); return z ? z : gnil;
    4151              : }
    4152              : 
    4153              : GEN
    4154            4 : readstr(const char *s)
    4155              : {
    4156            4 :   GEN z = get_lines(switchin(s));
    4157            4 :   popinfile(); return z;
    4158              : }
    4159              : 
    4160              : /*******************************************************************/
    4161              : /**                                                               **/
    4162              : /**                    I/O IN BINARY FORM                         **/
    4163              : /**                                                               **/
    4164              : /*******************************************************************/
    4165              : static void
    4166          112 : pari_fread_longs(void *a, size_t c, FILE *d)
    4167          112 : { if (fread(a,sizeof(long),c,d) < c)
    4168            0 :     pari_err_FILE("input file [fread]", "FILE*"); }
    4169              : 
    4170              : static void
    4171          152 : _fwrite(const void *a, size_t b, size_t c, FILE *d)
    4172          152 : { if (fwrite(a,b,c,d) < c) pari_err_FILE("output file [fwrite]", "FILE*"); }
    4173              : static void
    4174          136 : _lfwrite(const void *a, size_t b, FILE *c) { _fwrite(a,sizeof(long),b,c); }
    4175              : static void
    4176           16 : _cfwrite(const void *a, size_t b, FILE *c) { _fwrite(a,sizeof(char),b,c); }
    4177              : 
    4178              : enum { BIN_GEN, NAM_GEN, VAR_GEN, RELINK_TABLE };
    4179              : 
    4180              : static long
    4181           88 : rd_long(FILE *f) { long L; pari_fread_longs(&L, 1UL, f); return L; }
    4182              : static void
    4183          112 : wr_long(long L, FILE *f) { _lfwrite(&L, 1UL, f); }
    4184              : 
    4185              : /* append x to file f */
    4186              : static void
    4187           24 : wrGEN(GEN x, FILE *f)
    4188              : {
    4189           24 :   GENbin *p = copy_bin_canon(x);
    4190           24 :   size_t L = p->len;
    4191              : 
    4192           24 :   wr_long(L,f);
    4193           24 :   if (L)
    4194              :   {
    4195           24 :     wr_long((long)p->x,f);
    4196           24 :     wr_long((long)p->base,f);
    4197           24 :     _lfwrite(GENbinbase(p), L,f);
    4198              :   }
    4199           24 :   pari_free((void*)p);
    4200           24 : }
    4201              : 
    4202              : static void
    4203           16 : wrstr(const char *s, FILE *f)
    4204              : {
    4205           16 :   size_t L = strlen(s)+1;
    4206           16 :   wr_long(L,f);
    4207           16 :   _cfwrite(s, L, f);
    4208           16 : }
    4209              : 
    4210              : static char *
    4211           16 : rdstr(FILE *f)
    4212              : {
    4213           16 :   size_t L = (size_t)rd_long(f);
    4214              :   char *s;
    4215           16 :   if (!L) return NULL;
    4216           16 :   s = (char*)pari_malloc(L);
    4217           16 :   pari_fread_chars(s, L, f); return s;
    4218              : }
    4219              : 
    4220              : static void
    4221            8 : writeGEN(GEN x, FILE *f)
    4222              : {
    4223            8 :   fputc(BIN_GEN,f);
    4224            8 :   wrGEN(x, f);
    4225            8 : }
    4226              : 
    4227              : static void
    4228           16 : writenamedGEN(GEN x, const char *s, FILE *f)
    4229              : {
    4230           16 :   fputc(x ? NAM_GEN : VAR_GEN,f);
    4231           16 :   wrstr(s, f);
    4232           16 :   if (x) wrGEN(x, f);
    4233           16 : }
    4234              : 
    4235              : /* read a GEN from file f */
    4236              : static GEN
    4237           24 : rdGEN(FILE *f)
    4238              : {
    4239           24 :   size_t L = (size_t)rd_long(f);
    4240              :   GENbin *p;
    4241              : 
    4242           24 :   if (!L) return gen_0;
    4243           24 :   p = (GENbin*)pari_malloc(sizeof(GENbin) + L*sizeof(long));
    4244           24 :   p->len  = L;
    4245           24 :   p->x    = (GEN)rd_long(f);
    4246           24 :   p->base = (GEN)rd_long(f);
    4247           24 :   p->rebase = &shiftaddress_canon;
    4248           24 :   pari_fread_longs(GENbinbase(p), L,f);
    4249           24 :   return bin_copy(p);
    4250              : }
    4251              : 
    4252              : /* read a binary object in file f. Set *ptc to the object "type":
    4253              :  * BIN_GEN: an anonymous GEN x; return x.
    4254              :  * NAM_GEN: a named GEN x, with name v; set 'v to x (changevalue) and return x
    4255              :  * VAR_GEN: a name v; create the (unassigned) variable v and return gnil
    4256              :  * RELINK_TABLE: a relinking table for gen_relink(), to replace old adresses
    4257              :  * in * the original session by new incarnations in the current session.
    4258              :  * H is the current relinking table
    4259              :  * */
    4260              : static GEN
    4261           36 : readobj(FILE *f, int *ptc, hashtable *H)
    4262              : {
    4263           36 :   int c = fgetc(f);
    4264           36 :   GEN x = NULL;
    4265           36 :   switch(c)
    4266              :   {
    4267            8 :     case BIN_GEN:
    4268            8 :       x = rdGEN(f);
    4269            8 :       if (H) gen_relink(x, H);
    4270            8 :       break;
    4271           16 :     case NAM_GEN:
    4272              :     case VAR_GEN:
    4273              :     {
    4274           16 :       char *s = rdstr(f);
    4275           16 :       if (!s) pari_err(e_MISC,"malformed binary file (no name)");
    4276           16 :       if (c == NAM_GEN)
    4277              :       {
    4278           16 :         x = rdGEN(f);
    4279           16 :         if (H) gen_relink(x, H);
    4280           16 :         err_printf("setting %s\n",s);
    4281           16 :         changevalue(varentries[fetch_user_var(s)], x);
    4282              :       }
    4283              :       else
    4284              :       {
    4285            0 :         pari_var_create(fetch_entry(s));
    4286            0 :         x = gnil;
    4287              :       }
    4288           16 :       break;
    4289              :     }
    4290            0 :     case RELINK_TABLE:
    4291            0 :       x = rdGEN(f); break;
    4292           12 :     case EOF: break;
    4293            0 :     default: pari_err(e_MISC,"unknown code in readobj");
    4294              :   }
    4295           36 :   *ptc = c; return x;
    4296              : }
    4297              : 
    4298              : #define MAGIC "\020\001\022\011-\007\020" /* ^P^A^R^I-^G^P */
    4299              : #ifdef LONG_IS_64BIT
    4300              : #  define ENDIAN_CHECK 0x0102030405060708L
    4301              : #else
    4302              : #  define ENDIAN_CHECK 0x01020304L
    4303              : #endif
    4304              : static const long BINARY_VERSION = 1; /* since 2.2.9 */
    4305              : 
    4306              : static int
    4307           79 : is_magic_ok(FILE *f)
    4308              : {
    4309           79 :   pari_sp av = avma;
    4310           79 :   size_t L = strlen(MAGIC);
    4311           79 :   char *s = stack_malloc(L);
    4312           79 :   return gc_int(av, fread(s,1,L, f) == L && strncmp(s,MAGIC,L) == 0);
    4313              : }
    4314              : 
    4315              : static int
    4316           12 : is_sizeoflong_ok(FILE *f)
    4317              : {
    4318              :   char c;
    4319           12 :   return (fread(&c,1,1, f) == 1 && c == (char)sizeof(long));
    4320              : }
    4321              : 
    4322              : static int
    4323           24 : is_long_ok(FILE *f, long L)
    4324              : {
    4325              :   long c;
    4326           24 :   return (fread(&c,sizeof(long),1, f) == 1 && c == L);
    4327              : }
    4328              : 
    4329              : /* return 1 if valid binary file */
    4330              : static int
    4331           12 : check_magic(const char *name, FILE *f)
    4332              : {
    4333           12 :   if (!is_magic_ok(f))
    4334            0 :     pari_warn(warner, "%s is not a GP binary file",name);
    4335           12 :   else if (!is_sizeoflong_ok(f))
    4336            0 :     pari_warn(warner, "%s not written for a %ld bit architecture",
    4337              :                name, sizeof(long)*8);
    4338           12 :   else if (!is_long_ok(f, ENDIAN_CHECK))
    4339            0 :     pari_warn(warner, "unexpected endianness in %s",name);
    4340           12 :   else if (!is_long_ok(f, BINARY_VERSION))
    4341            0 :     pari_warn(warner, "%s written by an incompatible version of GP",name);
    4342           12 :   else return 1;
    4343            0 :   return 0;
    4344              : }
    4345              : 
    4346              : static void
    4347           12 : write_magic(FILE *f)
    4348              : {
    4349           12 :   fprintf(f, MAGIC);
    4350           12 :   fprintf(f, "%c", (char)sizeof(long));
    4351           12 :   wr_long(ENDIAN_CHECK, f);
    4352           12 :   wr_long(BINARY_VERSION, f);
    4353           12 : }
    4354              : 
    4355              : int
    4356           18 : file_is_binary(FILE *f)
    4357              : {
    4358           18 :   int r, c = fgetc(f);
    4359           18 :   ungetc(c,f);
    4360           18 :   r = (c != EOF && isprint((unsigned char)c) == 0 && isspace((unsigned char)c) == 0);
    4361              : #ifdef _WIN32
    4362              :   if (r) { setmode(fileno(f), _O_BINARY); rewind(f); }
    4363              : #endif
    4364           18 :   return r;
    4365              : }
    4366              : 
    4367              : void
    4368           12 : writebin(const char *name, GEN x)
    4369              : {
    4370           12 :   FILE *f = fopen(name,"rb");
    4371           12 :   pari_sp av = avma;
    4372              :   GEN V;
    4373           12 :   int already = f? 1: 0;
    4374              : 
    4375           12 :   if (f) {
    4376            0 :     int ok = check_magic(name,f);
    4377            0 :     fclose(f);
    4378            0 :     if (!ok) pari_err_FILE("binary output file",name);
    4379              :   }
    4380           12 :   f = fopen(name,"ab");
    4381           12 :   if (!f) pari_err_FILE("binary output file",name);
    4382           12 :   if (!already) write_magic(f);
    4383              : 
    4384           12 :   V = copybin_unlink(x);
    4385           12 :   if (lg(gel(V,1)) > 1)
    4386              :   {
    4387            0 :     fputc(RELINK_TABLE,f);
    4388            0 :     wrGEN(V, f);
    4389              :   }
    4390           12 :   if (x) writeGEN(x,f);
    4391              :   else
    4392              :   {
    4393              :     entree *ep;
    4394              :     long i;
    4395          544 :     for (i = 0; i < functions_tblsz; i++)
    4396         6160 :       for (ep = functions_hash[i]; ep; ep = ep->next)
    4397         5620 :         if (EpVALENCE(ep) == EpVAR) writenamedGEN((GEN)ep->value,ep->name,f);
    4398              :   }
    4399           12 :   set_avma(av); fclose(f);
    4400           12 : }
    4401              : 
    4402              : /* read all objects in f. If f contains BIN_GEN that would be silently ignored
    4403              :  * [i.e f contains more than one objet, not all of them 'named GENs'], return
    4404              :  * them all in a vector and set 'vector'. */
    4405              : GEN
    4406           12 : readbin(const char *name, FILE *f, int *vector)
    4407              : {
    4408           12 :   pari_sp av = avma;
    4409           12 :   hashtable *H = NULL;
    4410              :   pari_stack s_obj;
    4411              :   GEN obj, x, y;
    4412              :   int cy;
    4413           12 :   if (vector) *vector = 0;
    4414           12 :   if (!check_magic(name,f)) return NULL;
    4415           12 :   pari_stack_init(&s_obj, sizeof(GEN), (void**)&obj);
    4416              :   /* HACK: push codeword so as to be able to treat s_obj.data as a t_VEC */
    4417           12 :   pari_stack_pushp(&s_obj, (void*) (evaltyp(t_VEC)|_evallg(1)));
    4418           12 :   x = gnil;
    4419           36 :   while ((y = readobj(f, &cy, H)))
    4420              :   {
    4421           24 :     x = y;
    4422           24 :     switch(cy)
    4423              :     {
    4424            8 :       case BIN_GEN:
    4425            8 :         pari_stack_pushp(&s_obj, (void*)y); break;
    4426            0 :       case RELINK_TABLE:
    4427            0 :         if (H) hash_destroy(H);
    4428            0 :         H = hash_from_link(gel(y,1),gel(y,2), 0);
    4429              :     }
    4430              :   }
    4431           12 :   if (H) hash_destroy(H);
    4432           12 :   switch(s_obj.n) /* >= 1 */
    4433              :   {
    4434            4 :     case 1: break; /* nothing but the codeword */
    4435            8 :     case 2: x = gel(obj,1); break; /* read a single BIN_GEN */
    4436            0 :     default: /* more than one BIN_GEN */
    4437            0 :       setlg(obj, s_obj.n);
    4438            0 :       if (DEBUGLEVEL)
    4439            0 :         pari_warn(warner,"%ld unnamed objects read. Returning then in a vector",
    4440            0 :                   s_obj.n - 1);
    4441            0 :       x = gc_GEN(av, obj);
    4442            0 :       if (vector) *vector = 1;
    4443              :   }
    4444           12 :   pari_stack_delete(&s_obj);
    4445           12 :   return x;
    4446              : }
    4447              : 
    4448              : /*******************************************************************/
    4449              : /**                                                               **/
    4450              : /**                             GP I/O                            **/
    4451              : /**                                                               **/
    4452              : /*******************************************************************/
    4453              : /* print a vector of GENs, in output context 'out', using 'sep' as a
    4454              :  * separator between sucessive entries [ NULL = no separator ]*/
    4455              : 
    4456              : static void
    4457       148603 : str_print0(pari_str *S, const char *sep, GEN g, long flag)
    4458              : {
    4459       148603 :   pari_sp av = avma;
    4460       148603 :   OUT_FUN f = get_fun(flag);
    4461       148603 :   long i, l = lg(g);
    4462       444854 :   for (i = 1; i < l; i++)
    4463              :   {
    4464       296251 :     GEN x = gel(g,i);
    4465       296251 :     if (typ(x) == t_STR) str_puts(S, GSTR(x)); else f(x, GP_DATA->fmt, S);
    4466       296251 :     if (sep && i+1 < l) str_puts(S, sep);
    4467       296251 :     if (!S->use_stack) set_avma(av);
    4468              :   }
    4469       148603 :   *(S->cur) = 0;
    4470       148603 : }
    4471              : 
    4472              : void
    4473       116810 : out_print0(PariOUT *out, const char *sep, GEN g, long flag)
    4474              : {
    4475       116810 :   pari_sp av = avma;
    4476              :   pari_str S;
    4477       116810 :   str_init(&S,1);
    4478       116810 :   str_print0(&S, sep, g, flag);
    4479       116810 :   str_putc(&S,'\n'); *(S.cur) = 0;
    4480       116810 :   out_puts(out, S.string);
    4481       116810 :   set_avma(av);
    4482       116810 : }
    4483              : 
    4484              : void
    4485        20496 : out_print1(PariOUT *out, const char *sep, GEN g, long flag)
    4486              : {
    4487        20496 :   pari_sp av = avma;
    4488              :   pari_str S;
    4489        20496 :   str_init(&S,1);
    4490        20496 :   str_print0(&S, sep, g, flag);
    4491        20496 :   out_puts(out, S.string);
    4492        20496 :   set_avma(av);
    4493        20496 : }
    4494              : 
    4495              : /* see print0(). Returns pari_malloc()ed string */
    4496              : char *
    4497        11189 : RgV_to_str(GEN g, long flag)
    4498              : {
    4499        11189 :   pari_str S; str_init(&S,0);
    4500        11189 :   str_print0(&S, NULL, g, flag);
    4501        11189 :   return S.string;
    4502              : }
    4503              : 
    4504              : static GEN
    4505        11189 : Str_fun(GEN g, long flag) {
    4506        11189 :   char *t = RgV_to_str(g, flag);
    4507        11189 :   GEN z = strtoGENstr(t);
    4508        11189 :   pari_free(t); return z;
    4509              : }
    4510              : GEN
    4511        11063 : Str(GEN g)    { return Str_fun(g, f_RAW); }
    4512              : GEN
    4513          126 : strtex(GEN g) { return Str_fun(g, f_TEX); }
    4514              : GEN
    4515            0 : strexpand(GEN g) {
    4516            0 :   char *s = RgV_to_str(g, f_RAW), *t = path_expand(s);
    4517            0 :   GEN z = strtoGENstr(t);
    4518            0 :   pari_free(t); pari_free(s); return z;
    4519              : }
    4520              : 
    4521              : /* display s, followed by the element of g */
    4522              : char *
    4523           14 : pari_sprint0(const char *s, GEN g, long flag)
    4524              : {
    4525           14 :   pari_str S; str_init(&S, 0);
    4526           14 :   str_puts(&S, s);
    4527           14 :   str_print0(&S, NULL, g, flag);
    4528           14 :   return S.string;
    4529              : }
    4530              : 
    4531              : static void
    4532           94 : print0_file(FILE *out, GEN g, long flag)
    4533              : {
    4534           94 :   pari_sp av = avma;
    4535           94 :   pari_str S; str_init(&S, 1);
    4536           94 :   str_print0(&S, NULL, g, flag);
    4537           94 :   fputs(S.string, out);
    4538           94 :   set_avma(av);
    4539           94 : }
    4540              : 
    4541              : static void
    4542       115487 : printfl_0(GEN g, long flag) { out_print0(pariOut, NULL, g, flag); }
    4543              : static void
    4544        20468 : printfl_1(GEN g, long flag) { out_print1(pariOut, NULL, g, flag); }
    4545              : void
    4546         1323 : printsep(const char *s, GEN g)
    4547         1323 : { out_print0(pariOut, s, g, f_RAW); pari_flush(); }
    4548              : void
    4549           21 : printsep1(const char *s, GEN g)
    4550           21 : { out_print1(pariOut, s, g, f_RAW); pari_flush(); }
    4551              : 
    4552              : static char *
    4553        80036 : sm_dopr(const char *fmt, GEN arg_vector, va_list args)
    4554              : {
    4555        80036 :   pari_str s; str_init(&s, 0);
    4556        80035 :   str_arg_vprintf(&s, fmt, arg_vector, args);
    4557        80014 :   return s.string;
    4558              : }
    4559              : char *
    4560        78573 : pari_vsprintf(const char *fmt, va_list ap)
    4561        78573 : { return sm_dopr(fmt, NULL, ap); }
    4562              : 
    4563              : /* dummy needed to pass an empty va_list to sm_dopr */
    4564              : static char *
    4565         1463 : dopr_arg_vector(GEN arg_vector, const char* fmt, ...)
    4566              : {
    4567              :   va_list ap;
    4568              :   char *s;
    4569         1463 :   va_start(ap, fmt);
    4570         1463 :   s = sm_dopr(fmt, arg_vector, ap);
    4571         1442 :   va_end(ap); return s;
    4572              : }
    4573              : /* GP only */
    4574              : void
    4575          742 : printf0(const char *fmt, GEN args)
    4576          742 : { char *s = dopr_arg_vector(args, fmt);
    4577          721 :   pari_puts(s); pari_free(s); pari_flush(); }
    4578              : /* GP only */
    4579              : GEN
    4580          721 : strprintf(const char *fmt, GEN args)
    4581          721 : { char *s = dopr_arg_vector(args, fmt);
    4582          721 :   GEN z = strtoGENstr(s); pari_free(s); return z; }
    4583              : 
    4584              : void
    4585        14702 : out_vprintf(PariOUT *out, const char *fmt, va_list ap)
    4586              : {
    4587        14702 :   char *s = pari_vsprintf(fmt, ap);
    4588        14702 :   out_puts(out, s); pari_free(s);
    4589        14702 : }
    4590              : void
    4591          757 : pari_vprintf(const char *fmt, va_list ap) { out_vprintf(pariOut, fmt, ap); }
    4592              : 
    4593              : void
    4594          355 : err_printf(const char* fmt, ...)
    4595              : {
    4596          355 :   va_list args; va_start(args, fmt);
    4597          355 :   out_vprintf(pariErr,fmt,args); va_end(args);
    4598          355 : }
    4599              : 
    4600              : /* variadic version of printf0 */
    4601              : void
    4602        12669 : out_printf(PariOUT *out, const char *fmt, ...)
    4603              : {
    4604        12669 :   va_list args; va_start(args,fmt);
    4605        12669 :   out_vprintf(out,fmt,args); va_end(args);
    4606        12669 : }
    4607              : void
    4608          757 : pari_printf(const char *fmt, ...) /* variadic version of printf0 */
    4609              : {
    4610          757 :   va_list args; va_start(args,fmt);
    4611          757 :   pari_vprintf(fmt,args); va_end(args);
    4612          757 : }
    4613              : 
    4614              : GEN
    4615         2000 : gvsprintf(const char *fmt, va_list ap)
    4616              : {
    4617         2000 :   char *s = pari_vsprintf(fmt, ap);
    4618         1999 :   GEN z = strtoGENstr(s);
    4619         1999 :   pari_free(s); return z;
    4620              : }
    4621              : 
    4622              : char *
    4623        19146 : pari_sprintf(const char *fmt, ...) /* variadic version of strprintf */
    4624              : {
    4625              :   char *s;
    4626              :   va_list ap;
    4627        19146 :   va_start(ap, fmt);
    4628        19146 :   s = pari_vsprintf(fmt, ap);
    4629        19146 :   va_end(ap); return s;
    4630              : }
    4631              : 
    4632              : void
    4633       148096 : str_printf(pari_str *S, const char *fmt, ...)
    4634              : {
    4635       148096 :   va_list ap; va_start(ap, fmt);
    4636       148096 :   str_arg_vprintf(S, fmt, NULL, ap);
    4637       148096 :   va_end(ap);
    4638       148096 : }
    4639              : 
    4640              : char *
    4641        42725 : stack_sprintf(const char *fmt, ...)
    4642              : {
    4643              :   char *s, *t;
    4644              :   va_list ap;
    4645        42725 :   va_start(ap, fmt);
    4646        42725 :   s = pari_vsprintf(fmt, ap);
    4647        42725 :   va_end(ap);
    4648        42725 :   t = stack_strdup(s);
    4649        42725 :   pari_free(s); return t;
    4650              : }
    4651              : 
    4652              : GEN
    4653         1603 : gsprintf(const char *fmt, ...) /* variadic version of gvsprintf */
    4654              : {
    4655              :   GEN s;
    4656              :   va_list ap;
    4657         1603 :   va_start(ap, fmt);
    4658         1603 :   s = gvsprintf(fmt, ap);
    4659         1603 :   va_end(ap); return s;
    4660              : }
    4661              : 
    4662              : /* variadic version of fprintf0. FIXME: fprintf0 not yet available */
    4663              : void
    4664            0 : pari_vfprintf(FILE *file, const char *fmt, va_list ap)
    4665              : {
    4666            0 :   char *s = pari_vsprintf(fmt, ap);
    4667            0 :   fputs(s, file); pari_free(s);
    4668            0 : }
    4669              : void
    4670            0 : pari_fprintf(FILE *file, const char *fmt, ...)
    4671              : {
    4672            0 :   va_list ap; va_start(ap, fmt);
    4673            0 :   pari_vfprintf(file, fmt, ap); va_end(ap);
    4674            0 : }
    4675              : 
    4676              : void
    4677       115438 : print   (GEN g) { printfl_0(g, f_RAW); pari_flush(); }
    4678              : void
    4679            7 : printp  (GEN g) { printfl_0(g, f_PRETTYMAT); pari_flush(); }
    4680              : void
    4681           42 : printtex(GEN g) { printfl_0(g, f_TEX); pari_flush(); }
    4682              : void
    4683        20468 : print1  (GEN g) { printfl_1(g, f_RAW); pari_flush(); }
    4684              : 
    4685              : void
    4686           14 : error0(GEN g)
    4687              : {
    4688           14 :   if (lg(g)==2 && typ(gel(g,1))==t_ERROR) pari_err(0, gel(g,1));
    4689           14 :   else pari_err(e_USER, g);
    4690            0 : }
    4691              : 
    4692              : void
    4693            7 : warning0(GEN g) { pari_warn(warnuser, g); }
    4694              : 
    4695              : static void
    4696          122 : wr_check(const char *t) {
    4697          122 :   if (GP_DATA->secure)
    4698              :   {
    4699            0 :     char *msg = pari_sprintf("[secure mode]: about to write to '%s'",t);
    4700            0 :     pari_ask_confirm(msg);
    4701            0 :     pari_free(msg);
    4702              :   }
    4703          122 : }
    4704              : 
    4705              : /* write to file s */
    4706              : static void
    4707           94 : wr(const char *s, GEN g, long flag, int addnl)
    4708              : {
    4709           94 :   char *t = path_expand(s);
    4710              :   FILE *out;
    4711              : 
    4712           94 :   wr_check(t);
    4713           94 :   out = switchout_get_FILE(t);
    4714           94 :   print0_file(out, g, flag);
    4715           94 :   if (addnl) fputc('\n', out);
    4716           94 :   fflush(out);
    4717           94 :   if (fclose(out)) pari_warn(warnfile, "close", t);
    4718           94 :   pari_free(t);
    4719           94 : }
    4720              : void
    4721           82 : write0  (const char *s, GEN g) { wr(s, g, f_RAW, 1); }
    4722              : void
    4723            4 : writetex(const char *s, GEN g) { wr(s, g, f_TEX, 1); }
    4724              : void
    4725            8 : write1  (const char *s, GEN g) { wr(s, g, f_RAW, 0); }
    4726              : void
    4727           12 : gpwritebin(const char *s, GEN x)
    4728              : {
    4729           12 :   char *t = path_expand(s);
    4730           12 :   wr_check(t); writebin(t, x); pari_free(t);
    4731           12 : }
    4732              : 
    4733              : /*******************************************************************/
    4734              : /**                                                               **/
    4735              : /**                       HISTORY HANDLING                        **/
    4736              : /**                                                               **/
    4737              : /*******************************************************************/
    4738              : /* history management function:
    4739              :  *   p > 0, called from %p or %#p
    4740              :  *   p <= 0, called from %` or %#` (|p| backquotes, possibly 0) */
    4741              : static gp_hist_cell *
    4742        61041 : history(long p)
    4743              : {
    4744        61041 :   gp_hist *H = GP_DATA->hist;
    4745        61041 :   ulong t = H->total, s = H->size;
    4746              :   gp_hist_cell *c;
    4747              : 
    4748        61041 :   if (!t) pari_err(e_MISC,"The result history is empty");
    4749              : 
    4750        61041 :   if (p <= 0) p += t; /* count |p| entries starting from last */
    4751        61041 :   if (p <= 0 || p <= (long)(t - s) || (ulong)p > t)
    4752              :   {
    4753           14 :     long pmin = (long)(t - s) + 1;
    4754           14 :     if (pmin <= 0) pmin = 1;
    4755           14 :     pari_err(e_MISC,"History result %%%ld not available [%%%ld-%%%lu]",
    4756              :              p,pmin,t);
    4757              :   }
    4758        61027 :   c = H->v + ((p-1) % s);
    4759        61027 :   if (!c->z)
    4760            7 :     pari_err(e_MISC,"History result %%%ld has been deleted (histsize changed)", p);
    4761        61020 :   return c;
    4762              : }
    4763              : GEN
    4764        60999 : pari_get_hist(long p) { return history(p)->z; }
    4765              : long
    4766            0 : pari_get_histtime(long p) { return history(p)->t; }
    4767              : long
    4768            0 : pari_get_histrtime(long p) { return history(p)->r; }
    4769              : GEN
    4770           21 : pari_histtime(long p) { return mkvec2s(history(p)->t, history(p)->r); }
    4771              : 
    4772              : void
    4773       108589 : pari_add_hist(GEN x, long time, long rtime)
    4774              : {
    4775       108589 :   gp_hist *H = GP_DATA->hist;
    4776       108589 :   ulong i = H->total % H->size;
    4777       108589 :   H->total++;
    4778       108589 :   guncloneNULL(H->v[i].z);
    4779       108589 :   H->v[i].t = time;
    4780       108589 :   H->v[i].r = rtime;
    4781       108589 :   H->v[i].z = gclone(x);
    4782       108589 : }
    4783              : 
    4784              : ulong
    4785            0 : pari_nb_hist(void)
    4786              : {
    4787            0 :   return GP_DATA->hist->total;
    4788              : }
    4789              : 
    4790              : /*******************************************************************/
    4791              : /**                                                               **/
    4792              : /**                       TEMPORARY FILES                         **/
    4793              : /**                                                               **/
    4794              : /*******************************************************************/
    4795              : 
    4796              : #ifndef R_OK
    4797              : #  define R_OK 4
    4798              : #  define W_OK 2
    4799              : #  define X_OK 1
    4800              : #  define F_OK 0
    4801              : #endif
    4802              : 
    4803              : #ifdef __EMX__
    4804              : #include <io.h>
    4805              : static int
    4806              : unix_shell(void)
    4807              : {
    4808              :   char *base, *sh = getenv("EMXSHELL");
    4809              :   if (!sh) {
    4810              :     sh = getenv("COMSPEC");
    4811              :     if (!sh) return 0;
    4812              :   }
    4813              :   base = _getname(sh);
    4814              :   return (stricmp (base, "cmd.exe") && stricmp (base, "4os2.exe")
    4815              :        && stricmp (base, "command.com") && stricmp (base, "4dos.com"));
    4816              : }
    4817              : #endif
    4818              : 
    4819              : /* check if s has rwx permissions for us */
    4820              : static int
    4821            0 : pari_is_rwx(const char *s)
    4822              : {
    4823              : /* FIXME: HAS_ACCESS */
    4824              : #if defined(UNIX) || defined (__EMX__)
    4825            0 :   return access(s, R_OK | W_OK | X_OK) == 0;
    4826              : #else
    4827              :   (void) s; return 1;
    4828              : #endif
    4829              : }
    4830              : 
    4831              : #if defined(UNIX) || defined (__EMX__)
    4832              : #include <sys/types.h>
    4833              : #include <sys/stat.h>
    4834              : static int
    4835            0 : pari_file_exists(const char *s)
    4836              : {
    4837            0 :   int id = open(s, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
    4838            0 :   return id < 0 || close(id);
    4839              : }
    4840              : static int
    4841            0 : pari_dir_exists(const char *s) { return mkdir(s, 0777); }
    4842              : #elif defined(_WIN32)
    4843              : static int
    4844              : pari_file_exists(const char *s) { return GetFileAttributesA(s) != ~0UL; }
    4845              : static int
    4846              : pari_dir_exists(const char *s) { return mkdir(s); }
    4847              : #else
    4848              : static int
    4849              : pari_file_exists(const char *s) { return 0; }
    4850              : static int
    4851              : pari_dir_exists(const char *s) { return 0; }
    4852              : #endif
    4853              : 
    4854              : static char *
    4855            0 : env_ok(const char *s)
    4856              : {
    4857            0 :   char *t = os_getenv(s);
    4858            0 :   if (t && !pari_is_rwx(t))
    4859              :   {
    4860            0 :     pari_warn(warner,"%s is set (%s), but is not writable", s,t);
    4861            0 :     t = NULL;
    4862              :   }
    4863            0 :   if (t && !pari_is_dir(t))
    4864              :   {
    4865            0 :     pari_warn(warner,"%s is set (%s), but is not a directory", s,t);
    4866            0 :     t = NULL;
    4867              :   }
    4868            0 :   return t;
    4869              : }
    4870              : 
    4871              : static const char*
    4872            0 : pari_tmp_dir(void)
    4873              : {
    4874              :   char *s;
    4875            0 :   s = env_ok("GPTMPDIR"); if (s) return s;
    4876            0 :   s = env_ok("TMPDIR"); if (s) return s;
    4877              : #if defined(_WIN32) || defined(__EMX__)
    4878              :   s = env_ok("TMP"); if (s) return s;
    4879              :   s = env_ok("TEMP"); if (s) return s;
    4880              : #endif
    4881              : #if defined(UNIX) || defined(__EMX__)
    4882            0 :   if (pari_is_rwx("/tmp")) return "/tmp";
    4883            0 :   if (pari_is_rwx("/var/tmp")) return "/var/tmp";
    4884              : #endif
    4885            0 :   return ".";
    4886              : }
    4887              : 
    4888              : /* loop through 26^2 variants [suffix 'aa' to 'zz'] */
    4889              : static int
    4890            0 : get_file(char *buf, int test(const char *), const char *suf)
    4891              : {
    4892            0 :   char c, d, *end = buf + strlen(buf) - 1;
    4893            0 :   if (suf) end -= strlen(suf);
    4894            0 :   for (d = 'a'; d <= 'z'; d++)
    4895              :   {
    4896            0 :     end[-1] = d;
    4897            0 :     for (c = 'a'; c <= 'z'; c++)
    4898              :     {
    4899            0 :       *end = c;
    4900            0 :       if (! test(buf)) return 1;
    4901            0 :       if (DEBUGLEVEL) err_printf("I/O: file %s exists!\n", buf);
    4902              :     }
    4903              :   }
    4904            0 :   return 0;
    4905              : }
    4906              : 
    4907              : #if defined(__EMX__) || defined(_WIN32)
    4908              : static void
    4909              : swap_slash(char *s)
    4910              : {
    4911              : #ifdef __EMX__
    4912              :   if (!unix_shell())
    4913              : #endif
    4914              :   {
    4915              :     char *t;
    4916              :     for (t=s; *t; t++)
    4917              :       if (*t == '/') *t = '\\';
    4918              :   }
    4919              : }
    4920              : #endif
    4921              : 
    4922              : /* s truncated to 8 chars, suf possibly NULL */
    4923              : static char *
    4924            0 : init_unique(const char *s, const char *suf)
    4925              : {
    4926            0 :   const char *pre = pari_tmp_dir();
    4927              :   char *buf, salt[64];
    4928              :   size_t lpre, lsalt, lsuf;
    4929              : #ifdef UNIX
    4930            0 :   sprintf(salt,"-%ld-%ld", (long)getuid(), (long)getpid());
    4931              : #else
    4932              :   sprintf(salt,"-%ld", (long)time(NULL));
    4933              : #endif
    4934            0 :   lsuf = suf? strlen(suf): 0;
    4935            0 :   lsalt = strlen(salt);
    4936            0 :   lpre = strlen(pre);
    4937              :   /* room for prefix + '/' + s + salt + suf + '\0' */
    4938            0 :   buf = (char*) pari_malloc(lpre + 1 + 8 + lsalt + lsuf + 1);
    4939            0 :   strcpy(buf, pre);
    4940            0 :   if (buf[lpre-1] != '/') { (void)strcat(buf, "/"); lpre++; }
    4941              : #if defined(__EMX__) || defined(_WIN32)
    4942              :   swap_slash(buf);
    4943              : #endif
    4944            0 :   sprintf(buf + lpre, "%.8s%s", s, salt);
    4945            0 :   if (lsuf) strcat(buf, suf);
    4946            0 :   if (DEBUGLEVEL) err_printf("I/O: prefix for unique file/dir = %s\n", buf);
    4947            0 :   return buf;
    4948              : }
    4949              : 
    4950              : /* Return a "unique filename" built from the string s, possibly the user id
    4951              :  * and the process pid (on Unix systems). A "temporary" directory name is
    4952              :  * prepended. The name returned is pari_malloc'ed. It is DOS-safe
    4953              :  * (s truncated to 8 chars) */
    4954              : char*
    4955            0 : pari_unique_filename_suffix(const char *s, const char *suf)
    4956              : {
    4957            0 :   char *buf = init_unique(s, suf);
    4958            0 :   if (pari_file_exists(buf) && !get_file(buf, pari_file_exists, suf))
    4959            0 :     pari_err(e_MISC,"couldn't find a suitable name for a tempfile (%s)",s);
    4960            0 :   return buf;
    4961              : }
    4962              : char*
    4963            0 : pari_unique_filename(const char *s)
    4964            0 : { return pari_unique_filename_suffix(s, NULL); }
    4965              : 
    4966              : /* Create a "unique directory" and return its name built from the string
    4967              :  * s, the user id and process pid (on Unix systems). A "temporary"
    4968              :  * directory name is prepended. The name returned is pari_malloc'ed.
    4969              :  * It is DOS-safe (truncated to 8 chars) */
    4970              : char*
    4971            0 : pari_unique_dir(const char *s)
    4972              : {
    4973            0 :   char *buf = init_unique(s, NULL);
    4974            0 :   if (pari_dir_exists(buf) && !get_file(buf, pari_dir_exists, NULL))
    4975            0 :     pari_err(e_MISC,"couldn't find a suitable name for a tempdir (%s)",s);
    4976            0 :   return buf;
    4977              : }
    4978              : 
    4979              : static long
    4980           56 : get_free_gp_file(void)
    4981              : {
    4982           56 :   long i, l = s_gp_file.n;
    4983           56 :   for (i=0; i<l; i++)
    4984            0 :     if (!gp_file[i].fp)
    4985            0 :       return i;
    4986           56 :   return pari_stack_new(&s_gp_file);
    4987              : }
    4988              : 
    4989              : static void
    4990          320 : check_gp_file(const char *s, long n)
    4991              : {
    4992          320 :   if (n < 0 || n >= s_gp_file.n || !gp_file[n].fp)
    4993           20 :     pari_err_FILEDESC(s, n);
    4994          300 : }
    4995              : 
    4996              : static long
    4997           56 : new_gp_file(const char *s, FILE *f, int t)
    4998              : {
    4999              :   long n;
    5000           56 :   n = get_free_gp_file();
    5001           56 :   gp_file[n].name = pari_strdup(s);
    5002           56 :   gp_file[n].fp = f;
    5003           56 :   gp_file[n].type = t;
    5004           56 :   gp_file[n].serial = gp_file_serial++;
    5005           56 :   if (DEBUGLEVEL) err_printf("fileopen:%ld (%ld)\n", n, gp_file[n].serial);
    5006           56 :   return n;
    5007              : }
    5008              : 
    5009              : #if defined(ZCAT) && defined(HAVE_PIPES)
    5010              : static long
    5011           36 : check_compress(const char *name)
    5012              : {
    5013           36 :   long l = strlen(name);
    5014           36 :   const char *end = name + l-1;
    5015           36 :   if (l > 2 && (!strncmp(end-1,".Z",2)
    5016              : #ifdef GNUZCAT
    5017           36 :              || !strncmp(end-2,".gz",3)
    5018              : #endif
    5019              :   ))
    5020              :   { /* compressed file (compress or gzip) */
    5021            0 :     char *cmd = stack_malloc(strlen(ZCAT) + l + 4);
    5022            0 :     sprintf(cmd,"%s \"%s\"",ZCAT,name);
    5023            0 :     return gp_fileextern(cmd,"r");
    5024              :   }
    5025           36 :   return -1;
    5026              : }
    5027              : #endif
    5028              : 
    5029              : long
    5030           52 : gp_fileopen(const char *s, const char *mode)
    5031              : {
    5032              :   FILE *f;
    5033           52 :   if (mode[0]==0 || mode[1]!=0)
    5034            0 :     pari_err_TYPE("fileopen",strtoGENstr(mode));
    5035           52 :   switch (mode[0])
    5036              :   {
    5037           36 :   case 'r':
    5038              : #if defined(ZCAT) && defined(HAVE_PIPES)
    5039              :     {
    5040           36 :       long n = check_compress(s);
    5041           36 :       if (n >= 0) return n;
    5042              :     }
    5043              : #endif
    5044           36 :     f = fopen(s, "r");
    5045           36 :     if (!f) pari_err_FILE("requested file", s);
    5046           36 :     return new_gp_file(s, f, mf_IN);
    5047           16 :   case 'w':
    5048              :   case 'a':
    5049           16 :     wr_check(s);
    5050           16 :     f = fopen(s, mode[0]=='w' ? "w": "a");
    5051           16 :     if (!f) pari_err_FILE("requested file", s);
    5052           16 :     return new_gp_file(s, f, mf_OUT);
    5053            0 :   default:
    5054            0 :     pari_err_TYPE("fileopen",strtoGENstr(mode));
    5055              :     return -1; /* LCOV_EXCL_LINE */
    5056              :   }
    5057              : }
    5058              : 
    5059              : long
    5060            4 : gp_fileextern(const char *s, const char *mode)
    5061              : {
    5062              :   FILE *f;
    5063            4 :   if (mode[0]==0 || mode[1]!=0)
    5064            0 :     pari_err_TYPE("fileopen",strtoGENstr(mode));
    5065            4 :   check_secure(s);
    5066            4 :   switch (mode[0])
    5067              :   {
    5068            4 :   case 'r':
    5069              : #ifndef HAVE_PIPES
    5070              :   pari_err(e_ARCH,"pipes");
    5071              :   return NULL;/*LCOV_EXCL_LINE*/
    5072              : #else
    5073            4 :     f = popen(s, "r");
    5074              : #endif
    5075            4 :     if (!f) pari_err(e_MISC,"[pipe:] '%s' failed",s);
    5076            4 :     return new_gp_file(s, f, mf_PIPE|mf_IN);
    5077            0 :   case 'w':
    5078              : #ifndef HAVE_PIPES
    5079              :   pari_err(e_ARCH,"pipes");
    5080              :   return NULL;/*LCOV_EXCL_LINE*/
    5081              : #else
    5082            0 :     f = popen(s, "w");
    5083              : #endif
    5084            0 :     if (!f) pari_err(e_MISC,"[pipe:] '%s' failed",s);
    5085            0 :     return new_gp_file(s, f, mf_PIPE|mf_OUT);
    5086            0 :   default:
    5087            0 :     pari_err_TYPE("fileextern",strtoGENstr(mode));
    5088              :     return -1; /* LCOV_EXCL_LINE */
    5089              :   }
    5090              : }
    5091              : 
    5092              : void
    5093           56 : gp_fileclose(long n)
    5094              : {
    5095           56 :   check_gp_file("fileclose", n);
    5096           56 :   if (DEBUGLEVEL) err_printf("fileclose(%ld)\n",n);
    5097           56 :   if (gp_file[n].type&mf_PIPE)
    5098            4 :     pclose(gp_file[n].fp);
    5099              :   else
    5100           52 :     fclose(gp_file[n].fp);
    5101           56 :   pari_free((void*)gp_file[n].name);
    5102           56 :   gp_file[n].name = NULL;
    5103           56 :   gp_file[n].fp = NULL;
    5104           56 :   gp_file[n].type = mf_FALSE;
    5105           56 :   gp_file[n].serial = -1;
    5106          112 :   while (s_gp_file.n > 0 && !gp_file[s_gp_file.n-1].fp)
    5107           56 :     s_gp_file.n--;
    5108           56 : }
    5109              : 
    5110              : void
    5111           44 : gp_fileflush(long n)
    5112              : {
    5113           44 :   check_gp_file("fileflush", n);
    5114           40 :   if (DEBUGLEVEL) err_printf("fileflush(%ld)\n",n);
    5115           40 :   if (gp_file[n].type == mf_OUT) (void)fflush(gp_file[n].fp);
    5116           40 : }
    5117              : void
    5118           52 : gp_fileflush0(GEN gn)
    5119              : {
    5120              :   long i;
    5121           52 :   if (gn)
    5122              :   {
    5123           48 :     if (typ(gn) != t_INT) pari_err_TYPE("fileflush",gn);
    5124           44 :     gp_fileflush(itos(gn));
    5125              :   }
    5126            8 :   else for (i = 0; i < s_gp_file.n; i++)
    5127            4 :     if (gp_file[i].fp && gp_file[i].type == mf_OUT) gp_fileflush(i);
    5128           44 : }
    5129              : 
    5130              : GEN
    5131           64 : gp_fileread(long n)
    5132              : {
    5133              :   Buffer *b;
    5134              :   FILE *fp;
    5135              :   GEN z;
    5136           64 :   check_gp_file("fileread", n);
    5137           60 :   if ((gp_file[n].type&mf_IN)==0)
    5138            4 :     pari_err_FILEDESC("fileread",n);
    5139           56 :   fp = gp_file[n].fp;
    5140           56 :   b = new_buffer();
    5141              :   while(1)
    5142              :   {
    5143           56 :     if (!gp_read_stream_buf(fp, b)) { delete_buffer(b); return gen_0; }
    5144           48 :     if (*(b->buf)) break;
    5145              :   }
    5146           48 :   z = strtoGENstr(b->buf);
    5147           48 :   delete_buffer(b);
    5148           48 :   return z;
    5149              : }
    5150              : 
    5151              : void
    5152           48 : gp_filewrite(long n, const char *s)
    5153              : {
    5154              :   FILE *fp;
    5155           48 :   check_gp_file("filewrite", n);
    5156           44 :   if ((gp_file[n].type&mf_OUT)==0)
    5157            4 :     pari_err_FILEDESC("filewrite",n);
    5158           40 :   fp = gp_file[n].fp;
    5159           40 :   fputs(s, fp);
    5160           40 :   fputc('\n',fp);
    5161           40 : }
    5162              : 
    5163              : void
    5164           52 : gp_filewrite1(long n, const char *s)
    5165              : {
    5166              :   FILE *fp;
    5167           52 :   check_gp_file("filewrite1", n);
    5168           48 :   if ((gp_file[n].type&mf_OUT)==0)
    5169            4 :     pari_err_FILEDESC("filewrite1",n);
    5170           44 :   fp = gp_file[n].fp;
    5171           44 :   fputs(s, fp);
    5172           44 : }
    5173              : 
    5174              : GEN
    5175           56 : gp_filereadstr(long n)
    5176              : {
    5177              :   Buffer *b;
    5178              :   char *s, *e;
    5179              :   GEN z;
    5180              :   int t;
    5181              :   input_method IM;
    5182           56 :   check_gp_file("filereadstr", n);
    5183           52 :   t = gp_file[n].type;
    5184           52 :   if ((t&mf_IN)==0)
    5185            4 :     pari_err_FILEDESC("fileread",n);
    5186           48 :   b = new_buffer();
    5187           48 :   IM.myfgets = (fgets_t)&fgets;
    5188           48 :   IM.file = (void*) gp_file[n].fp;
    5189           48 :   s = b->buf;
    5190           48 :   if (!file_getline(b, &s, &IM)) { delete_buffer(b); return gen_0; }
    5191           44 :   e = s + strlen(s)-1;
    5192           44 :   if (*e == '\n') *e = 0;
    5193           44 :   z = strtoGENstr(s);
    5194           44 :   delete_buffer(b);
    5195           44 :   return z;
    5196              : }
    5197              : 
    5198              : /*******************************************************************/
    5199              : /**                                                               **/
    5200              : /**                             INSTALL                           **/
    5201              : /**                                                               **/
    5202              : /*******************************************************************/
    5203              : 
    5204              : #ifdef HAS_DLOPEN
    5205              : #include <dlfcn.h>
    5206              : 
    5207              : /* see try_name() */
    5208              : static void *
    5209            0 : try_dlopen(const char *s, int flag)
    5210            0 : { void *h = dlopen(s, flag); pari_free((void*)s); return h; }
    5211              : 
    5212              : /* like dlopen, but using default(sopath) */
    5213              : static void *
    5214            4 : gp_dlopen(const char *name, int flag)
    5215              : {
    5216              :   void *handle;
    5217              :   char *s;
    5218              : 
    5219            4 :   if (!name) return dlopen(NULL, flag);
    5220            0 :   s = path_expand(name);
    5221              : 
    5222              :   /* if sopath empty or path is absolute, use dlopen */
    5223            0 :   if (!GP_DATA || *(GP_DATA->sopath->PATH)==0 || path_is_absolute(s))
    5224            0 :     return try_dlopen(s, flag);
    5225              :   else
    5226              :   {
    5227              :     forpath_t T;
    5228              :     char *t;
    5229            0 :     forpath_init(&T, GP_DATA->sopath, s);
    5230            0 :     while ( (t = forpath_next(&T)) )
    5231              :     {
    5232            0 :       if ( (handle = try_dlopen(t,flag)) ) { pari_free(s); return handle; }
    5233            0 :       (void)dlerror(); /* clear error message */
    5234              :     }
    5235            0 :     pari_free(s);
    5236              :   }
    5237            0 :   return NULL;
    5238              : }
    5239              : 
    5240              : static void *
    5241            4 : install0(const char *name, const char *lib)
    5242              : {
    5243              :   void *handle;
    5244              : 
    5245              : #ifndef RTLD_GLOBAL /* OSF1 has dlopen but not RTLD_GLOBAL*/
    5246              : #  define RTLD_GLOBAL 0
    5247              : #endif
    5248            4 :   handle = gp_dlopen(lib, RTLD_LAZY|RTLD_GLOBAL);
    5249              : 
    5250            4 :   if (!handle)
    5251              :   {
    5252            0 :     const char *s = dlerror(); if (s) err_printf("%s\n\n",s);
    5253            0 :     if (lib) pari_err(e_MISC,"couldn't open dynamic library '%s'",lib);
    5254            0 :     pari_err(e_MISC,"couldn't open dynamic symbol table of process");
    5255              :   }
    5256            4 :   return dlsym(handle, name);
    5257              : }
    5258              : #else
    5259              : #  ifdef _WIN32
    5260              : static HMODULE
    5261              : try_LoadLibrary(const char *s)
    5262              : { void *h = LoadLibrary(s); pari_free((void*)s); return h; }
    5263              : 
    5264              : /* like LoadLibrary, but using default(sopath) */
    5265              : static HMODULE
    5266              : gp_LoadLibrary(const char *name)
    5267              : {
    5268              :   HMODULE handle;
    5269              :   char *s = path_expand(name);
    5270              : 
    5271              :   /* if sopath empty or path is absolute, use LoadLibrary */
    5272              :   if (!GP_DATA || *(GP_DATA->sopath->PATH)==0 || path_is_absolute(s))
    5273              :     return try_LoadLibrary(s);
    5274              :   else
    5275              :   {
    5276              :     forpath_t T;
    5277              :     char *t;
    5278              :     forpath_init(&T, GP_DATA->sopath, s);
    5279              :     while ( (t = forpath_next(&T)) )
    5280              :       if ( (handle = try_LoadLibrary(t)) ) { pari_free(s); return handle; }
    5281              :     pari_free(s);
    5282              :   }
    5283              :   return NULL;
    5284              : }
    5285              : static void *
    5286              : install0(const char *name, const char *lib)
    5287              : {
    5288              :   HMODULE handle;
    5289              :   if (lib == pari_library_path)
    5290              :   {
    5291              :     handle = GetModuleHandleA(NULL);
    5292              :     void * fun = (void *) GetProcAddress(handle,name);
    5293              :     if (fun) return fun;
    5294              :   }
    5295              :   handle = gp_LoadLibrary(lib);
    5296              :   if (!handle)
    5297              :   {
    5298              :     if (lib) pari_err(e_MISC,"couldn't open dynamic library '%s'",lib);
    5299              :     pari_err(e_MISC,"couldn't open dynamic symbol table of process");
    5300              :   }
    5301              :   return (void *) GetProcAddress(handle,name);
    5302              : }
    5303              : #  else
    5304              : static void *
    5305              : install0(const char *name, const char *lib)
    5306              : { pari_err(e_ARCH,"install"); return NULL; }
    5307              : #endif
    5308              : #endif
    5309              : 
    5310              : static char *
    5311            4 : dft_help(const char *gp, const char *s, const char *code)
    5312            4 : { return stack_sprintf("%s: installed function\nlibrary name: %s\nprototype: %s", gp, s, code); }
    5313              : 
    5314              : void
    5315            4 : gpinstall(const char *s, const char *code, const char *gpname, const char *lib)
    5316              : {
    5317            4 :   pari_sp av = avma;
    5318            4 :   const char *gp = *gpname? gpname: s;
    5319              :   int update_help;
    5320              :   void *f;
    5321              :   entree *ep;
    5322            4 :   if (GP_DATA->secure)
    5323              :   {
    5324            0 :     char *msg = pari_sprintf("[secure mode]: about to install '%s'", s);
    5325            0 :     pari_ask_confirm(msg);
    5326            0 :     pari_free(msg);
    5327              :   }
    5328            4 :   f = install0(s, *lib ?lib :pari_library_path);
    5329            4 :   if (!f)
    5330              :   {
    5331            0 :     if (*lib) pari_err(e_MISC,"can't find symbol '%s' in library '%s'",s,lib);
    5332            0 :     pari_err(e_MISC,"can't find symbol '%s' in dynamic symbol table of process",s);
    5333              :   }
    5334            4 :   ep = is_entry(gp);
    5335              :   /* Delete help if 1) help is the default (don't delete user addhelp)
    5336              :    * and 2) default help changes */
    5337            0 :   update_help = (ep && ep->valence == EpINSTALL && ep->help
    5338            0 :       && strcmp(ep->code, code)
    5339            4 :       && !strcmp(ep->help, dft_help(gp,s,ep->code)));
    5340            4 :   ep = install(f,gp,code);
    5341            4 :   if (update_help || !ep->help) addhelp(gp, dft_help(gp,s,code));
    5342            4 :   mt_broadcast(snm_closure(is_entry("install"),
    5343              :                            mkvec4(strtoGENstr(s),strtoGENstr(code),
    5344              :                                   strtoGENstr(gp),strtoGENstr(lib))));
    5345            4 :   set_avma(av);
    5346            4 : }
        

Generated by: LCOV version 2.0-1