\chapter{Programming PARI in Library Mode}

\section{Introduction: initializations, universal objects.}
\label{se:intro4}

To be able to use PARI in \idx{library mode}, you must write a C program and
link it to the PARI library. See the installation guide (given in Appendix A)
on how to create and install the library and include files. A sample Makefile
is also given in Appendix B.

Probably the best way to understand how programming is done is to work
through a complete example. We will write such a program in
\secref{se:prog}. Before doing this, a few explanations are in order.

First, one must explain to the outside world what kind of objects and
routines we are going to use. This is done simply with the statement

{\tt \#include <genpari.h>}

This file {\tt \idx{genpari.h}} exports all the necessary constants,
variables and functions, defines some important macros, and also defines the
fundamental type for all PARI objects: the type {\tt \idx{GEN}}, which is
simply a pointer to {\tt long}.

{\bf Technical note}: we would have liked to define a type {\tt GEN} to
be a pointer on itself. This unfortunately is not possible in C, except by
using structures, but then the names become unwieldy. The result of this is
that when we will use a component of a PARI object, it will be a {\tt long},
hence will need to be typecasted to a {\tt GEN} again if we want to avoid
warnings from the compiler. This will sometimes be quite tedious, but of
course is trivially done. See the discussion on typecasts in the next
section.

After declaring the use of the file {\tt genpari.h}, the first executable
statement of a main program should be to initialize the PARI system, and in
particular the PARI stack which will be both a scratchboard and a repository
for computed objects. This is done with a call to the function
\sidx{pari\string\_init} {\tt void {pari\_init}(long size, long maxprime)}.
The first argument is the number of bytes given to PARI to
work with (it should not reasonably drop under 500000), and the second is the
upper limit on a precomputed prime number table. If you don't want prime
numbers, just put ${\tt maxrprime} = 2$. Be careful because lots a PARI
functions need this table (certainly all the ones of interest to number
theorists). If you end up with the error message ``not enough precomputed
primes'', try to increase this value.

\noindent We have now at our disposal:

$\bullet$ a large PARI {\it \idx{stack}\/} containing nothing. It's a big
connected chunk of memory whose size you chose when invoking {\tt
pari\_init}. All your computations are going to take place here.
When doing large computations, unwanted intermediate results clutter up
memory very fast so some kind of garbage collecting is needed. Most large
systems do garbage collecting when the cluttering gets heavy, and this slows
down the performance. In PARI we have taken a different approach: you must do
your own cleaning up when the intermediate results are not needed anymore.
Special purpose routines have been written to do this, we will see later how
(and when, if at all) you should use them.

$\bullet$ the following {\it universal objects\/} (by definition, objects
which do not belong to the stack): the integers 0, 1 and 2 (respectively
called {\tt \idx{gzero}}, {\tt \idx{gun}}, and  {\tt \idx{gdeux}}), the
fraction $\dfrac{1}{2}$ ({\tt \idx{ghalf}}), the complex number $i$ ({\tt
\idx{gi}}). All of these are of type {\tt GEN}.

\sidx{variables}
  In addition, space is reserved for the polynomials $x_v$ ({\tt
\idx{polx}[v]}), and the polynomials $1_v$ ({\tt \idx{polun}[v]}).
Here, $x_v$ is the name of variable number $v$, where $0\le v\le {\tt
MAXVARN}$ (the exact value of which depends on your machine, at least 16383 in
any case). Both {\tt polun} and {\tt polx} are arrays of {\tt GEN}s, the
index being the polynomial variable number.

However, except for the ones corresponding to variables $0$ and {\tt
MAXVARN}, these polynomials are {\it not\/} created upon initialization. It
is the programmer's responsibility to fill them before use. We'll see how
this is done in \secref{se:vars} ({\it never} through direct assignment).

$\bullet$ a {\it \idx{heap}\/} which is just a linked list of permanent
universal objects. For now, it contains exactly the ones listed above. You
will probably very rarely use the heap yourself; and if so, only as a
collection of individual copies of objects taken from the stack
(called \idx{clone}s in the sequel). Thus you need not bother with its
internal structure, which may eventually change. Some complex PARI functions
may create clones for special garbage collecting purposes, usually
destroying them when returning.

$\bullet$ a table of primes (in fact of {\it differences\/} between
consecutive primes), called {\tt \idx{diffptr}}, of type {\tt \idx{byteptr}}
(pointer to {\tt unsigned char}). Its use is described in appendix D.

$\bullet$ access to all the built-in functions of the PARI library.
These are declared to the outside world when you include {\tt genpari.h}, but
need the above things to function properly. So if you forget the call to
{\tt pari\_init}, you will immediately get a fatal error when running your
program ({\tt SEGV} usually).

\section{Important technical notes.}
\subsec{Typecasts.}\label{se:typecast}

We have seen that, due to the non-recursivity of the PARI types from the
compiler's point of view, many typecasts will be necessary when programming
in PARI. To take an example, a vector $V$ of dimension 2 (two components)
will be represented by a chunk of memory pointed to by the {\tt GEN V}. {\tt
V[0]} contain code information, in particular the type of the object, its
length, etc\dots. {\tt V[1]} and {\tt V[2]} contain pointers to the two
components of {\tt V}. Those coefficients {\tt V[i]} themselves are in chunks
of memory whose complexity depends on their own types, and so on. This is
where typecasting will be necessary: in principle {\tt V[i]} (for
${\tt i}=1,2$) is a {\tt long}, but we will want to use it as a {\tt GEN}.
The following two constructions will be exceedingly frequent ({\tt x} and
{\tt V} are {\tt GEN}s):
%
\bprog
  V[i] = (long) x;
  x = (GEN) V[i];
\eprog
\noindent Note that a typecast is not a valid lvalue (cannot be put on the
left side of an assignment), so {\tt (GEN)V[i] = x} would be incorrect, though
some compilers may accept it.

  Due to this annoyance, the PARI functions and variables that occur most
frequently have analogs which are macros including the typecast. The complete
list can be found in the file {\tt cast.h} (which is included by {\tt
genpari.h} and can be found at the same place). For instance you can
abbreviate:
%
\bprog\settabs\+
-----------------&--------&\cr
\+
(long) gzero  & -----> &\idx{zero}
\cr\+
(long) gun    & -----> &\idx{un}
\cr\+
(long) polx[v]& -----> &\idx{lpolx}[v]
\cr\+
(long) gadd(x,y)& -----> &\idx{ladd(x,y)}
\cr\eprog

The macro {\tt \idx{coeff}(x,m,n)} exists with exactly the meaning of {\tt
x[m,n]} under GP when {\tt x} is a matrix. This is a purely syntactical trick
to reduce the number of typecasts and thus does not create a copy of the
coefficient (contrary to all the library {\it functions\/}). It can be put on
the left side of an assignment statement, and its value is a {\tt long}
integer. The macro {\tt gcoeff} is a synonym for {\tt (GEN) coeff}, hence
cannot be put on the left side of an assignment. 

To retrieve the values of elements of lists of \dots\ of
lists of vectors, without getting infuriated by gigantic lists of typecasts,
we have the \teb{mael} macros (for {\bf m}ultidimensional {\bf a}rray {\bf
el}ement). The syntax is {\tt mael}$n(x,a_1,\dots,a_n)$, where $x$ is a {\tt
GEN}, the $a_i$ are indexes, and $n$ is an integer between $2$ and $5$ (with
a standalone {\tt mael} as a synonym for {\tt mael}$2$). This stands for
$x[a_1][a_2]\dots[a_n]$ (with all the necessary typecasts), and returns a
{\tt long} (i.e.~they are valid lvalues). The macros {\tt gmael} are synonyms
for {\tt (GEN) mael}. Note that due to the implementation of matrix types in
PARI (i.e.~as horizontal list of vertical vectors), {\tt coeff(x,y)} is
actually completely equivalent to {\tt mael(y,x)}. It is suggested that you
use {\tt coeff} in matrix context, and {\tt mael} otherwise.

\subsec{Portability: 32-bit / 64-bit architectures}

PARI supports both 32-bit and 64-bit based machines, but not simultaneously!
The library was compiled assuming a given architecture (a priori following a
guess by the {\tt Configure} program, see Appendix A), and some of the header
files you include (through {\tt genpari.h}) were modified according to this
setup.

  Portable macros are defined to bypass most machine dependencies. If you
want your programs to run identically on 32-bit and 64-bit machines, you will
have to use them, and not the corresponding numeric values, whenever the
precise size of your {\tt long} integers might matter. Here are the most
important ones:

\bprog\settabs\+
------------------&----------&------------&\cr
\+
                & {\rm 64-bit} & {\rm 32-bit}
\cr\+
BITS\_IN\_LONG  & 64 & 32
\cr\+
LONG\_IS\_64BIT & {\rm defined} & {\rm undefined}
\cr\+
DEFAULTPREC     & 3 & 4 & {\rm ($\approx$ 19 decimal digits, see formula below)}
\cr\+
MEDDEFAULTPREC  & 4 & 6 & {\rm ($\approx$ 38 decimal digits)}
\cr\+
BIGDEFAULTPREC  & 5 & 8 & {\rm ($\approx$ 57 decimal digits)}
\cr
\eprog
\sidx{DEFAULTPREC}
\sidx{MEDDEFAULTPREC}
\sidx{BIGDEFAULTPREC}
\sidx{LONG\string\_IS\string\_64BIT}
\sidx{BITS\string\_IN\string\_LONG}

   For instance, suppose you call a transcendental function (such as {\tt GEN
gexp(GEN x, long prec)}). The last argument {\tt prec} is only used if {\tt
x} is an exact object (otherwise the relative precision is determined from
the precision of {\tt x}). But in this case, the same value of {\tt prec}
will yield different results on 32-bit and 64-bit machines, because it gives
the total length in {\tt long} words (including codewords) of the inexact
result. Real numbers have two codewords (see \secref{se:impl}), so the
formula giving bit accuracy is \sidx{bit\string\_accuracy}
$$ {\tt bit\_accuracy(prec)} = ({\tt prec} - 2) * {\tt BITS\_IN\_LONG} $$
(this is actually the definition of a macro). The corresponding accuracy
expressed in decimal digits would be
%
$$ {\tt bit\_accuracy(prec)} * \log(2) / \log(10).$$
%
For example if the value of {\tt prec} is 5, the corresponding accuracy for
32-bit machines is $(5-2)*\log(2^{32})/\log(10)\approx 28$ decimal digits,
while for 64-bit machines it is $(5-2)*\log(2^{64})/\log(10)\approx 57$
decimal digits.

 Thus, you must take care to change the {\tt prec} parameter that you give
according to the bit size, either using the default precisions given by the
various {\tt DEFAULTPREC}s, or by using conditional constructs of the form:
%
\bprog
\#ifndef LONG\_IS\_64BIT
\q prec = 4;
\#else
\q prec = 6;
\#endif
\eprog
\noindent which is in this case equivalent to the statement
{\tt prec = MEDDEFAULTPREC;}

Note that for parity reasons, half the accuracies available on 32-bit
architectures (the odd ones) are unatainable on 64-bit machines.

\section{Creation of PARI objects, assignments, conversions.}
\subsec{Creation of PARI objects.\sidx{creation}}
The basic function which creates a PARI object is the function
{\bf \idx{cgetg}} whose prototype is:

{\tt GEN cgetg(long length, long type)}

Here {\tt length} specifies the number of longwords to be allocated to the
object, and type is the type number of the object, preferably in symbolic
form (see \secref{se:impl} for the list of these). The precise effect of
this function is as follows: it first creates on the PARI {\it stack\/} a
chunk of memory of size {\tt length} longwords, and puts the address of the
chunk as the returned value.  If the stack has been used up, a message to the
effect that ``the PARI stack overflows'' will be printed. Otherwise, it sets
the type and length of the PARI object. In effect, it fills correctly and
completely its first codeword ({\tt z[0]} or {\tt *z}).  Many PARI objects
have also a second codeword (types \typ{INT}, \typ{REAL}, {\tt
t\_PADIC}, \typ{POL}, and \typ{SER}). In case you'd want to produce one
of those from scratch (this should be exceedingly rare), {\bf it is your
responsibility to fill this second codeword\/}, either explicitly (using the
macros described in \secref{se:impl}), or implicitly using an assignment
statement (using {\tt gaffect}).

Note that the argument {\tt length} is forced for a number of types: 3 for
types \typ{INTMOD}, \typ{FRAC}, \typ{FRACN}, \typ{COMPLEX},
\typ{POLMOD}, \typ{RFRAC} and \typ{RFRACN}, 4 for type \typ{QUAD}
and \typ{QFI}, and 5 for type \typ{PADIC} and \typ{QFR}. However for
efficiency's sake no checking is made in the function {\tt cgetg} so
disasters will occur if you give an incorrect length.

\noindent {\bf Notes:}
1)  The main use of this function is to prepare for later assigments
(see \secref{se:assign}). Most of the time you will use {\tt GEN}
objects as they are returned by PARI functions. In this case you don't need
to use {\tt cgetg} to create space to hold them.

2) the creation of leaves, i.e.~integers or reals, being so
common, {\tt GEN \idx{cgeti}(long length)} and {\tt GEN \idx{cgetr}(long
length)} should be used instead of {\tt cgetg(length, t\_INT)} and {\tt
cgetg(length, t\_REAL)} respectively.

3) the macros {\tt \idx{lgetg}}, {\tt \idx{lgeti}} and {\tt \idx{lgetr}} are
predefined as {\tt (long)cgetg}, {\tt (long)cgeti} and {\tt (long)cgetr}
respectively.

\noindent {\bf Examples:} 1) {\tt z = cgeti(DEFAULTPREC)} and {\tt
cgetg(DEFAULTPREC, t\_INT)} create an integer type whose ``precision'' is
{\tt bit\_accuracy(DEFAULTPREC)} = 64. This means {\tt z} can hold rational
integers of absolute value less than $2^{64}$. Note that in both cases, the
second codeword will {\it not\/} be filled. Of course we could use numerical
values, e.g {\tt cgeti(4)}, but this would have different meanings on
different machines as {\tt bit\_accuracy(4)} equals 64 on 32-bit machines,
but 128 on 64-bit machines.

2) The following creates a complex type whose real and imaginary part can
hold real numbers of precision 
$${\tt bit\_accuracy(MEDDEFAULTPREC)} = 96\hbox{ bits:}$$ 
%
\bprog
  z = cgetg(3, t\_COMPLEX);
  z[1] = lgetr(MEDDEFAULTPREC);
  z[2] = lgetr(MEDDEFAULTPREC);
\eprog
%

3) {\tt z = cgetg(4, t\_MAT); for(i=1; i<4; i++) z[i] = lgetg(5, t\_COL);}

\noindent creates a matrix type for $4\times 3$ matrices. If one wishes to
create space for the matrix elements themselves, one has to use a double
loop and fill each column vector.

These last two examples illustrate the fact that since PARI types are
recursive, all the branches of the tree must be created. The function
{\tt cgetg} creates only the ``root'', and other calls to {\tt cgetg} must be
made to get the whole tree.  For matrices, a common mistake is to think that
{\tt z = cgetg(4, t\_MAT)} (for example) will create the root of the matrix:
one needs also to create the column vectors of the matrix (obviously since we
specified only one dimension in the first {\tt cgetg}!). This is because a
matrix is really nothing else than a line vector of column vectors (hence a
priori not a basic type), but it has been given a special type number so that
operations with matrices become possible.

\subsec{Assignment:} First if {\tt x} and {\tt y} are both declared as {\tt
GEN} (i.e.~pointers to something), the ordinary C assignment {\tt y = x}
makes perfect sense: we are just moving a pointer around. However, physically
modifying either {\tt x} or {\tt y} (for instance, {\tt x[1] = 0}),
will also change the other one, which is usually not desirable.
\label{se:assign}

The general PARI \idx{assignment} function is the function {\bf
\idx{gaffect}} with the following syntax:

{\tt void gaffect(GEN x, GEN y)}

Its effect is to assign the PARI object {\tt x} into the {\it preexisting\/}
object {\tt y}. This copies the whole structure of {\tt x} into {\tt y} so
many conditions must be met for the assignment to be possible. For instance
it is allowed to assign an integer into a real number, but the converse is
forbidden.  For that, you must use the truncation or rounding function of
your choice (see section 3.2). It can also happen that {\tt y} is not large
enough or does not have the proper tree structure to receive the object {\tt
x}. As an extreme example, assume {\tt y} is the zero integer with length
equal to 2. Then all assignments of a non-zero integer into {\tt y} will
result in an error message since {\tt y} is not large enough to fit a non-zero
integer.  In general common sense will tell you what is possible, keeping in
mind the PARI philosophy which says that if it makes sense it is legal.
For instance, the assignment of an imprecise object into a precise one does
{\it not\/} make sense. However, a change in precision of imprecise objects
is allowed.

  All functions ending in ``{\tt z}'' such as {\tt \idx{gaddz}} (see
beginning of chapter 3) implicitly use this function. In fact what they
exactly do is record {\tt avma} (see \secref{se:garbage}), perform the
required operation, {\tt gaffect} the result to the last operand, then
restore the initial {\tt avma}.

You can assign ordinary C long integers into a PARI object (not necessarily
of type \typ{INT}). Use the function {\bf \idx{gaffsg}} with the following
syntax:

{\tt void gaffsg(long s, GEN y)}

\sidx{copy}
\subsec{Copy}: it is also very useful to copy a PARI object, not
just by moving around a pointer as in the {\tt y = x} example, but by
creating a copy of the whole tree structure, without pre-allocating a
possibly complicated {\tt y} to use with {\tt gaffect}. The function which
does this is called {\bf \idx{gcopy}}, with the predefined macro {\tt
\idx{lcopy}} as a synonym for {\tt (long)gcopy}. Its syntax is:

{\tt GEN gcopy(GEN x)}

\noindent and the effect is to create a new copy of x on the PARI stack.
Beware that universal objects which occur in specific components of certain
types (mainly moduli for types \typ{INTMOD} and \typ{PADIC}) are not
copied, as they are assumed to be permanent. In this case, {\tt gcopy} only
copies the pointer. Use {\tt GEN \idx{forcecopy}(GEN x)} if you want a
complete copy.

Please check at this point that you really understand the difference between
{\tt y = x}, {\tt y = gcopy(x)}, and {\tt gaffect(x,y)}: this will spare you
many ``obvious'' mistakes later on.

\sidx{clone}
\subsec{Clones:}
However, it may be more efficient to create a {\it permanent} copy of a PARI
object. This will not be created on the stack but on the heap. The function
which does this is called {\bf \idx{gclone}}, with the predefined macro
{\tt \idx{lclone}} as a synonym for {\tt (long)gclone}. Its syntax is:

{\tt GEN gclone(GEN x)}

\sidx{conversions}
\subsec{Conversions}: the following functions convert C objects to
PARI objects (creating them on the stack as usual):

{\tt GEN \idx{stoi}(long s)}: C {\tt long} integer  (``small'') to PARI
integer (\typ{INT})

{\tt GEN \idx{dbltor}(double s)}: C {\tt double} to PARI real (\typ{REAL}).

Their meaning is clear from their names. The accuracy of the result of {\tt
dbltor} is 19 decimal digits, i.e.~a type \typ{REAL} of length {\tt
DEFAULTPREC}, although on 32-bit machines only 16 of them will be
significant. We also have the converse functions

{\tt long \idx{itos}(GEN x)}: {\tt x} must be of type \typ{INT}.

{\tt double \idx{rtodbl}(GEN x)}: {\tt x} must be of type \typ{REAL}.

\noindent as well as the more general ones:

{\tt long \idx{gtolong}(GEN x)}

{\tt double \idx{gtodouble}(GEN x)}

\sidx{garbage collecting}
\section{Garbage collection.}\label{se:garbage}
\subsec{Why and how.}

As we have seen, the {\tt pari\_init} routine allocates a big range of
addresses (the {\it stack}) that are going to be used throughout. Recall that
all PARI objects are pointers. But for universal objects, they will all point
on some part of the stack.

The stack starts at the address {\tt bot} and goes up to {\tt top}. This
means that the quatity
%
$$ ({\tt top} - {\tt bot})\,/\,{\tt sizeof(long)} $$
%
is equal to the {\tt size} argument of {\tt pari\_init}. The PARI
stack also has a ``current stack pointer'' called {\tt \idx{avma}}, which
stands for {\bf av}ailable {\bf m}emory {\bf a}ddress. These three variables
are global (declared for you by {\tt genpari.h}). For historical reasons they
are of type {\tt long} and not of type {\tt GEN} as would seem more natural.

The stack is oriented updside-down: the more recent an object, the closer to
{\tt bot}. Accordingly, initially {\tt avma} = {\tt top} and it gets {\it
down} as new objects are created. As its name indicates, {\tt avma} always
points just {\it after} the first free address on the stack, and {\tt
(GEN)avma} is always the last object created. When {\tt avma} reaches {\tt
bot}, the stack overflows aborting all computations, and an error message is
output. To avoid this {\it you} will need to clean up the stack from times to
times, when a bunch of intermediate objects will not be needed anymore. This
is called ``{\it garbage collecting}''.

We are now going to describe briefly how this is done. We will see many
concrete examples in the next subsection.

$\bullet$ First, PARI routines will do their own garbage collecting, which
means that anytime a documented function from the library returns, only its
result(s) will be added on the stack (non documented ones may not do this for
speed sake). In particular, the PARI functions that do not return {\tt GEN}s
do not clutter the stack. Thus, if your computation is small enough (i.e.~you
call few PARI routines, or most of them return {\tt long} integers) then you
don't need to do any garbage collecting. This will probably be the case in
many of your subroutines. Of course the objects that were on the stack {\it
before} the function call are left alone. But for the ones listed below,
PARI functions only collect their own garbage.

$\bullet$ It may happen that you don't need anymore {\sl all} objects
that were created after a certain point. For instance if the final result you
need is not a {\tt GEN}, or if some search proved futile. Then¸ it is enough
to record the value of {\tt avma} just {\sl before} the first garbage is
created, and restore it upon exit:

\bprog
long ltop = avma; /* record initial avma */
\h
garbage ...
avma = ltop; /* restore it */
\eprog
\noindent All objects created in the {\tt garbage} zone will eventually 
be overwritten: they should not be accessed anymore once {\tt avma} has been
restored.

$\bullet$ If you want to destroy (i.e.~give back the memory occupied by) the
latest PARI object on the stack (e.g. the latest one obtained from a function
call), and the above method is not available (because the initial value of
{\tt avma} has been lost), just use the function \sidx{destruction}

{\tt void \idx{cgiv}(GEN z)}

\noindent where {\tt z} is the object you want to give back. 

$\bullet$  Unfortunately life is not so simple, and sometimes you will want
to give back accumulated garbage {\it during} a computation without losing
recent data. For this you need the {\bf gerepile} function (or one of its
variants described hereafter):

{\tt GEN \idx{gerepile}(long ltop, long lbot, GEN q)}

This function cleans up the stack between {\tt ltop} and {\tt lbot}, where 
${\tt lbot} < {\tt ltop}$, and return the updated object {\tt q}. This means:

1) we translate (copy) all the objects in the interval
$[{\tt avma}, {\tt lbot}[$, so that its right extremity abutts the address
{\tt ltop}. Graphically

\bprog\settabs\+
{\rm end of stack}  &|-&-----------&|++++++&|-/-/-/-/-/-/-&|++++++++&|
\cr\+
            &bot  &       &avma  &lbot         &ltop    &top
\cr\+
{\rm end of stack}  |------------[++++++[-/-/-/-/-/-/-|++++++++|\q
{\rm beginning of stack}
\cr\+
             & &{\rm free memory}
\cr\eprog\noindent becomes:
%
\bprog\settabs\+
{\rm end of stack}  &|--------&------------------&|++++++&|++++++++&|
\cr\+
             &bot      &                  &avma   &ltop     &top
\cr\+
{\rm end of stack} |--------------------------[++++++[++++++++|\q
{\rm beginning of stack}
\cr\+
                      &&{\rm free memory}
\cr\eprog
%
\noindent where {\tt ++} denote significant objects, {\tt --} the unused part
of the stack, and {\tt -/-} the garbage we remove.

2) The function then considers all the PARI objects between {\tt avma} and
{\tt lbot} (i.e.~the ones that we want to keep and that have been translated)
and looks at every component of such an object which is not a codeword. This
component is a pointer on an object whose address is either 

  --- between {\tt avma} and {\tt lbot}, in which case it will be suitably
updated,

  --- larger than or equal to {\tt ltop}, in which case it will not change, or
  
  --- between {\tt lbot} and {\tt ltop} in which case {\tt gerepile} will
scream an error message at you (``significant pointers lost in gerepile'').

3) {\tt avma} is corrected (we add ${\tt ltop} - {\tt lbot}$ to the old value).

4) We return the (possibly updated) object {\tt q}. Namely if {\tt q} pointed
initially between {\tt avma} and {\tt lbot}, we return the translated
address, as in 2). If not the original address is still valid (and we return
it!).

As stated above, no component of the remaining objects (in particular {\tt
q}) should belong to the erased segment [{\tt lbot}, {\tt ltop}[, and this is
checked within {\tt gerepile}. But beware as well that the address of all the
objects in the translated zone will have changed after a call to
{\tt gerepile}: every pointer previously pointing to a zone under {\tt ltop}
is to be discarded. If you need to recover more than one object, use one of
the {\tt gerepilemany} functions below.

As a consequence of the preceding explanation, we must now state the most
important law about programming in PARI:

{\bf If a given PARI object is to be relocated by {\tt gerepile} then,
apart from universal objects, the chunks of memory used by its components should
be in consecutive memory locations}. All {\tt GEN}s created by documented
PARI function are guaranteed to satisfy this.

Namely the {\tt gerepile} function knows only about two {\it connected} zones:
the garbage that will be erased (between {\tt lbot} and {\tt ltop}) and the 
significant pointers that will be copied and updated. If there is garbage
interspersed with your objects, disasters will occur when we try to update
them and consider the corresponding ``pointers''. So be {\it very} wary when
you allow objects to become disconnected. Have a look at the examples, it's
not as complicated as it seems.

\noindent In practice this is achieved as follows:
\bprog
  ltop=avma; garbage(); lbot=avma; q=anything();
  return gerepile(ltop, lbot, q);  /* returns the updated q */
\eprog

\noindent Beware that
\bprog
  ltop=avma; garbage();
  return gerepile(ltop, avma, anything())
\eprog

\noindent might work, but should be frowned upon: exactly when {\tt avma} is
evaluated is compiler dependant. If it's {\it after} the call to {\tt
anything()}, the result of {\tt anything} belongs to the garbage zone and the
{\tt gerepile} statement becomes equivalent to {\tt avma = ltop}. Thus we
return a pointer to random garbage.

$\bullet$ A simple variant is

{\tt GEN \idx{gerepileupto}(long ltop, GEN q)}

\noindent which cleans the stack between {\tt ltop} and the {\it connected\/}
object {\tt q} and returns {\tt q} updated. For this to work, {\tt q} must
have been created {\it before} all its components, otherwise they would
belong to the garbage zone! Most documented PARI functions guarantee this. If
you stumble on one that does not, consider it as a bug worth reporting.

$\bullet$ To cope with complicated routines where many objects have to be
preserved, you can use

{\tt void \idx{gerepilemany}(long ltop, GEN *gptr[], long n)}

\noindent which cleans up the most recent part of the stack (between {\tt
ltop} and {\tt avma}). All the {\tt GEN}s pointed by the elements of the
array {\tt gptr} (of length {\tt n}) are updated. A copy is done just before
the cleaning to preserve them, so they don't need to be connected before the
call. This is the most robust of the gerepile functions (the less prone to
user error), but also the slowest.

$\bullet$ More efficient, but trickier to use is

{\tt void \idx{gerepilemanysp}(long ltop, long lbot, GEN *gptr[], long n)}

\noindent which cleans the stack between {\tt lbot} and {\tt ltop} and
updates the {\tt GEN}s pointed by the elements of {\tt gptr} without doing any
copy. This is subject to the same restrictions as {\tt gerepile}, the only
difference being that more than one address gets updated.

\subsec{Examples}

Let {\tt x} and {\tt y} be two preexisting PARI objects and suppose that we
want to compute ${\tt x}^2+ {\tt y}^2$. This can trivially be done using the
following program (we skip the necessary declarations, everybody in sight is
a {\tt GEN}):

{\tt p1 = gsqr(x); p2 = gsqr(y); z = gadd(p1,p2);}

The GEN {\tt z} indeed points on the required quantity. However, consider the
stack: it contains as unnecessary garbage {\tt p1} and {\tt p2}. More
precisely it contains (in that order) {\tt z}, {\tt p2}, {\tt p1} (recall
that, the stack being upside-down, this means the most recent comes first).
We need a way to get rid of this garbage (in this case it causes no harm
except that it occupies memory space, but in other cases it could disconnect
PARI objects and this is dangerous). 

It would not have been possible to get rid of {\tt p1}, {\tt p2} before 
{\tt z} is computed, since they are used in the final operation. We cannot
record {\tt avma} before {\tt p1} is computed then restore it later, since
this would destroy {\tt z} as well. It is not possible either to use the
function {\tt cgiv} since {\tt p1} and {\tt p2} are not at the bottom of the
stack and we don't want to give back {\tt z}.

But using {\tt gerepile}, we can give back the memory locations corresponding
to {\tt p1}, {\tt p2}, and move the object {\tt z} upwards so that no
space is lost. Specifically:
\bprog
  ltop = avma; /* keep in mind the current address of the top of the stack */
  p1 = gsqr(x); p2 = gsqr(y);
  lbot = avma; /* keep the address of the bottom of the garbage pile */
  z = gadd(p1, p2); /* z is now the last object on the stack */
  z = gerepile(ltop, lbot, z); /* garbage collecting */
\eprog
\noindent Of course, the last two instructions could also have been
written more simply:

{\tt z = gerepile(ltop, lbot, gadd(p1,p2));}

\noindent In fact {\tt gerepileupto} is even simpler to use, because the result
of {\tt gadd} will be the last object on the stack and {\tt gadd} is
guaranteed to return a suitable object for {\tt gerepileupto}:
\bprog
  ltop = avma; 
  z = gerepileupto(ltop, gadd(gsr(x), gsqr(y)));
\eprog

As you can see, in simple conditions the use of {\tt gerepile} is not really
difficult. However make sure you understand exactly what has happened before
you go on (use the figure from the preceding section).

{\bf Important remark}: as we will see presently it is often necessary to do
several {\tt gerepile} in a computation. However, the fewer the better.  The
only condition for {\tt gerepile} to work is that the garbage be connected.
If the computation can be arranged so that there is a minimal number of
connected pieces of garbage, then it should be done that way.

For example suppose we want to write a function of two {\tt GEN} variables 
{\tt x} and {\tt y} which creates the vector ${\tt [x}^2+{\tt y}, {\tt
y}^2+{\tt x]}$. Without garbage collecting, one would write:
%
\bprog
  p1 = gsqr(x); p2 = gadd(p1, y);
  p3 = gsqr(y); p4 = gadd(p3, x);
  z = cgetg(3,t\_VEC); z[1] = (long)p2; z[2] = (long)p4;
\eprog

This leaves a dirty stack with (in that order) {\tt z}, {\tt p4}, {\tt p3},
{\tt p2}, {\tt p1}. The garbage here is {\tt p1} and {\tt p3} which is
disconnected by {\tt p2}. But if we compute {\tt p3 {\it before\/} p2} then
the garbage becomes connected, and we get the following program with garbage
collecting:
%
\bprog
  ltop = avma; p1 = gsqr(x); p3 = gsqr(y); lbot = avma;
  z = cgetg(3,t\_VEC); z[1] = ladd(p1,y); z[2] = ladd(p3,x);
  z = gerepile(ltop,lbot,z);
\eprog

\noindent Finishing by {\tt z = gerepileupto(ltop, z)} would be ok as well.
But when you have the choice, it's usually clearer to brace the garbage
between {\tt ltop} / {\tt lbot} pairs.

\noindent Beware that
\bprog
  ltop = avma; p1 = gadd(gsqr(x), y); p3 = gadd(gsqr(y), x);
  z = cgetg(3,t\_VEC); z[1] = (long)p1; z[2] = (long)p3
  z = gerepileupto(ltop,z); /* WRONG !!! */
\eprog
\noindent will be a disaster as {\tt p1} and {\tt p3} have been created
before {\tt z}, so the call to {\tt gerepileupto} will overwrite them. Thus
{\tt z[1]} and {\tt z[2]} now points to random data!

We next want to write a program to compute the product of two complex numbers
$x$ and $y$, using a method which takes only 3 multiplications instead of 4.
Let $z = x*y$, and set $x = x_r + i*x_i$ and similarly for $y$ and $z$. The
well known trick is to compute $p_1 = x_r*y_r$, $p_2=x_i*y_i$,
$p_3=(x_r+x_i)*(y_r+y_i)$, and then we have $z_r=p_1-p_2$,
$z_i=p_3-(p_1+p_2)$. The program is essentially as follows:
%
\bprog
ltop = avma; p1 = gmul(x[1],y[1]); p2 = gmul(x[2],y[2]); 
p3 = gmul(gadd(x[1],x[2]), gadd(y[1],y[2]));
p4 = gadd(p1,p2); lbot = avma; 
z = cgetg(3,t\_COMPLEX); z[1] = lsub(p1,p2); z[2] = lsub(p3,p4); 
z = gerepile(ltop,lbot,z); 
\eprog

``Essentially'' because for instance {\tt x[1]} is a long and not a {\tt
GEN}, so we need to insert many annoying typecasts: {\tt p1 = gmul((GEN)x[1],
(GEN)y[1])} and so on.

  Let us now look at a less trivial example where more than one {\tt
gerepile} is needed in practice (at the expense of efficiency, one can always
use only one using {\tt gcopy}, see below). Suppose that we want to write a
function which multiplies a line vector by a matrix (such a function is of
course already part of {\tt gmul}, but let's ignore this for a moment). Then
the most natural way is to do a {\tt cgetg} of the result immediately, and
then for each coefficient of the result vector to do a {\tt gerepile} to get
rid of the garbage which has accumulated for that particular coefficient. We
leave the details to the reader, who can look at the answer in the file {\tt
basemath/gen2.c}, in the function {\tt gmul}, case \typ{VEC} times case {\tt
t\_MAT}. It would theoretically be possible to have a single connected piece
of garbage, but it would be a much less natural and unnecessarily complicated
program.

  Let us now take an example which is probably the least trivial way of using
{\tt gerepile}, but is unfortunately sometimes necessary. Although it is not
an infrequent occurrence, we will not give a specific example but a general
one: suppose that we want to do a computation (usually inside a larger
function) giving more than one PARI object as a result, say two for instance.
Then even if we set up the work properly, before cleaning up we will have a
stack which has the desired results {\tt z1}, {\tt z2} (say), and then
connected garbage from lbot to ltop. If we write

{\tt z1 = gerepile(ltop,lbot,z1);}

then the stack will be cleaned, the pointers OK, but we will have lost the
address of {\tt z2}. This is where we need one of the \idx{gerepilemany}
functions: we declare
\bprog
  GEN *gptr[2]; /* Array of pointers to GENs */
  gptr[0] = \&z1; gptr[1] = \&z2;
\eprog
\noindent then the call {\tt gerepilemany(ltop, gptr, 2)} copies {\tt z1} and
{\tt z2} to new locations, cleans the stack from {\tt ltop} to the old
{\tt avma}, and updates the pointers {\tt z1} and {\tt z2}. Here we don't
assume anything about the stack: the garbage can be disconnected and {\tt
z1}, {\tt z2} need not be at the bottom of the stack. If we can make these
assumptions, then we can call {\tt gerepilemanysp} instead, which will be
faster as we don't need the initial copy.

Another important usage is ``random'' garbage collection during loops
whose size we do not control:
\bprog
\q  GEN x, y;
\q  long ltop = avma, limit = (avma+bot)/2;
\h
\q  while (...)
\q  $\{$
\q\q  garbage(); x = anything();
\q\q  garbage(); y = anything()
\q\q  garbage();
\q\q  if (avma < limit) /* memory is running low (half spent since entry) */
\q\q  $\{$
\q\q\q   GEN *gptr[2];
\q\q\q   gptr[0] = \&x; gptr[1] = \&y;
\q\q\q   gerepilemany(ltop, gptr, 2);
\q\q  $\}$
\q  $\}$
\eprog
\noindent Here we assume that only {\tt x} and {\tt y} are needed from one
iteration to the next. As it would be too costly to call gerepile at each
iteration, we only do it once it has become necessary. Of course, if the need
arises, you can use bigger arrays: in the PARI library source code, we once
needed to preserve up to 10 objects at a time!

\subsec{Some tricks and hints}. Even for the authors, the use of
{\tt gerepile} was not evident at first. Hence we give some indications on
how to avoid most problems connected with {\tt gerepile}.

First, although it looks complicated, {\tt gerepile} has turned out to be a
very flexible and fast garbage collector, which can compare very favorably
with much more sophisticated methods used in other systems. A few tests that
we have made indicate that the price paid for using {\tt gerepile}, when
properly done, is never more than 10 percent, and usually around 5 or 6
percent of the total time, which is quite acceptable.

Second, in many cases, in particular when the tree structure and the size of
the PARI objects which will appear in a computation are under control, one
can avoid {\tt gerepile} altogether by creating sufficiently large objects at
the beginning (using {\tt cgetg}), and then using assignment statements and
operations ending with z (such as {\tt gaddz}). Coming back to our first
example, note that if we know that x and y are of type real and of length
less than or equal to 5, we can program without using {\tt gerepile} at all:

\bprog
  z = cgetr(5); ltop = avma;
  p1 = gsqr(x); p2 = gsqr(y); gaddz(p1,p2,z);
  avma = ltop;
\eprog

Third, the philosophy of {\tt gerepile} is the following: keep the value of
the stack pointer {\tt avma} at the beginning, and just {\it before\/} the
last operation.  Afterwards, it would be too late since the garbage address
would be lost. Of course you can always use {\tt gerepileupto} but you will
have to assume that the object was created {\sl before} its components.

Finally, if everything seems hopeless, at the expense of speed you can do the
following: after keeping in ltop the value of avma, perform your computation
as you wish, in any order, leaving a messy stack. Let {\tt z} be your result.
Then write the following:

{\tt lbot = avma; z = gerepile(ltop,lbot,gcopy(z));}

The trick is to force a copy of {\tt z} at the bottom of the stack, hence all
the rest including the initial {\tt z} becomes connected garbage. If you need
to keep more than one result, use {\tt gerepilemany} (of which the above is
just a special case).

\smallskip If you followed us this far, congratulations, and rejoice, the
rest is much easier.

\section{Implementation of the PARI types.}
\label{se:impl}

Although it is a little tedious, we now go through each type and explain its
implementation. Let {\tt z} be a PARI object. Common to all the types is the
first codeword {\tt z[0]}, which we don't have to worry about since this is
taken care of by {\tt cgetg}. Its precise structure will depend on the
machine you are using, but it always contain the following data: the
{\it internal \idx{type number}\/} associated to the symbolic type name, the
{\it\idx{length}\/} of the root in longwords, and a technical bit which
indicates whether the object is a clone (see below) or not. This last one is
used by GP for internal garbage collecting, you won't have to worry about it.

\noindent These data can be handled through the following macros:

{\tt long \idx{typ}(GEN z)} returns the type number of {\tt z}.

{\tt void \idx{settyp}(GEN z, long n)} sets equal to {\tt n} the type number
of {\tt z} (you should not have to use this function if you use cgetg).

{\tt long \idx{lg}(GEN z)} returns the length (in longwords) of the root
of {\tt z}.

{\tt long \idx{setlg}(GEN z, long l)} sets equal to {\tt l} the length of
{\tt z} (you should not have to use this function if you use {\tt cgetg};
however, see an advanced example in the matexp function given in
\secref{se:prog}).

(If you know enough about PARI to need to access the ``clone'' bit, then you
can find your way in the code (esp. {\tt killbloc()} and
{\tt matrix\_block()}). It {\it is} technical after all.)

These macros are written in such a way that you don't need to worry about
type casts when using them: i.e.~is {\tt z} is a {\tt GEN}, {\tt typ(z[2])}
will be accepted by your compiler, without your having to explicitly type
{\tt typ((GEN)z[2])}. Note that for efficiency's sake, none of the
codeword-handling macros check the types of their arguments even when there
are stringent restrictions to their use.

The possible second codeword is used differently by the different types, we
will describe it as we now consider them in turn:

\def\sectype#1#2{
  \subsecprot{Type \typ{#1} (#2s):}
             {Type {\tt t\string\_#1} (#2s):}
  \sidx{#2}
}
\def\sectypeindex#1#2#3{
  \subsecprot{Type \typ{#1} (#2):}
             {Type {\tt t\string\_#1} (#2):}
  \sidx{#3}
}
\def\sectypes#1#2#3{
  \subsecprot{Types \typ{#1} and \typ{#2} (#3s):}
             {Types {\tt t\string\_#1} and {\tt t\string\_#2} (#3s):}
  \sidx{#3}
}

\sectype{INT}{integer} this type has a second codeword {\tt z[1]} which
contains the following information: 

the sign of {\tt z}: coded as $1$, $0$ or $-1$ if ${\tt z} > 0$, ${\tt z} = 0$,
${\tt z} < 0$ respectively. 

the {\it effective length} of {\tt z}, i.e.~the total number of significant
longwords. This means the following: apart from the integer 0, every integer
is ``normalized'', meaning that the first mantissa longword (i.e.~{\tt z[2]})
is non-zero. However, the integer may have been created with a longer length.
Hence the ``length'' which is in {\tt z[0]} can be larger than the
``effective length'' which is in {\tt z[1]}. Accessing {\tt z[i]}
for {\tt i} larger than or equal to the effective length will yield random
results.

\noindent This information is handled using the following macros:

{\tt long \idx{signe}(GEN z)} returns the sign of {\tt z}.

{\tt void \idx{setsigne}(GEN z, long s)} sets equal to {\tt s} the sign of
{\tt z}.

{\tt long \idx{lgefint}(GEN z)} returns the \idx{effective length} of
{\tt z}.

{\tt void \idx{setlgefint}(GEN z, long l)} sets equal to {\tt l} the
effective length of {\tt z}.

The integer 0 can be characterized either by its sign equal to 0, or by its
effective length equal to 2. Apart from ${\tt z} = 0$, {\tt z[2]} exists and
is non-zero, and the absolute value of {\tt z} is ({\tt z[2]},{\tt
z[3]},\dots,{\tt z[lgefint(z)-1]}) in base {\tt 2\pow BITS\_IN\_LONG},
where as usual in this notation {\tt z[2]} is the high order longword.

\noindent The following macros are also available:

{\tt long mpodd(GEN x)} which is 1 if {\tt x} is odd, and 0 otherwise.

{\tt long mod2(GEN x)}, {\tt mod4(x)}, and so on up to {\tt mod64(x)}, which
give the residue class of {\tt x} modulo the corresponding power of 2, {\bf
for positive {\tt x}} (you will obtain false results if you use these on
the integer 0 or on negative numbers).

These macros directly access the binary data and are thus much faster than
the generic modulo functions. Besides, they return long integers instead of
GENs, so they don't clutter up the stack.

\sectype{REAL}{real number} this type has a second codeword z[1] which
encodes also its sign (obtained or set using the same functions as for the
integers), and a biased binary exponent (i.e.~the exponent plus some power of
2 whose value is given by {\tt HIGHEXPOBIT}). This exponent can be handled
using the following macros:

{\tt long \idx{expo}(GEN z)} returns the true (unbiased) exponent of {\tt z}.
This is defined even when z is equal to zero, see \secref{se:whatzero}.

{\tt void \idx{setexpo}(GEN z, long e)} sets equal to {\tt e} the exponent
of z, of course after adding the bias.

\noindent Note the functions:

{\tt long \idx{gexpo}(GEN z)} which tries to return an exponent for {\tt z}
even if {\tt z} is not a real number.

{\tt long \idx{gsigne}(GEN z)} which returns a signe for {\tt z} even when
{\tt z} is neither real nor integer (a rational number for instance).

The real zero is characterized by having its sign equal to 0. However,
usually the first mantissa word {\tt z[2]} is defined and equal to 0. This
fact must {\it never\/} be used to characterize 0. If {\tt z} is not equal to
0, the first mantissa word {\tt z[2]} is normalized, i.e.~its first bit is 1.
The mantissa is ({\tt z[2]},{\tt z[3]},\dots,{\tt z[lg(z]-1]}) in base
{\tt 2\pow BITS\_IN\_LONG}. Here, {\tt z[2]} is the most significant
longword, and the mantissa is understood to be between 1 (included) and 2
(excluded). Thus the real number $3.5$ is represented (assume that {\tt
sizeof(long)} is 32 and length is 4) as {\tt z[0]} (encoding ${\tt type} =
\typ{REAL}$, ${\tt lg} = 4$), {\tt z[1]} (encoding ${\tt sign} = 1$, ${\tt
expo} = 1$),  ${\tt z[2]} = {\tt 0xe0000000}$, ${\tt z[3]} = {\tt 0x0}$.

\sectype{INTMOD}{integermod} {\tt z[1]} points to the modulus, and {\tt z[2]}
on the number representing the class {\tt z}. Both must be of type integer.
In principle {\tt z[1]} $>$ 0 and 0 $\le$ {\tt z[2]} $<$ {\tt z[1]}, but this
rule does not have to be strictly obeyed by the user. Any integermod obtained
after a PARI operation will satisfy these conditions.

\sectypes{FRAC}{FRACN}{rational number} {\tt z[1]} points to the numerator,
and {\tt z[2]} on the denominator. Both must be of type integer. In principle
${\tt z[2]} > 0$, but this rule does not have to be strictly obeyed. Note
that a type \typ{FRACN} rational number can be converted to irreductible
form using the function {\tt GEN gred(GEN x)}. \sidx{gred}

\sectype{COMPLEX}{complex number} {\tt z[1]} points to the real part, and
{\tt z[2]} on the imaginary part. A priori {\tt z[1]} and {\tt z[2]} can be
of any type, but only certain types are useful and make sense.

\sectype{PADIC}{p-adic number} this type has a second codeword {\tt z[1]}
which contains the following information: the $p$-adic precision (the
exponent of $p$ modulo which the $p$-adic unit corresponding to {\tt z} is
defined if {\tt z} is not 0), i.e.~one less than the number of significant
$p$-adic digits, and the biased exponent of {\tt z} (the bias being here
equal to {\tt HIGHVALPBIT}). This information can be handled using the
following functions:

{\tt long \idx{precp}(GEN z)} returns the $p$-adic precision of {\tt z}.

{\tt void \idx{setprecp}(GEN z, long l)} sets equal to {\tt l} the $p$-adic
precision of {\tt z}.

{\tt long \idx{valp}(GEN z)} returns the $p$-adic valuation of {\tt z} (i.e.
the unbiased exponent). This is defined even if {\tt z} is equal to 0, see
\secref{se:whatzero}.

{\tt void \idx{setvalp}(GEN z, long e)} sets equal to {\tt e} the $p$-adic
valuation of {\tt z}.

In addition to this codeword, {\tt z[2]} points to the prime $p$, {\tt z[3]}
points to $p^{\text{precp(z)}}$, and {\tt z[4]} points to an integer
representing the $p$-adic unit associated to {\tt z} modulo {\tt z[3]} (or
points to zero if {\tt z} is zero). To summarize, we have the equality:
$$ {\tt z} = p^{\text{valp(z)}} * ({\tt z[4]} + O({\tt z[3]})) = 
     p^{\text{valp(z)}} * ({\tt z[4]} + O(p^{\text{precp(z)}})) $$

\sectype{QUAD}{quadratic number} {\tt z[1]} points to the polynomial defining
the quadratic field, {\tt z[2]} on the ``real part'' and {\tt z[3]} on the
``imaginary part'', where this is to be taken as the coefficients of {\tt z}
on the ``canonical'' basis $(1,w)$, see \secref{se:compquad}. Complex
numbers are particular cases of quadratics but deserve a separate type.

\sectype{POLYMOD}{polymod} exactly as for integermods, {\tt z[1]} points to
the modulus, and {\tt z[2]} on a polynomial representing the class of {\tt
z}. Both must be of type polynomial. However, one must obey the rules
explained in Chapter 2 concerning the hierarchical structure of the variables
of a polymod.

\sectype{POL}{polynomial} this type has a second codeword which is analogous
to the one for integers. It contains a ``{\it sign\/}'': 0 if the polynomial
is equal to 0, and 1 if not (see however the important remark below), a {\it
variable number\/} (e.g. 0 for $x$, 1 for $y$, etc\dots), and an {\it
effective length}.

\noindent This data can be handled with the following macros:

{\tt signe} and {\tt setsigne} as for reals and integers.

{\tt long \idx{lgef}(GEN z)} returns the \idx{effective length} of {\tt z}.

{\tt void \idx{setlgef}(GEN z, long l)} sets equal to {\tt l} the effective
length of {\tt z}.

{\tt long \idx{varn}(GEN z)} returns the variable number of the object {\tt z}.

{\tt void \idx{setvarn}(GEN z,long v)} sets equal to {\tt v} the variable
number of {\tt z}.

Note also the function {\tt long \idx{gvar}(GEN z)} which tries to return a
\idx{variable} number for {\tt z}, even if {\tt z} is not a polynomial or power
series. The variable number of a scalar type is set by definition equal to
{\tt BIGINT}.

The components {\tt z[2]}, {\tt z[3]},\dots {\tt z[lgef(z)-1]} point to the
coefficients of the polynomial {\it in ascending order\/}, with {\tt z[2]}
being the constant term and so on. Note that the {\it \idx{degree}\/} of the
polynomial is equal to its effective length minus three. The function

{\tt long degree(GEN x)} returns the degree of {\tt x} with respect to its
main variable even when {\tt x} is not a polynomial (a rational function for
instance). By convention, the degree of $0$ is $-1$.

{\bf Important remark}. A zero polynomial can be characterized by the fact
that its sign is 0. However, its effective length may be equal to 2, or
greater than 2. If it is greater than 2, this means that all the coefficients
of the polynomial are equal to zero (as they should for a zero polynomial),
but not all of these zeros are exact zeros, and more precisely the leading
term {\tt z[lgef(z)-1]} is not an exact zero.

\sectypeindex{SER}{power series}{power series} This type also has a second
codeword, which encodes a ``{\it sign\/}'', i.e.~0 if the power series is 0,
and 1 if not, a {\it variable number\/} as for polynomials, and a {\it biased
exponent} with a bias of {\tt HIGHVALPBIT}. This information can be handled
with the following functions:

{\tt \idx{signe}, \idx{setsigne}, \idx{varn}, \idx{setvarn}} as for
polynomials, and {\tt \idx{valp}, \idx{setvalp}} for the exponent as for
$p$-adic numbers. Beware not to use {\tt expo} and {\tt setexpo} for power
series.

If the power series is non-zero, {\tt z[2]}, {\tt z[3]},\dots {\tt
z[lg(z)-1]} point to the coefficients of {\tt z} in ascending order, {\tt
z[2]} being the first non-zero coefficient.  Note that the exponent of a
power series can be negative, i.e.~we are then dealing with a Laurent series
(with a finite number of negative terms).

\sectypes{RFRAC}{RFRACN}{rational function} {\tt z[1]} points to the
numerator, and {\tt z[2]} on the denominator. Both must be of type
polynomial. Note that a type \typ{RFRACN} rational function can be
converted to irreducible form using the function {\tt gred}.\sidx{gred}

\sectype{QFR}{indefinite binary quadratic form} {\tt z[1]}, {\tt z[2]}, {\tt
z[3]} point on the three coefficients of the form and should be of type
integer. {\tt z[4]} is Shanks's distance function, and should be of type
real.

\sectype{QFI}{definite binary quadratic form} {\tt z[1]}, {\tt z[2]}, {\tt
z[3]} point on the three coefficients of the form. All three should be of
type integer.

\sidx{row vector}\sidx{column vector}
\sectypes{VEC}{COL}{vector} {\tt z[1]}, {\tt z[2]},\dots {\tt z[lg(z)-1]}
point on the components of the vector.

\sectypeindex{MAT}{matrices}{matrix} {\tt z[1]}, {\tt z[2]},\dots {\tt
z[lg(z)-1]} point on the column vectors of {\tt z}, i.e.~they must be of type
\typ{COL} and of the same length.

\noindent The last two were introduced for specific GP use, and you'll be
much better off using the standard malloc'ed C constructs. We quote them just
for completeness (advising you not to use them):

\sectype{LIST}{list} This one has a second codeword which contains an
effective length (handled through {\tt lgef}/{\tt setlgef}). {\tt
z[2]},\dots, {\tt z[lgef(z)-1]} contain the list's components.

\sectype{STR}{character string} {\tt GSTR(z)} (= {\tt (z+1)}) points to the
first character of the ({\tt NULL}-terminated) string.

\section{PARI variables.}\label{se:vars}

We now consider variables and formal computations. As we have seen in
\secref{se:impl}, the codewords for types \typ{POL} and \typ{SER}
encode a ``variable number''. This is an integer, going from $0$ to 
{\tt MAXVARN}. The lower it is, the higher the variable priority. PARI does
not know anything about intelligent ``sparse'' representation of polynomials.
So a multivariate polynomial in PARI is just a polynomial (in one variable),
whose coefficients are themselves (arbitrary) polynomials. All computations
are then just done formally on the coefficient as if the polynomial was
univariate.

  In fact, the way an object will be considered in formal computations depend
entirely on his ``principal variable number'' which is given by the function
{\tt long \idx{gvar}(GEN z)} which returns a \idx{variable} number for {\tt
z}, even if {\tt z} is not a polynomial or power series. The variable number
of a scalar type is set by definition equal to {\tt BIGINT} which is bigger
than any legal variable number. The variable number of a recursive type which
is not a polynomial or power series is the minimal variable number of its
components. But for polynomials and power series only the ``outermost''
number counts: the representation is not symetrical at all.

  Under GP, one need not worry too much since the interpreter will define
the variables as it sees them and do the right thing with the polynomials
produced (however, have a look at the remark in \secref{se:rempolmod}). But
in library mode, they are tricky objects if you intend to build polynomials
yourself (and not just let PARI functions produce them, which is usually less
efficient). For instance, it does not make sense to have a variable number
used in the components of a polynomial whose main variable has lower
priority, even though there's nothing PARI can do to prevent you from doing
it.

  The other, more basic, difficulty is to ``create'' a variable. As we have
seen in \secref{se:intro4}, we have a variety of objects associated to a
variable number {\tt v}. Here is the complete list: {\tt polun[v]} and {\tt
polx[v]}, which you can use in library mode and represent respectively the
monomials of degree 0 and 1 in {\tt v}, {\tt varentries[v]} and {\tt
polvar[v]}. The latter two are only meaningful to GP, but they have to be set
nevertheless. All of them must be properly defined before you can use a given
integer as a variable number.

  Initially, this is done for $0$ (the variable {\tt x} under GP), and 
{\tt MAXVARN}, which is there to address the need for a ``temporary'' new
variable, which would not be used in regular objects (created by the
library). We call the latter type a ``user variable''. {\tt MAXVARN} should
be enough for most cases, but you can create more user variables using

{\tt long fetch\_var()}\sidx{fetch\string\_var}

This returns a variable number which is guaranteed to be unused by the
library at the time you get it and as long as you do not delete it (we'll see
how to do that shortly). This has {\it lower} number (i.e.~{\it higher}
priority) than any user variable produced so far ({\tt MAXVARN} is assumed to
be the first one). This updates all the aforementioned internal arrays. In
particular, after the statement {\tt v = fetch\_var()}, you can use 
{\tt polun[v]} and {\tt polx[v]}. The variables created in this way have no
assigned identifier though, and they will be printed as {\tt
\#<\text{number}>}, except for {\tt MAXVARN} which will be printed {\tt \#}.

All objects created by {\tt fetch\_var} are on the heap and not the stack,
thus they are not subject to standard garbage collecting (they won't be
destroyed by a {\tt gerepile} or {\tt avma = ltop} statement). When you don't
need a variable number anymore, you can delete it using

{\tt long delete\_var()}\sidx{delete\string\_var}

\noindent which deletes the {\it last} user variable created and return the
variable number of the previous one (or simply return 0 if you try to delete
{\tt MAXVARN}). Of course you should make sure that this variable does not
appear anywhere in the objects you use later on. Here is an example:

\bprog\obr
\q  long first = fetch\_var();
\q  long n1 = fetch\_var();
\q  long n2 = fetch\_var(); /* prepare three variables for internal use */
\q  ...
\q  /* delete all variables before leaving */
\q  do \obr\ num = delete\_var(); \cbr\ while (num \&\& num <= first);
\cbr\eprog

The (dangerous) statement 

\bprog
while (delete\_var()) /* empty */;
\eprog

\noindent removes all user variables that were in use (except {\tt MAXVARN}
which cannot be deleted).

\section{Input and output.}

Two important aspects have not yet been explained which are specific to
library mode: input and output of PARI objects.

\subsec{Input.}

For \idx{input}, PARI provides you with two powerful high level functions
which enables you to input your objects as if you were under GP. In fact, the
second one {\it is\/} essentially the GP syntactical parser, hence you can
use it not only for input but for (most) computations that you can do under GP.
These functions are called {\tt \idx{flisexpr}} and {\tt \idx{flisseq}}. The
first one has the following syntax:

{\tt GEN \idx{flisexpr}(char* s)}

Its effect is to analyze the input string s and to compute the result as in
GP.  However it is limited to one expression. If you want to read and
evaluate a sequence of expressions, use

{\tt GEN \idx{flisseq}(char* s)}

  In fact those two functions start by {\it\idx{filter}ing\/} out all spaces
and comments in the input string (that's what the initial {\tt f} stands
for). These then call the underlying basic functions, the GP parser proper:
{\tt GEN lisexpr(char *)} and {\tt GEN lisseq(char *)}, which are slightly
faster but which you probably don't need.

  Once in a while, it may be necessary to have the evaluation of the string
involving a call to a function you have defined in C. This is easy using
{\tt \idx{install}} which allows you to manipulate quite an arbitrary
function. The only restriction is that there is no way to pass your arguments
as variables (GP does not know about pointers !). The syntax is 

{\tt void install(void *f, char *name, char *code)}

where {\tt name} is the name under which you will access your function
in your GP expressions, {\tt f} is the (casted address of) the
function, and {\tt code} is a character string describing its prototype
(see \secref{se:gp.interface} for the precise description of those).

\subsec{Output.}
For \idx{output}, there exist essentially three different functions (with
variants), corresponding to the three main GP output formats (as described in
\secref{se:output}), plus three extra ones, respectively devoted to
\TeX\ output, string output, and (advanced) debugging.

\noindent $\bullet$ ``raw'' format: This is obtained by using the function
{\tt \idx{brute}} with the following syntax:

{\tt void \idx{brute}(GEN obj, char x, long n);}

This prints the PARI object {\tt obj} in \idx{format} {\tt x0.n}, using the
notations from \secref{se:format}. Recall that here {\tt x} is either
{\tt 'e'}, {\tt 'f'} or {\tt 'g'} corresponding to the three output formats
and {\tt n} is the number of printed significant digits, and should be put
equal to $-1$ if all of them are wanted (these arguments only affect the
printing of real numbers). Usually you won't need that much flexibility, so
the default use will be through the function:

{\tt void \idx{outbrute}(GEN obj)}, which is equivalent to
{\tt brute(x,'g',-1)}. 

\noindent Or even better, the function:

{\tt void \idx{output}(GEN obj)} which is equivalent to {\tt outbrute(obj)}
followed by a newline and a buffer flush. This is especially nice during
debugging. For instance using {\tt dbx} or {\tt gdb}, if {\tt obj} is a {\tt
GEN}, typing {\tt print output(obj)} will enable you to see the content of
{\tt obj} (provided the optimizer has not put it into a register, but it's
seldom a good idea to debug optimized code).

\noindent $\bullet$ ``prettymatrix'' format: this format is identical to the
preceding one except for matrices. The relevant functions are:

{\tt void \idx{matbrute}(GEN obj, char x, long n)}

{\tt void \idx{outmat}(GEN obj)}, which is followed by a newline and a buffer
flush.

\noindent $\bullet$ ``prettyprint'' format: the basic function has an
additional paramtere {\tt m}, corresponding to the field width of GP used for
printing integers:

{\tt void sor(GEN obj, char x, long n, long m)}

\noindent The simplified version is

{\tt void \idx{outbeaut}(GEN obj)} which is equivalent to {\tt
sor(obj,'g',-1,0)} followed by a newline and a buffer flush.

\noindent $\bullet$ The first extra format corresponds to the {\tt texprint}
function of GP, and gives a \TeX{} output of the result. It is obtained by
using:

{\tt void \idx{texe}(GEN obj, char x, long n)}

\noindent $\bullet$ The second one is the function {\tt GENtostr} which
converts a PARI {\tt GEN} to an ASCII string. The syntax is

{\tt char* GENtostr(GEN obj)}, wich returns a {\it malloc}'ed character string
(which you should {\tt free} after usage).

\noindent $\bullet$ The third and final one outputs the \idx{hexadecimal tree}
corresponding to the GP command \b x using the function

{\tt void voir(GEN obj, long nb)}, which will only output the first {\tt nb}
words corresponding to leaves (very handy when you have a look at big
recursive structures). If you set this parameter to $-1$ all significant
words will be printed. In principle this last type of output is used only for
debugging purposes.

\medskip
{\bf Remark.} Apart from {\tt GENtostr}, all PARI output is done on the
stream {\tt \idx{outfile}}, which by default is initialized to {\tt stdout}.
If you want that your output be directed to another file, you should use the
function {\tt void \idx{switchout}(char *name)} where {\tt name} is a
character string giving the name of the file you are going to use. The
printing is {\it appended\/} at the end of the file.  When you want to close
the file, you simply call {\tt switchout(NULL)}.

  Similarly, errors are sent to the stream {\tt \idx{errfile}} ({\tt stderr}
by default), and input is done on the stream {\tt infile} using the function
{\tt \idx{switchin}} analogous to {\tt switchout}.

\medskip
{\bf (Advanced) Remark.} All output is done according to the values of the
{\tt pariOut} / {\tt pariErr} global variables which are pointers to structs
of pointer to functions. If you really intend to use these, this probably
means you are rewriting GP. In that case, have look at the code in {\tt
language/es.c} ({\tt init80()} or {\tt GENtostr()} for instance).

\sidx{error}\sidx{talker}
\subsec{Errors.}

If error messages are to be generated in your functions, you can use the
general error handling routine {\tt err}. The basic syntax is
%
\bprog
  err(talker, \quo error message\quo);
\eprog

This will print the corresponding error message and exit the program (in
library mode; go back to the GP prompt otherwise).\label{se:err} You can also
use it in the more versatile guise
\bprog
  err(talker, format, ...);
\eprog\noindent
where {\tt format} describes the format to use to write the remaining
operands, as in the {\tt printf} function (however, see the next section).
The simple syntax above is just a special case with a constant format and no
remaining arguments.

The general syntax is

{\tt void err(numerr,...)}

\noindent where {\tt numerr} is a codeword which indicates what to do with
the remaining arguments and what message to print. The list of valid keyword
is in {\tt language/errmessages.c} together with the basic corresponding
message. For instance, {\tt err(typeer,"matexp")} will print the message:

{\tt  ***   incorrect type in matexp.}

Among the codewords are {\it warning} keywords (all those that start with
the prefix {\tt warn}). In that case, {\tt err} does {\it not} abort the
computation, just print the requested message and go on. The basic example is

{\tt err(warner, "Strategy 1 failed. Trying strategy 2")}

\noindent which is the exact equivalent of {\tt err(talker,...)} except that
you certainly don't want to stop the program at this point, just be informed
that something important occured (in particular, this output would be
suitably highlighted under GP, whereas a simple {\tt printf} would not).

\subsec{Debugging output.}\sidx{debugging}\sidx{format}\label{se:dbg_output}

The global variables {\tt DEBUGLEVEL} and {\tt DEBUGMEM} (corresponding
to the default {\tt debug} and {\tt debugmem}, see \secref{se:defaults}) 
are used throughout the PARI code to generate debugging output, depending on 
their value. You can use them to debug your function, especially if you
can easily access them under GP through the command {\tt install} (see
\secref{se:install}).

For debugging output, you can use {\tt printf} and the standard output
functions ({\tt brute} or {\tt output} mainly), but also some special purpose
functions which embody both concepts, the main one being

{\tt void \idx{fprintferr}(char *pariformat, ...)}

First let's define what a PARI format is. It is a character string, similar
to the one {\tt printf} uses, where {\tt \%} characters have a special
meaning. It describes the format to use when printing the remaining operands.
But, in addition to the standard format types, you can use {\tt \%Z} to
denote a {\tt GEN} object (we would have liked to pick {\tt \%G} but it was
already in use!). For portability reasons, you have to cast to {\tt long} the
corresponding {\tt GEN} argument. For instance you could write:

{\tt err(talker, "x[\%d] = \%Z is not invertible!", i, (long)x[i])},

\noindent since the {\tt err} function uses PARI formats. Here {\tt i} is an
{\tt int}, {\tt x} a {\tt GEN} which is not a leaf and this would insert in
raw format the value of the {\tt GEN} {\tt x[i]} (and the cast is not
necessary of course).

\subsec{Timer output}

To profile, your functions, you can use the PARI timer. The functions {\tt
long \idx{timer}()} and {\tt long \idx{timer2}()} return the elapsed time
since the last call of the function (in milliseconds). Two different
(identical!) functions are provided so you can have both global timing and
fine tuned profiling.

You can also use {\tt void \idx{msgtimer}(char *format,...)}, which prints
prints {\tt Time}, then the remaining arguments as specified by {\tt format}
(which is a PARI format), then the output of {\tt timer2()}.

\section{A complete program.}
\label{se:prog}

Now that the preliminaries are out of the way, the best way to learn how to
use the library mode is to work through a detailed non-trivial example of a
main program. We will write a program which computes the exponential of a
square matrix $x$.  The complete listing is given in Appendix C, but each
part of the program will be written and commented here. We will use an
algorithm which is not optimal but is not far from the one used for the PARI
function {\tt gexp} (in fact in the function {\tt mpexp1}). This consists in
calculating the sum of the series:
$$e^{x/(2^n)}=\sum_{k=0}^\infty \dfrac{(x/(2^n))^k}{k!}$$
for a suitable positive integer $n$, and then computing $e^x$ by repeated
squarings.  First, we will need to compute the $L^2$-norm of the matrix $x$,
i.e.~the quantity:
$$z=\|x\|_2=\sqrt{\sum_{i,j}x_{i,j}^2}.$$
We will then choose the integer $n$ such that the $L^2$-norm of $x/(2^n)$ is
less than or equal to 1, i.e.
$$ n = \left\lceil\dfrac{\ln(z)}{\ln(2)}\right\rceil $$
if $z\ge1$. Then the convergence of the series will be at least as good as
the one for $e^1$, and will be easy to estimate. In fact a larger value of
$n$ would be preferable, but this is slightly machine dependent and more
complicated, and will be left to the reader.

We will now start writing our program. So as to be able to use it in other
contexts, we will structure it in the following way: a main program which
will do the input and output, and a function which we shall call {\tt matexp}
which does the real work. The main program is easy to write. It can be
something like this:

\bprog
\#include <genpari.h>
\h
GEN matexp(GEN x, long prec);
\h
main()
\obr
\q GEN x, y;
\q long d, prec = 3;
\q char s[512];
\h
\q init(1000000,2); /* take a stack of million bytes, no prime table */
\q printf("precision of the computation in decimal digits? ");
\q scanf("\%d",\&d); if (d>0) prec = (long)(d*pariK1+3);
\h
\q printf("input your matrix in GP format:\bs n");
\q s[0]=0; while (!s[0]) gets(s);
\q x = flisexpr(s); y = matexp(x,prec);
\q sor(y,'g',d,0);
\cbr 
\eprog

The variable {\tt prec} represents the length in longwords of the real
numbers used. {\tt pariK1} is the constant (defined in
{\tt headers/gencom.h}) equal to $\ln(10) / (\ln(2) * {\tt BITS\_IN\_LONG})$,
which allows us to convert from a number of decimal digits to a number of
longwords, independently of the actual bit size of your long integers. The
function {\tt flisexpr} was mentioned earlier and avoids any trouble in the
input. In fact, as was also mentioned, {\tt flisexpr} can take any legal GP
expression hence can do not only input but also computations. Note that we
have used the construction {\tt gets} to get our string, instead of {\tt
scanf} which would make trouble in this case.

Finally, {\tt sor} is the general output routine. We have chosen to give
{\tt d} significant digits since this is what was asked. Note that there is a
trick hidden here: if {\tt d} was given to be negative, then the computation
will be done in precision 3 (i.e.~about 9.7 decimal digits for 32-bit
machines and 19.4 for 64-bit machines) and in the function {\tt sor}, giving
a negative third argument outputs all the significant digits, hence nothing
is wrong. Now let us attack the main course, the function {\tt matexp}:
%
\bprog
GEN 
matexp(GEN x, long prec)
\obr
\q  long lx=lg(x),i,k,n,lbot, ltop = avma;
\q  GEN y,r,s,p1,p2;
\h
\q /* check that x is a square matrix */
\q if (typ(x) != t\_MAT) err(talker,"this expression is not a matrix");
\q if (lx == 1) return cgetg(1, t\_MAT);
\q if (lx != lg(x[1])) err(talker,"not a square matrix");
\h
\q /* compute the L2 norm of x */
\q s = gzero;
\q for (i=1; i<lx; i++)
\q\q s = gadd(s, gnorml2((GEN)x[i]));
\q if (typ(s) == t\_REAL) setlg(s,3);
\q s = gsqrt(s,3); /* we do not need much precision on s */
\h
\q /* if s<1, we are happy */
\q k = expo(s);
\q if (k < 0) \obr\ n = 0; p1 = x; \cbr 
\q else \obr\ n = k+1; p1 = gmul2n(x,-n); setexpo(s,-1); \cbr 
\eprog

Before continuing, a few remarks are in order:

First, before starting this computation which will produce garbage on the
stack, we have carefully kept the value of the stack pointer {\tt avma} in 
{\tt ltop}. Note that we are going to assume throughout that the garbage does
not overflow the memory that we allocated on the stack. If it did, we would
have two solutions.  Either allocate more memory in the main program (for
instance change 1000000 into 2000000), or do some {\tt gerepile} along the
way.

Second, the {\tt \idx{err}} function is the general error handler for the
PARI library. This will abort the program after printing the required
message.

Third notice how we handle the special case ${\tt lx} = 1$ (empty matrix)
{\it before\/} accessing {\tt lx(x[1])}. Doing it the other way round could
produce a fatal error ({\tt SIGBUS} most probably). Indeed, if {\tt x} is of
length 1, then {\tt x[1]} is not a component of {\tt x}. It is just the
content of the memory cell next to the one pointed by {\tt x}, which has thus
no reason to be a valid {\tt GEN}. Now recall that none of the codeword
handling macros do any kind of type checking (see \secref{se:impl}), thus
{\tt lg} is going to consider {\tt x[1]} as a valid address, and try to
access {\tt *((GEN)x[1])} (the first codeword) which will probably not make
sense.

Fourth, to compute the square of the $L^2$-norm of {\tt x} we just add the
squares of the $L^2$-norms of the column vectors which we obtain using the
library function {\tt gnorml2}. Had this function not existed, it would of
course have been just as easy, but we would have had to make a double loop.

Then, we take the square root of {\tt s}, in precision 3 (the minimal one).
The {\tt prec} argument of transcendental functions (here $3$) is only taken
into account for {\it exact\/} object, when no a priori precision can be
determined from the object itself. To cater for this fact, if {\tt s} is of
type \typ{REAL}, we use the function {\tt setlg} which effectively sets
the precision of {\tt s} to the required value. Note that here, as we use a
numeric value for a {\tt cget} function, the program will run slightly
differently on 32-bit and 64-bit machines: we want to use the smallest
possible bit accuracy, and this is equal to {\tt BITS\_IN\_LONG}.

Note that the matrix {\tt x} is allowed to have complex entries, but the
function {\tt gnorml2} guarantees that s is a non-negative real number (not
necessarily of type \typ{REAL} of course). If we had not known this fact,
we would simply have added the instruction {\tt s = greal(s);} just after the
{\tt for} loop.

Note also that the function {\tt gnorml2} works as desired on matrices, so we
did not need this loop at all ({\tt s = gnorml2(x)} would have been enough),
but we wanted to give examples of function usage. Similarly, it is of course
not necessary to compute the square root for making our tests.

Fifth, note that we initialized the sum {\tt s} to {\tt gzero}, which is an
exact zero. This is logical, but has some disadvantages: if all the entries
of the matrix are integers (or rational numbers), the computation will be
rather long, about twice as long as with real numbers of the same length.
It would be better to initialize {\tt s} to a real zero, using for instance
the instructions:

{\tt s = cgetr(prec+1); gaffsg(0,s);}

As is, this does not make much sense: which real zero do we get in this way
(have a look at \secref{se:whatzero}) ? In fact, the following choice
has been made: it will give you the zero with exponent equal to $-{\tt
BITS\_IN\_LONG}$ times the number of longwords in the mantissa, i.e.~$-{\tt
bit\_accuracy(lg(s))}$. More simply, you can use the function {\tt GEN
\idx{realzero}(long prec)} which returns a real zero to accuracy 
{\tt -bit\_accuracy(prec)}.

Sixth, we will want to look at the approximate size of real numbers, and the
fastest way to do this is to look at their binary exponents. Hence we need to
have {\tt s} as a real number, and not as an integer or a rational number.
The result of transcendental functions is guaranteed to be of type 
\typ{REAL} or complex of \typ{REAL}, thus this is indeed the case after the
call to {\tt gsqrt} since we started from a real number.

Finally, note the use of the function {\bf \idx{gmul2n}}. It has
the following syntax:

{\tt GEN gmul2n(GEN x,long n);}

\noindent and the effect is simply to multiply {\tt x} by $2^{\text n}$,
where {\tt n} can be positive or negative. This is much faster than {\tt
gmul} or {\tt gmulgs}.

There is another function {\bf \idx{gshift}} with exactly the same syntax.
When {\tt n} is non-negative, the effects of these two functions is the same.
However when {\tt n} is negative, {\tt gshift} acts like a right shift of
{\tt -n}, hence does not give the same effect on integers. The function {\tt
gshift} is the PARI analogue of the C operators {\tt <<} and {\tt >>}.

We now come to the heart of the function. We have a {\tt GEN p1} which
points to a certain matrix of which we want to take the exponential. We will
want to transform this matrix into a matrix with real (or complex of real)
entries before starting the computation. To do this, we simply multiply by
the real number 1 in precision ${\tt prec}+1$ (to be safe). Then, to compute
the series we will keep three variables: a variable {\tt p2} which at stage k
will contain ${\tt p1}^k/k!$, a variable {\tt y} which will contain
$\sum_{i=0}^k {\tt p1}^i/i!$, and the variable {\tt r} which will contain
${\tt s}^k/k!$. Note that we do not use Horner's rule. This is simply because
we are lazy and do not want to compute in advance the number of terms that we
need. We leave this modification (and many other improvements!) to the
reader. The program continues as follows:

\bprog
\q /* initializations before the loop */
\q r = cgetr(prec+1); gaffsg(1,r); p1 = gmul(r,p1);
\q y = gscalmat(r,lx-1); /* creates scalar matrix with r on diagonal */
\q p2 = p1; r = s; k = 1;
\q y = gadd(y,p2);
\h
\q /* now the main loop */
\q while (expo(r) >= -BITS\_IN\_LONG*(prec-1))
\q \obr
\q\q k++; p2 = gdivgs(gmul(p2,p1),k);
\q\q r = gdivgs(gmul(s,r),k); y = gadd(y,p2);
\q \cbr 
\h
\q  /* now square back n times if necessary */
\q if (!n) \obr\ lbot = avma; y = gcopy(y); \cbr 
\q else
\q \obr 
\q\q for (i=0; i<n; i++) \obr\ lbot = avma; y = gsqr(y); \cbr 
\q \cbr 
\q return gerepile(ltop,lbot,y);
\cbr 
\eprog

A few remarks once again. First note the use of the function {\bf
\idx{gscalmat}} with the following syntax:

{\tt GEN gscalmat(GEN x, long m);}

The effect of this function is to create the ${\tt m}\times{\tt m}$ scalar
matrix whose diagonal entries is {\tt x}. Hence the length of the matrix
including the codeword will in fact be {\tt m+1}.  There is a corresponding
function {\bf \idx{gscalsmat}} which takes a long as a first argument. 

If we refer to what has been said above, the main loop is clear.

When we do the final squarings, according to the fundamental theorem on the
use of {\tt gerepile} we keep the value of {\tt avma} in {\tt lbot} just {\it
before} the squaring, so that if it is the last one, {\tt lbot} will indeed
be the bottom address of the garbage pile, and {\tt gerepile} will work. Note
that it takes a completely negligible time to do this in each loop compared
to a matrix squaring.  However, when {\tt n} is initially equal to 0, no
squaring has to be done, and we have our final result ready but we lost the
address of the bottom of the garbage pile. Hence we use the trick of copying
{\tt y} again on top of the stack. This is inefficient, but does the work. If
we wanted to avoid this using only {\tt gerepile}, the best thing to do would
be to put the instruction {\tt lbot=avma} just before both occurrences of the
instruction {\tt y=gadd(p2,y)}. Of course, we can rewrite the last block as
follows:

\bprog
\q /* now square back n times */
\q for (i=0; i<n; i++) y = gsqr(y);
\q return gerepileupto(ltop,y);
\cbr 
\eprog\noindent
because it does not matter to {\tt \idx{gerepileupto}} that we lost the address
just before the final result (note that the loop is not executed if {\tt n}
is 0). It is safe to use {\tt gerepileupto} here as {\tt y} will have been created
by either {\tt gsqr} or {\tt gadd}, both of which are guaranteed to return
suitable objects.

\noindent{\bf Remarks:} as such, the program should work most of the time if
{\tt x} is a square matrix with real or complex entries. Indeed, since
essentially the first thing that we do is to multiply by the real number 1,
the program should work for integer, real, rational, complex or quadratic
entries. This is in accordance with the behavior of transcendental functions.

Furthermore, since this program is intended to be only an illustrative
example, it has been written a little sloppily. In particular many error
checks have been omitted, and the efficiency is far from optimal. An evident
improvement was the use of {\tt gerepileupto} mentionned above. Another
improvement is to multiply the matrix x by the real number 1 right at the
beginning, speeding up the computation of the $L^2$-norm in many cases. These
improvements are included in the version given in Appendix C. Still another
improvement would come from a better choice of {\tt n}. If the reader takes a
look at the implementation of the function {\tt mpexp1} in the file {\tt
basemath/trans1.c} he can make himself the necessary changes. Finally, there
exist other algorithms of a different nature to compute the exponential of a
matrix.

\medskip\noindent
{\bf Remark}: While writing this program, we have seen a few new functions
(the complete list of available functions is given by alphabetical order in
the index). However, if you care to look at the file {\tt
headers/gendecl.h}, you will notice that many more functions are defined.
But in every case these missing functions are particular cases of general
functions. For example, we have the function {\tt gneg}, which takes the
negative of a PARI object. However, there also exist functions like {\tt
negi} (for type integer), {\tt negr} (for type real), and {\tt mpneg} (for
type integer or real).

These functions can of course be called by the user but we feel that the few
microseconds lost in calling more general functions (in this case {\tt gneg})
is compensated by the fact that one needs to remember a much smaller number
of functions, and also because there is a hidden danger here: the type of the
objects that you use, if they are themselves results of a previous
computation, is not completely predetermined. For instance the multiplication
of a type real by a type integer {\it usually\/} gives a result of type real,
except when the integer is 0, in which case according to the PARI philosophy
the result is the exact integer 0. Hence if afterwards you call a function
which specifically needs a real type argument, you are in trouble.

If you really want to use these functions, their names are self-explanatory
once you know that {\bf i} stands for a PARI integer, {\bf r} for a PARI
real, {\bf mp} for i or r, {\bf s} for an ordinary signed long, {\bf
z} (as a suffix) meaning as usual that the result is not created on the PARI
stack but assigned to a preexisting GEN given as an extra argument.

For completeness, in Chapter 5 we have given a description of all these
low-level functions.

Please note that in the present version \vers{} the names of the functions
are not always consistent. This will be changed. Hence anyone programming in
PARI must be aware that the names of almost all functions that he uses will
change eventually. If the need arises (i.e.~if there really are people out
there who delve into the innards of PARI), updated versions with no name
changes will be released.

\section{Adding functions to PARI.}
\subsec{Nota Bene.}

As already mentioned, modified versions of the PARI package should NOT be
spread without our prior approval. If you do modify PARI, however, it is
certainly for a good reason, hence we would like to know about it, so that
everyone can benefit from it. There is then a good chance that the
modifications that you have made will be incorporated into the next release.

(Recall the e-mail: {\tt pari@math.u-bordeaux.fr}).

Roughly four types of modifications can be made. The first type includes all
improvements to the documentation, in a broad sense. This includes correcting
typos or inacurracies of course, but also items which are not really covered
in this document, e.g if you happen to write a tutorial, or pieces of code
exemplifying some fine points that you think were unduly omitted.

  The second type is to expand or modify the configure routines and skeleton
files (the {\tt Configure} script and anything in the {\tt config/}
subdirectory) so that compilation is possible (or easier, or more efficient)
on a new system. This includes suppressing any idiosyncrasies in the code
that would hinder its portability.

  The third type is to modify existing (mathematical) code, either to correct
bugs, to add new functionalities to existing functions, or to improve their
efficiency.

Finally the last type is to add new functions to PARI. We explain here how
to do this, so that in particular the new function can be called from GP.

\subsec{Interface with GP.}
\label{se:gp.interface}

First code your function, preferably in a file of its own, using as a guide
other functions in the PARI sources. One important thing to remember is to
always clean the stack before exiting your main function (usually using {\tt
gerepile}) otherwise the successive calls to the function will clutter the
stack with unnecessary garbage and stack overflow will occur sooner.

If error messages are to be generated in your function, use the general error
handling routine {\tt err} (see \secref{se:err}). Recall that this
function does not return, but ends with a {\tt longjmp} statement. As well,
instead of explicit {\tt printf} / {\tt fprintf} statements, try to use the
following:

{\tt void \idx{pariputs}(char *s)}: write {\tt s} on GP output file.

{\tt void \idx{fprintferr}(char *s)}: write {\tt s} on GP error stream (this
function is in fact much more versatile, see \secref{se:dbg_output}).

Declare all public functions in {\tt gendecl.h} (you want the outside
world to know about them). The other ones should be declared {\tt static} in
your file.

Your function is now ready to be used in library mode after compilation and
creation of the library. It is however still inaccessible from GP.
\smallskip

To make it known to GP, you must do the following. First, find a name for
your function under GP. It does not have to be identical to the one used
in library mode, but consistency is nice. It has to be a valid GP identifier,
i.e.~use only alphabetic characters, digits and underscore character 
(\kbd{\_}), the first character being alphabetic. Then in the definition of
{\tt functions\_basic} (file {\tt language/init.c}) place in exact
alphabetical order of the GP name (note that digits $<$ letters) a line of
the form:

{\tt \obr"gpname",V,(void*)libname,secno,"code",NULL,NULL,NULL\cbr,}

\noindent where 

{\tt libname} is the name of your function in library mode,

{\tt gpname} the name that you have chosen to call it under GP,

{\tt secno} is the section number of Chapter 3 in which this function should
belong (type {\tt ?} in GP to see the list),

{\tt V} is a number between 0 and 99. Right now, there are only two
significant values: zero meaning that it's possible to call the function
without argument, and non-zero which means it needs at least one argument.

{\tt code} is a character string describing all the parser needs to know about
the function prototype. It contains the following atoms:
%
\bprog
\noindent $\bullet$ {\rm Arguments, described in input order:}
\q G\q  GEN
\q L\q  long {\rm (we implicitly identify {\tt int} with {\tt long})}
\q S\q  {\rm symbol (i.e.~GP identifier name). Send a pointer to {\tt entree}}
\q V\q  {\rm variable (same as {\tt S}, but symbols associated to functions will be rejected)}
\q n\q  {\rm send the {\tt long} internal variable number (and not a {\tt *entree})}
\q I\q  {\rm input position for control statements, to be processed with {\tt lisexpr} or {\tt lisseq}}.
\h
\q F\q  {\rm Fake {\tt *GEN}: function requires a {\tt *GEN}, but we don't use the resulting {\tt GEN}}
\q f\q  {\rm Fake {\tt *long}}
\h
\q p\q  {\rm real precision (default {\tt realprecision})}
\q P\q  {\rm series precision (default {\tt seriesprecision}, global variable {\tt precdl} for the library)}
\h
\q r\q  {\rm raw input (treated as a string without quotes). Quoted args are copied as strings. Stops at first unquoted {\tt ')'} or {\tt ','}. Special chars can be quoted using '{\tt \bs{}}'. Example: {\tt aa"b\bs n)"c} yields the string {\tt "aab\bs{n})c"}}
\q s\q  {\rm expanded string. Example: {\tt Pi"x"2} yields {\tt "3.142x2"} The unquoted components can be of any PARI type (converted according to the current output format)}
\q s*\q {\rm any number of strings (see {\tt s})}
\q s*p\q {\rm idem, setting ${\tt prettyp} = 1$ (i.e.~in beautified format)}
\q s*t\q {\rm idem, in \TeX\ format}
\h
\q D\q  {\rm argument has a default value. Format is ``{\tt Dvalue,type,}'' (the ending comma is mandatory). Ex: {\tt D0,L,} (arg is {\tt long}, {\tt 0} by default). Special syntax: if type = {\tt GEN}, {\tt DG} (no ending comma this time) send {\tt NULL}. The user-given arguments are read first, then completed by the defaults}
\h
\noindent $\bullet$ {\rm Return type: {\tt GEN} by default, otherwise the following can appear anywhere in the code}
%
\q l\q {\rm return} long
\q v\q {\rm return} void
\h
\noindent $\bullet$ {\rm Syntax requirements (used by the functions {\tt for}, {\tt sum}, etc.):}
%
\q =\q {\rm separator {\tt '='} required}
\eprog

\noindent For instance, here is how you would code the following 
prototypes:
\bprog
\settabs\+GEN name(GEN x, GEN y, long prec) & -----> & "GGp"\cr
\+ GEN name(GEN x, GEN y, long prec)  & -----> & "GGp"\cr
\+ void name(GEN x, long y, long prec) & -----> & "vGLp" {\rm {\tt "GvLp"}
would be ok as well)}\cr
\+ long name(GEN x) & -----> & "Gl"\cr
\eprog

\noindent {\bf Remark:} If you really need to implement complicated control
statements (probably for some improved sumations functions), you'll need to
know about the {\tt entree} type, which is not documented. Check the comment
before the function list at the end of {\tt language/init.c} and the source
code in {\tt language/sumiter.c}. You should be able to make something of it.
\smallskip

Once this has been done, in the file {\tt language/helpmessages.c} write in
exact alphabetical order a short message describing the effect of your
function:
{\tt \quo name(x,y,...)=short descriptive message\quo,}

The message must be a single line (which may have more than 80 characters).
Do not use {\tt \bs{n}}, the necessary newlines will be inserted by GP online
help functions. Optional arguments should be enclosed between braces (see the
other messages for comparative purposes). \smallskip

Finally create (or append to) a file called, say, {\tt Changes}, which lists
the modifications that you have made. After compiling and debugging, you now
have a new function available under GP (and we would very much like to hear
about it!).

\subsec{Example.}

A complete description could look like this (the following line is taken
verbatim from {\tt language/init.c}):
%
\bprog
\obr "bnfinit",91,(void*)bnfinit0,6,"GD0,L,DGp",NULL,NULL,NULL \cbr
\eprog\noindent 
%
which means we have a function {\tt bnfinit} under GP, which calls the
library function {\tt bnfinit0} (in fact coded in {\tt basemath/buch2.c} but
GP does not need to know about this), with one mandatory argument ({\tt V} is
non-zero), and possibly two more (two {\tt 'D'} in the code), plus the
current real precision. More precisely, the first argument is a {\tt GEN},
the second one is converted to a {\tt long} using {\tt itos} ({\tt 0} is sent
if it is omitted), and the third one is also a {\tt GEN}, but we send {\tt
NULL} if no argument was supplied by the user. This correspond to the C
prototype (from {\tt headers/gendecl.h}):
%
\bprog
  GEN bnfinit0(GEN P, long flag, GEN data, long prec)
\eprog\noindent 
%
Finally the help message (from {\tt language/helpmessages.c}) reads:
%
\bprog
  "bnfinit(P,\obr flag=0\cbr,\obr tech=[]\cbr): compute the necessary data for..."
\eprog
You see in this example that it is the function's responsibility to correctly
interpret its operands: {\tt data = NULL} is interpreted {\it by the function}
as an empty vector. Note that as {\tt NULL} is never a valid {\tt GEN} value,
this trick always enables to distinguish between a default value and an
actual input: the user could explicitly supply an empty vector!
\vfill\eject
