*************
* intro
*************

Quick introduction

    This is an interactive calculator which provides for easy large
    numeric calculations, but which also can be easily programmed
    for difficult or long calculations.  It can accept a command line
    argument, in which case it executes that single command and exits.
    Otherwise, it enters interactive mode.  In this mode, it accepts
    commands one at a time, processes them, and displays the answers.
    In the simplest case, commands are simply expressions which are
    evaluated.  For example, the following line can be input:

	    3 * (4 + 1)

    and the calculator will print 15.

    The special '.' symbol (called dot), represents the result of the
    last command expression, if any.  This is of great use when a series
    of partial results are calculated, or when the output mode is changed
    and the last result needs to be redisplayed.  For example, the above
    result can be doubled by typing:

	    . * 2

    and the calculator will print 30.

    For more complex calculations, variables can be used to save the
    intermediate results.  For example, the result of adding 7 to the
    previous result can be saved by typing:

	    old = . + 7

    Functions can be used in expressions.  There are a great number of
    pre-defined functions.  For example, the following will calculate
    the factorial of the value of 'old':

	    fact(old)

    and the calculator prints 13763753091226345046315979581580902400000000.
    Notice that numbers can be very large. (There is a practical limit
    of several thousand digits before calculations become too slow.)

    The calculator can calculate transcendental functions, and accept and
    display numbers in real or exponential format. For example, typing:

	    config("display", 50)
	    epsilon(1e-50)
	    sin(1)

    prints "~.84147098480789650665250232163029899962256306079837".

    The calculator also knows about complex numbers, so that typing:

	    (2+3i) * (4-3i)

    prints "17+6i".

    For more information about the calc lauguage and features, try:

	    help overview

*************
* overview
*************

		    CALC - An arbitrary precision calculator.
			    by David I. Bell


    This is a calculator program with arbitrary precision arithmetic.
    All numbers are represented as fractions with arbitrarily large
    numerators and denominators which are always reduced to lowest terms.
    Real or exponential format numbers can be input and are converted
    to the equivalent fraction.  Hex, binary, or octal numbers can be
    input by using numbers with leading '0x', '0b' or '0' characters.
    Complex numbers can be input using a trailing 'i', as in '2+3i'.
    Strings and characters are input by using single or double quotes.

    Commands are statements in a C-like language, where each input
    line is treated as the body of a procedure.  Thus the command
    line can contain variable declarations, expressions, labels,
    conditional tests, and loops.  Assignments to any variable name
    will automatically define that name as a global variable.  The
    other important thing to know is that all non-assignment expressions
    which are evaluated are automatically printed.  Thus, you can evaluate
    an expression's value by simply typing it in.

    Many useful built-in mathematical functions are available.  Use
    the 'show builtins' command to list them.  You can also define
    your own functions by using the 'define' keyword, followed by a
    function declaration very similar to C.  Functions which only
    need to return a simple expression can be defined using an
    equals sign, as in the example 'define sc(a,b) = a^3 + b^3'.
    Variables in functions can be defined as either 'global', 'local',
    or 'static'.  Global variables are common to all functions and the
    command line, whereas local variables are unique to each function
    level, and are destroyed when the function returns.  Static variables
    are scoped within single input files, or within functions, and are
    never destroyed.  Variables are not typed at definition time, but
    dynamically change as they are used.  So you must supply the correct
    type of variable to those functions and operators which only work
    for a subset of types.

    Calc has a help command that will produce information about
    every builtin function, command as well as a number of other
    aspects of calc usage.  Try the command:

	    help help

    for and overview of the help system.  The command:

	    help builtins

    provides information on built-in mathematical functions, whereas:

	    help asinh

    will provides information a specific function.  The following
    help files:

	    help command
	    help define
	    help operator
	    help statement
	    help variable

    provide a good overview of the calc language.  If you are familiar
    with C, you should also try:

	    help unexpected

    It contains information about differences between C and calc
    that may surprize you.

    A full and extensive overview of calc may be obtained by:

	    help full

    By default, arguments to functions are passed by value (even
    matrices).  For speed, you can put an ampersand before any
    variable argument in a function call, and that variable will be
    passed by reference instead.  However, if the function changes
    its argument, the variable will change.  Arguments to built-in
    functions and object manipulation functions are always called
    by reference.  If a user-defined function takes more arguments
    than are passed, the undefined arguments have the null value.
    The 'param' function returns function arguments by argument
    number, and also returns the number of arguments passed.  Thus
    functions can be written to handle an arbitrary number of
    arguments.

    The mat statement is used to create a matrix.  It takes a
    variable name, followed by the bounds of the matrix in square
    brackets.  The lower bounds are zero by default, but colons can
    be used to change them.  For example 'mat foo[3, 1:10]' defines
    a two dimensional matrix, with the first index ranging from 0
    to 3, and the second index ranging from 1 to 10.  The bounds of
    a matrix can be an expression calculated at runtime.

    Lists of values are created using the 'list' function, and values can
    be inserted or removed from either the front or the end of the list.
    List elements can be indexed directly using double square brackets.

    The obj statement is used to create an object.  Objects are
    user-defined values for which user-defined routines are
    implicitly called to perform simple actions such as add,
    multiply, compare, and print. Objects types are defined as in
    the example 'obj complex {real, imag}', where 'complex' is the
    name of the object type, and 'real' and 'imag' are element
    names used to define the value of the object (very much like
    structures).  Variables of an object type are created as in the
    example 'obj complex x,y', where 'x' and 'y' are variables.
    The elements of an object are referenced using a dot, as in the
    example 'x.real'. All user-defined routines have names composed
    of the object type and the action to perform separated by an
    underscore, as in the example 'complex_add'.  The command 'show
    objfuncs' lists all the definable routines.  Object routines
    which accept two arguments should be prepared to handle cases
    in which either one of the arguments is not of the expected
    object type.

    These are the differences between the normal C operators and
    the ones defined by the calculator.  The '/' operator divides
    fractions, so that '7 / 2' evaluates to 7/2. The '//' operator
    is an integer divide, so that '7 // 2' evaluates to 3.  The '^'
    operator is a integral power function, so that 3^4 evaluates to
    81.  Matrices of any dimension can be treated as a zero based
    linear array using double square brackets, as in 'foo[[3]]'.
    Matrices can be indexed by using commas between the indices, as
    in foo[3,4].  Object and list elements can be referenced by
    using double square brackets.

    The print statement is used to print values of expressions.
    Separating values by a comma puts one space between the output
    values, whereas separating values by a colon concatenates the
    output values.  A trailing colon suppresses printing of the end
    of line.  An example of printing is 'print \"The square of\",
    x, \"is\", x^2\'.

    The 'config' function is used to modify certain parameters that
    affect calculations or the display of values.  For example, the
    output display mode can be set using 'config(\"mode\", type)',
    where 'type' is one of 'frac', 'int', 'real', 'exp', 'hex',
    'oct', or 'bin'.  The default output mode is real.  For the
    integer, real, or exponential formats, a leading '~' indicates
    that the number was truncated to the number of decimal places
    specified by the default precision.  If the '~' does not
    appear, then the displayed number is the exact value.

    The number of decimal places printed is set by using
    'config(\"display\", n)'.  The default precision for
    real-valued functions can be set by using 'epsilon(x)', where x
    is the required precision (such as 1e-50).

    There is a command stack feature so that you can easily
    re-execute previous commands and expressions from the terminal.
    You can also edit the current command before it is completed.
    Both of these features use emacs-like commands.

    Files can be read in by using the 'read filename' command.
    These can contain both functions to be defined, and expressions
    to be calculated.  Global variables which are numbers can be
    saved to a file by using the 'write filename' command.

    XXX - update this file and add in new major features

*************
* help
*************

For more information while running calc, type  help  followed by one of the
following topics:

    topic		description
    -----		-----------
    intro		introduction to calc
    overview		overview of calc
    help		this file

    assoc		using associations
    builtin		builtin functions
    command		top level commands
    config		configuration parameters
    custom		information about the custom builtin interface
    define		how to define functions
    environment		how environment variables effect calc
    errorcodes		calc generated error codes
    expression		expression sequences
    file		using files
    history		command history
    interrupt		how interrupts are handled
    list		using lists
    mat			using matrices
    obj			user defined data types
    operator		math, relational, logic and variable access operators
    statement		flow control and declaration statements
    stdlib		description of some lib files shipped with calc
    types		builtin data types
    unexpected		unexpected syntax/usage surprises for C programmers
    usage		how to invoke the calc command
    variable		variables and variable declarations

    altbind		alternative input & history character bindings
    bindings		input & history character bindings
    custom_cal		information about custom calc library files
    libcalc		using the arbitrary precision routines in a C program
    new_custom		information about how to add new custom functions
    stdlib		standard calc library files and standards

    archive		where to get the latest versions of calc
    bugs		known bugs and mis-features
    changes		recent changes to calc
    contrib		how to contribute scripts, code or custom functions
    credit		who wrote calc and who helped
    todo		needed enhancements and wish list

    full		all of the above (in the above order)

You can also ask for help on a particular function name.  For example,

    help asinh
    help round

or on a particular symbol such as:

    help =

For example:

    help usage

will print the calc command usage information.  One can obtain calc help
without invoking any startup code by running calc as follows:

    calc -q help topic

where 'topic' is one of the topics listed above.

If the -m mode disallows opening files for reading or execution of programs,
then the help facility will be disabled.  See:

    help usage

for details of the -m mode.

The help command is able to display installed help files for custom builtin
functions.  However, if the custom name is the same as a standard help
file, the standard help file will be displayed instead.  The custom help
builtin should be used to directly access the custom help file.

For example, the custom help builtin has the same name as the standard
help file.  That is:

    help help

will print this file only.  However the custom help builtin will print
only the custom builtin help file:

    custom("help", "help");

will by-pass a standard help file and look for the custom version directly.

As a hack, the following:

     help custhelp/anything

as the same effect as:

    custom("help", "anything");

*************
* assoc
*************

NAME
    assoc - create a new association array

SYNOPSIS
    assoc()

TYPES
    return	association

DESCRIPTION
    This function returns an empty association array.

    After A = assoc(), elements can be added to the association by
    assignments of the forms

	A[a_1] = v_1
        A[a_1, a_2] = v_2
	A[a_1, a_2, a_3] = v_3
	A[a_1, a_2, a_3, a_4] = v_4

    There are no restrictions on the values of the "indices" a_i or
    the "values" v_i.

    After the above assignments, so long as no new values have been
    assigned to A[a_i], etc., the expressions A[a_1], A[a_1, a_2], etc.
    will return the values v_1, v_2, ...

    Until A[a_1], A[a_1, a_2], ... are defined as described above, these
    expressions return the null value.

    Thus associations act like matrices except that different elements
    may have different numbers (between 1 and 4 inclusive) of indices,
    and these indices need not be integers in specified ranges.

    Assignments of a null value
    to an element of an association does not delete the element, but
    a later reference to that element will return the null value as if
    the element is undefined.

    The elements of an association are stored in a hash table for
    quick access.  The index values are hashed to select the correct
    hash chain for a small sequential search for the element.  The hash
    table will be resized as necessary as the number of entries in
    the association becomes larger.

    The size function returns the number of elements in an association.
    This size will include elements with null values.

    Double bracket indexing can be used for associations to walk through
    the elements of the association.  The order that the elements are
    returned in as the index increases is essentially random.  Any
    change made to the association can reorder the elements, this making
    a sequential scan through the elements difficult.

    The search and rsearch functions can search for an element in an
    association which has the specified value.  They return the index
    of the found element, or a NULL value if the value was not found.

    Associations can be copied by an assignment, and can be compared
    for equality.  But no other operations on associations have meaning,
    and are illegal.

EXAMPLE
    > A = assoc(); print A
     assoc (0 elements):

    > A["zero"] = 0; A["one"] = 1; A["two"] = 2; A["three"] = 3;
    > A["smallest", "prime"] = 2;
    > print A
    assoc (5 elements);
    ["two"] = 2
    ["three"] = 3
    ["one"] = 1
    ["zero"] = 0
    ["smallest","prime"] = 2

LIMITS
    none

LIBRARY
    none

SEE ALSO
    isassoc, rsearch, search, size

*************
* builtin
*************

Builtin functions

	There is a large number of built-in functions.  Many of the
	functions work on several types of arguments, whereas some only
	work for the correct types (e.g., numbers or strings).  In the
	following description, this is indicated by whether or not the
	description refers to values or numbers.  This display is generated
	by the 'show builtin' command.


	Name	Args	Description

	abs       1-2   absolute value within accuracy b
	access    1-2   determine accessibility of file a for mode b
	acos      1-2   arccosine of a within accuracy b
	acosh     1-2   inverse hyperbolic cosine of a within accuracy b
	acot      1-2   arccotangent of a within accuracy b
	acoth     1-2   inverse hyperbolic cotangent of a within accuracy b
	acsc      1-2   arccosecant of a within accuracy b
	acsch     1-2   inverse csch of a within accuracy b
	agd       1-2   inverse gudermannian function
	append    1+    append values to end of list
	appr      1-3   approximate a by multiple of b using rounding c
	arg       1-2   argument (the angle) of complex number
	asec      1-2   arcsecant of a within accuracy b
	asech     1-2   inverse hyperbolic secant of a within accuracy b
	asin      1-2   arcsine of a within accuracy b
	asinh     1-2   inverse hyperbolic sine of a within accuracy b
	assoc     0     create new association array
	atan      1-2   arctangent of a within accuracy b
	atan2     2-3   angle to point (b,a) within accuracy c
	atanh     1-2   inverse hyperbolic tangent of a within accuracy b
	avg       0+    arithmetic mean of values
	base      0-1   set default output base
	bit       2     whether bit b in value a is set
	blk       0-3   block with or without name, octet number, chunksize
	blkcpy    2-5   copy value to/from a block: blkcpy(d,s,len,di,si)
	blkfree   1     free all storage from a named block
	blocks    0-1   named block with specified index, or null value
	bround    1-3   round value a to b number of binary places
	btrunc    1-2   truncate a to b number of binary places
	ceil      1     smallest integer greater than or equal to number
	cfappr    1-3   approximate a within accuracy b using
			    continued fractions
	cfsim     1-2   simplify number using continued fractions
	char      1     character corresponding to integer value
	cmdbuf    0     command buffer
	cmp       2     compare values returning -1, 0, or 1
	comb      2     combinatorial number a!/b!(a-b)!
	config    1-2   set or read configuration value
	conj      1     complex conjugate of value
	copy      2-5   copy value to/from a block: copy(s,d,len,si,di)
	cos       1-2   cosine of value a within accuracy b
	cosh      1-2   hyperbolic cosine of a within accuracy b
	cot       1-2   cotangent of a within accuracy b
	coth      1-2   hyperbolic cotangent of a within accuracy b
	count     2     count listr/matrix elements satisfying some condition
	cp        2     cross product of two vectors
	csc       1-2   cosecant of a within accuracy b
	csch      1-2   hyperbolic cosecant of a within accuracy b
	ctime     0     date and time as string
	custom    0+    custom builtin function interface
	delete    2     delete element from list a at position b
	den       1     denominator of fraction
	det       1     determinant of matrix
	digit     2     digit at specified decimal place of number
	digits    1     number of digits in number
	dp        2     dot product of two vectors
	epsilon   0-1   set or read allowed error for real calculations
	errcount  0-1   set or read error count
	errmax    0-1   set or read maximum for error count
	errno     0-1   set or read calc_errno
	error     0-1   generate error value
	eval      1     evaluate expression from string to value
	exp       1-2   exponential of value a within accuracy b
	factor    1-3   lowest prime factor < b of a, return c if error
	fcnt      2     count of times one number divides another
	fib       1     Fibonacci number F(n)
	forall    2     do function for all elements of list or matrix
	frem      2     number with all occurrences of factor removed
	fact      1     factorial
	fclose    0+    close file
	feof      1     whether EOF reached for file
	ferror    1     whether error occurred for file
	fflush    0+    flush output to file(s)
	fgetc     1     read next char from file
	fgetfield 1     read next white-space delimited field from file
	fgetline  1     read next line from file, newline removed
	fgets     1     read next line from file, newline is kept
	fgetstr   1     read next null-terminated string from file, null character is kept
	files     0-1   return opened file or max number of opened files
	floor     1     greatest integer less than or equal to number
	fopen     2     open file name a in mode b
	fprintf   2+    print formatted output to opened file
	fputc     2     write a character to a file
	fputs     2+    write one or more strings to a file
	fputstr   2+    write one or more null-terminated strings to a file
	free      0+    free listed or all global variables
	freeglobals 0     free all global and visible static variables
	freeredc  0     free redc data cache
	freestatics 0     free all unscoped static variables
	freopen   2-3   reopen a file stream to a named file
	fscan     2+    scan a file for assignments to one or more variables
	fscanf    2+    formatted scan of a file for assignment to one or more variables
	fseek     2-3   seek to position b (offset from c) in file a
	fsize     1     return the size of the file
	ftell     1     return the file position
	frac      1     fractional part of value
	gcd       1+    greatest common divisor
	gcdrem    2     a divided repeatedly by gcd with b
	gd        1-2   gudermannian function
	getenv    1     value of environment variable (or NULL)
	hash      1+    return non-negative hash value for one or
			    more values
	head      2     return list of specified number at head of a list
	highbit   1     high bit number in base 2 representation
	hmean     0+    harmonic mean of values
	hnrmod    4     v mod h*2^n+r, h>0, n>0, r = -1, 0 or 1
	hypot     2-3   hypotenuse of right triangle within accuracy c
	ilog      2     integral log of one number with another
	ilog10    1     integral log of a number base 10
	ilog2     1     integral log of a number base 2
	im        1     imaginary part of complex number
	insert    2+    insert values c ... into list a at position b
	int       1     integer part of value
	inverse   1     multiplicative inverse of value
	iroot     2     integer b'th root of a
	isassoc   1     whether a value is an association
	isatty    1     whether a file is a tty
	isblk     1     whether a value is a block
	isconfig  1     whether a value is a config state
	isdefined 1     whether a string names a function
	iserror   1     where a value is an error
	iseven    1     whether a value is an even integer
	isfile    1     whether a value is a file
	ishash    1     whether a value is a hash state
	isident   1     returns 1 if identity matrix
	isint     1     whether a value is an integer
	islist    1     whether a value is a list
	ismat     1     whether a value is a matrix
	ismult    2     whether a is a multiple of b
	isnull    1     whether a value is the null value
	isnum     1     whether a value is a number
	isobj     1     whether a value is an object
	isobjtype 1     whether a string names an object type
	isodd     1     whether a value is an odd integer
	isoctet   1     whether a value is an octet
	isprime   1-2   whether a is a small prime, return b if error
	isptr     1     whether a value is a pointer
	isqrt     1     integer part of square root
	isrand    1     whether a value is a additive 55 state
	israndom  1     whether a value is a Blum state
	isreal    1     whether a value is a real number
	isrel     2     whether two numbers are relatively prime
	isstr     1     whether a value is a string
	issimple  1     whether value is a simple type
	issq      1     whether or not number is a square
	istype    2     whether the type of a is same as the type of b
	jacobi    2     -1 => a is not quadratic residue mod b
			    1 => b is composite, or a is quad residue of b
	join      1+    join one or more lists into one list
	lcm       1+    least common multiple
	lcmfact   1     lcm of all integers up till number
	lfactor   2     lowest prime factor of a in first b primes
	links     1     links to number or string value
	list      0+    create list of specified values
	ln        1-2   natural logarithm of value a within accuracy b
	lowbit    1     low bit number in base 2 representation
	ltol      1-2   leg-to-leg of unit right triangle (sqrt(1 - a^2))
	makelist  1     create a list with a null elements
	matdim    1     number of dimensions of matrix
	matfill   2-3   fill matrix with value b (value c on diagonal)
	matmax    2     maximum index of matrix a dim b
	matmin    2     minimum index of matrix a dim b
	matsum    1     sum the numeric values in a matrix
	mattrace  1     return the trace of a square matrix
	mattrans  1     transpose of matrix
	max       0+    maximum value
	md5       0+    MD5 Hash Algorithm
	memsize   1     number of octets used by the value, including overhead
	meq       3     whether a and b are equal modulo c
	min       0+    minimum value
	minv      2     inverse of a modulo b
	mmin      2     a mod b value with smallest abs value
	mne       3     whether a and b are not equal modulo c
	mod       2-3   residue of a modulo b, rounding type c
	modify    2     modify elements of a list or matrix
	name      1     name assigned to block or file
	near      2-3   sign of (abs(a-b) - c)
	newerror  0-1   create new error type with message a
	nextcand  1-5   smallest value == d mod e > a, ptest(a,b,c) true
	nextprime 1-2   return next small prime, return b if err
	norm      1     norm of a value (square of absolute value)
	null      0+    null value
	num       1     numerator of fraction
	ord       1     integer corresponding to character value
	param     1     value of parameter n (or parameter count if n
			    is zero)
	perm      2     permutation number a!/(a-b)!
	prevcand  1-5   largest value == d mod e < a, ptest(a,b,c) true
	prevprime 1-2   return previous small prime, return b if err
	pfact     1     product of primes up till number
	pi        0-1   value of pi accurate to within epsilon
	pix       1-2   number of primes <= a < 2^32, return b if error
	places    1     places after decimal point (-1 if infinite)
	pmod      3     mod of a power (a ^ b (mod c))
	polar     2-3   complex value of polar coordinate (a * exp(b*1i))
	poly      1+    evaluates a polynomial given its coefficients or coefficient-list
	pop       1     pop value from front of list
	popcnt    1-2   number of bits in a that match b (or 1)
	power     2-3   value a raised to the power b within accuracy c
	protect   1-2   read or set protection level for variable
	ptest     1-3   probabilistic primality test
	printf    1+    print formatted output to stdout
	prompt    1     prompt for input line using value a
	push      1+    push values onto front of list
	putenv    1-2   define an environment variable
	quo       2-3   integer quotient of a by b, rounding type c
	quomod    4     set c and d to quotient and remainder of a
			    divided by b
	rand      0-2   additive 55 random number [0,2^64), [0,a), or [a,b)
	randbit   0-1   additive 55 random number [0,2^a)
	random    0-2   Blum-Blum-Shub random number [0,2^64), [0,a), or [a,b)
	randombit 0-1   Blum-Blum-Sub random number [0,2^a)
	randperm  1     random permutation of a list or matrix
	rcin      2     convert normal number a to REDC number mod b
	rcmul     3     multiply REDC numbers a and b mod c
	rcout     2     convert REDC number a mod b to normal number
	rcpow     3     raise REDC number a to power b mod c
	rcsq      2     square REDC number a mod b
	re        1     real part of complex number
	remove    1     remove value from end of list
	reverse   1     reverse a copy of a matrix or list
	rewind    0+    rewind file(s)
	rm        1+    remove file(s), -f turns off no-such-file errors
	root      2-3   value a taken to the b'th root within accuracy c
	round     1-3   round value a to b number of decimal places
	rsearch   2-4   reverse search matrix or list for value b
			    starting at index c
	runtime   0     user mode cpu time in seconds
	saveval   1     set flag for saving values
	scale     2     scale value up or down by a power of two
	scan      1+    scan standard input for assignment to one or more variables
	scanf     2+    formatted scan of standard input for assignment to variables
	search    2-4   search matrix or list for value b starting
			    at index c
	sec       1-2   sec of a within accuracy b
	sech      1-2   hyperbolic secant of a within accuracy b
	segment   2-3   specified segment of specified list
	select    2     form sublist of selected elements from list
	setbit    2-3   set specified bit in string
	sgn       1     sign of value (-1, 0, 1)
	sha       0+    old Secure Hash Algorithm (SHS FIPS Pub 180)
	sha1      0+    Secure Hash Algorithm (SHS-1 FIPS Pub 180-1)
	sin       1-2   sine of value a within accuracy b
	sinh      1-2   hyperbolic sine of a within accuracy b
	size      1     total number of elements in value
	sizeof    1     number of octets used to hold the value
	sort      1     sort a copy of a matrix or list
	sqrt      1-3   square root of value a within accuracy b
	srand     0-1   seed the rand() function
	srandom   0-4   seed the random() function
	ssq       1+    sum of squares of values
	str       1     simple value converted to string
	strcat    1+    concatenate strings together
	strcmp    2     compare two null-terminated strings
	strcpy    2     copy null-terminated string to string
	strerror  0-1   string describing error type
	strlen    1     length of string
	strncmp   3     compare strings a, b to c characters
	strncpy   3     copy up to c characters from string to string
	strpos    2     index of first occurrence of b in a
	strprintf 1+    return formatted output as a string
	strscan   2+    scan a string for assignments to one or more variables
	strscanf  2+    formatted scan of string for assignments to variables
	substr    3     substring of a from position b for c chars
	sum       0+    sum of list or object sums and/or other terms
	swap      2     swap values of variables a and b (can be dangerous)
	system    1     call Unix command
	tail      2     retain list of specified number at tail of list
	tan       1-2   tangent of a within accuracy b
	tanh      1-2   hyperbolic tangent of a within accuracy b
	test      1     test that value is nonzero
	time      0     number of seconds since 00:00:00 1 Jan 1970 UTC
	trunc     1-2   truncate a to b number of decimal places
	ungetc    2     unget char read from file
	xor       1+    logical xor


	The config function sets or reads the value of a configuration
	parameter.  The first argument is a string which names the parameter
	to be set or read.  If only one argument is given, then the current
	value of the named parameter is returned.  If two arguments are given,
	then the named parameter is set to the value of the second argument,
	and the old value of the parameter is returned.  Therefore you can
	change a parameter and restore its old value later.  The possible
	parameters are explained in the next section.

	The scale function multiplies or divides a number by a power of 2.
	This is used for fractional calculations, unlike the << and >>
	operators, which are only defined for integers.  For example,
	scale(6, -3) is 3/4.

	The quomod function is used to obtain both the quotient and remainder
	of a division in one operation.  The first two arguments a and b are
	the numbers to be divided.  The last two arguments c and d are two
	variables which will be assigned the quotient and remainder.  For
	nonnegative arguments, the results are equivalent to computing a//b
	and a%b.  If a is negative and the remainder is nonzero, then the
	quotient will be one less than a//b.  This makes the following three
	properties always hold:  The quotient c is always an integer.  The
	remainder d is always 0 <= d < b.  The equation a = b * c + d always
	holds.  This function returns 0 if there is no remainder, and 1 if
	there is a remainder.  For examples, quomod(10, 3, x, y) sets x to 3,
	y to 1, and returns the value 1, and quomod(-4, 3.14159, x, y) sets x
	to -2, y to 2.28318, and returns the value 1.

	The eval function accepts a string argument and evaluates the
	expression represented by the string and returns its value.
	The expression can include function calls and variable references.
	For example, eval("fact(3) + 7") returns 13.  When combined with
	the prompt function, this allows the calculator to read values from
	the user.  For example, x=eval(prompt("Number: ")) sets x to the
	value input by the user.

	The digit and bit functions return individual digits of a number,
	either in base 10 or in base 2, where the lowest digit of a number
	is at digit position 0.  For example, digit(5678, 3) is 5, and
	bit(0b1000100, 2) is 1.  Negative digit positions indicate places
	to the right of the decimal or binary point, so that for example,
	digit(3.456, -1) is 4.

	The ptest builtin is a primality testing function.  The
	1st argument is the suspected prime to be tested.  The
	absolute value of the 2nd argument is an iteration count.

	If ptest is called with only 2 args, the 3rd argument is
	assumed to be 0.  If ptest is called with only 1 arg, the
	2nd argument is assumed to be 1.  Thus, the following
	calls are equivalent:

		ptest(a)
		ptest(a,1)
		ptest(a,1,0)

	Normally ptest performs a some checks to determine if the
	value is divisable by some trivial prime.  If the 2nd
	argument is < 0, then the trivial check is omitted.

	For example, ptest(a,10) performs the same work as:

		ptest(a,-3)	(7 tests without trivial check)
		ptest(a,-7,3)	(3 more tests without the trivial check)

	The ptest function returns 0 if the number is definitely not
	prime, and 1 is the number is probably prime.  The chance
	of a number which is probably prime being actually composite
	is less than 1/4 raised to the power of the iteration count.
	For example, for a random number p, ptest(p, 10) incorrectly
	returns 1 less than once in every million numbers, and you
	will probably never find a number where ptest(p, 20) gives
	the wrong answer.

	The first 3 args of nextcand and prevcand functions are the same
	arguments as ptest.  But unlike ptest, nextcand and prevcand return
	the next and previous values for which ptest is true.

	For example, nextcand(2^1000) returns 2^1000+297 because
	2^1000+297 is the smallest value x > 2^1000 for which
	ptest(x,1) is true.  And for example, prevcand(2^31-1,10,5)
	returns 2147483629 (2^31-19) because 2^31-19 is the largest
	value y < 2^31-1 for which ptest(y,10,5) is true.

	The nextcand and prevcand functions also have a 5 argument form:

		nextcand(num, count, skip, modval, modulus)
		prevcand(num, count, skip, modval, modulus)

	return the smallest (or largest) value ans > num (or < num) that
	is also == modval % modulus for which ptest(ans,count,skip) is true.

	The builtins nextprime(x) and prevprime(x) return the
	next and previous primes with respect to x respectively.
	As of this release, x must be < 2^32.  With one argument, they
	will return an error if x is out of range.  With two arguments,
	they will not generate an error but instead will return y.

	The builtin function pix(x) returns the number of primes <= x.
	As of this release, x must be < 2^32.  With one argument, pix(x)
	will return an error if x is out of range.  With two arguments,
	pix(x,y) will not generate an error but instead will return y.

	The builtin function factor may be used to search for the
	smallest factor of a given number.  The call factor(x,y)
	will attempt to find the smallest factor of x < min(x,y).
	As of this release, y must be < 2^32.  If y is omitted, y
	is assumed to be 2^32-1.

	If x < 0, factor(x,y) will return -1.  If no factor <
	min(x,y) is found, factor(x,y) will return 1.  In all other
	cases, factor(x,y) will return the smallest prime factor
	of x.  Note except for the case when abs(x) == 1, factor(x,y)
	will not return x.

	If factor is called with y that is too large, or if x or y
	is not an integer, calc will report an error.  If a 3rd argument
	is given, factor will return that value instead.  For example,
	factor(1/2,b,c) will return c instead of issuing an error.

	The builtin lfactor(x,y) searches a number of primes instead
	of below a limit.  As of this release, y must be <= 203280221
	(y <= pix(2^32-1)).  In all other cases, lfactor is operates
	in the same way as factor.

	If lfactor is called with y that is too large, or if x or y
	is not an integer, calc will report an error.  If a 3rd argument
	is given, lfactor will return that value instead.  For example,
	lfactor(1/2,b,c) will return c instead of issuing an error.

	The lfactor function is slower than factor.  If possible factor
	should be used instead of lfactor.

	The builtin isprime(x) will attempt to determine if x is prime.
	As of this release, x must be < 2^32.  With one argument, isprime(x)
	will return an error if x is out of range.  With two arguments,
	isprime(x,y) will not generate an error but instead will return y.

	The functions rcin, rcmul, rcout, rcpow, and rcsq are used to
	perform modular arithmetic calculations for large odd numbers
	faster than the usual methods.  To do this, you first use the
	rcin function to convert all input values into numbers which are
	in a format called REDC format.  Then you use rcmul, rcsq, and
	rcpow to multiply such numbers together to produce results also
	in REDC format.  Finally, you use rcout to convert a number in
	REDC format back to a normal number.  The addition, subtraction,
	negation, and equality comparison between REDC numbers are done
	using the normal modular methods.  For example, to calculate the
	value 13 * 17 + 1 (mod 11), you could use:

		p = 11;
		t1 = rcin(13, p);
		t2 = rcin(17, p);
		t3 = rcin(1, p);
		t4 = rcmul(t1, t2, p);
		t5 = (t4 + t3) % p;
		answer = rcout(t5, p);

	The swap function exchanges the values of two variables without
	performing copies.  For example, after:

		x = 17;
		y = 19;
		swap(x, y);

	then x is 19 and y is 17.  This function should not be used to
	swap a value which is contained within another one.  If this is
	done, then some memory will be lost.  For example, the following
	should not be done:

		mat x[5];
		swap(x, x[0]);

	The hash function returns a relatively small non-negative integer
	for one or more input values.  The hash values should not be used
	across runs of the calculator, since the algorithms used to generate
	the hash value may change with different versions of the calculator.

	The base function allows one to specify how numbers should be
	printer.  The base function provides a numeric shorthand to the
	config("mode") interface.  With no args, base() will return the
	current mode.  With 1 arg, base(val) will set the mode according to
	the arg and return the previous mode.

	The following convention is used to declare modes:

		 base    config
		value    string

		   2	"binary"	binary fractions
		   8	"octal"		octal fractions
		  10	"real"		decimal floating point
		  16	"hex"		hexadecimal fractions
		 -10	"int"		decimal integer
		 1/3	"frac"		decimal fractions
		1e20	"exp"		decimal exponential

	For convenience, any non-integer value is assumed to mean "frac",
	and any integer >= 2^64 is assumed to mean "exp".

*************
* command
*************

Command sequence

    This is a sequence of any the following command formats, where
    each command is terminated by a semicolon or newline.  Long command
    lines can be extended by using a back-slash followed by a newline
    character.  When this is done, the prompt shows a double angle
    bracket to indicate that the line is still in progress.  Certain
    cases will automatically prompt for more input in a similar manner,
    even without the back-slash.  The most common case for this is when
    a function is being defined, but is not yet completed.

    Each command sequence terminates only on an end of file.  In
    addition, commands can consist of expression sequences, which are
    described in the next section.


    NOTE: Calc commands are in lower case.   UPPER case is used below
	  for emphasis only, and should be considered in lower case.


    DEFINE function(params) { body }
    DEFINE function(params) = expression
	    This first form defines a full function which can consist
	    of declarations followed by many statements which implement
	    the function.

	    The second form defines a simple function which calculates
	    the specified expression value from the specified parameters.
	    The expression cannot be a statement.  However, the comma
	    and question mark operators can be useful.  Examples of
	    simple functions are:

		    define sumcubes(a, b) = a^3 + b^3;
		    define pimod(a) = a % pi();

    HELP
	    This displays a general help message.

    READ filename
	    This reads definitions from the specified filename.
	    The name can be quoted if desired.  The calculator
	    uses the CALCPATH environment variable to search
	    through the specified directories for the filename,
	    similarly to the use of the PATH environment variable.
	    If CALCPATH is not defined, then a default path which is
	    usually ":/usr/local/lib/calc" is used (that is, the current
	    directory followed by a general calc library directory).
	    The ".cal" extension is defaulted for input files, so
	    that if "filename" is not found, then "filename.cal" is
	    then searched for.  The contents of the filename are
	    command sequences which can consist of expressions to
	    evaluate or functions to define, just like at the top
	    level command level.

	    If the -m mode disallows opening of files for reading,
	    this command will be disabled.

    READ -once filename
	    This command acts like the regular READ expect that it
	    will ignore filename if is has been previously read.

	    This command is particularly useful in a library that
	    needs to read a 2nd library.  By using the READ -once
	    command, one will not reread that 2nd library, nor will
	    once risk entering into a infinite READ loop (where
	    that 2nd library directly or indirectly does a READ of
	    the first library).

	    If the -m mode disallows opening of files for reading,
	    this command will be disabled.

    WRITE filename
	    This writes the values of all global variables to the
	    specified filename, in such a way that the file can be
	    later read in order to recreate the variable values.
	    For speed reasons, values are written as hex fractions.
	    This command currently only saves simple types, so that
	    matrices, lists, and objects are not saved.  Function
	    definitions are also not saved.

	    If the -m mode disallows opening of files for writing,
	    this command will be disabled.

    QUIT
	    This leaves the calculator, when given as a top-level
	    command.

    CD
	    Change the current directory to the home directory, if $HOME
	    is set in the environment.

    CD dir
	    Change the current directory to dir.


    Also see the help topic:

	    statement       flow control and declaration statements
	    usage		for -m modes

*************
* config
*************

Configuration parameters

    Configuration parameters affect how the calculator performs certain
    operations.  Among features that are controlled by these parameters
    are the accuracy of some calculations, the displayed format of results,
    the choice from possible alternative algorithms, and whether or not
    debugging information is displayed.  The parameters are
    read or set using the "config" built-in function; they remain in effect
    until their values are changed by a config or equivalent instruction.
    The following parameters can be specified:

	    "all"		all configuration values listed below

	    "trace"		turns tracing features on or off
	    "display"		sets number of digits in prints.
	    "epsilon"		sets error value for transcendentals.
	    "maxprint"		sets maximum number of elements printed.
	    "mode"		sets printout mode.
	    "mul2"		sets size for alternative multiply.
	    "sq2"		sets size for alternative squaring.
	    "pow2"		sets size for alternate powering.
	    "redc2"		sets size for alternate REDC.
	    "tilde"		enable/disable printing of the roundoff '~'
	    "tab"		enable/disable printing of leading tabs
	    "quomod"		sets rounding mode for quomod
	    "quo"		sets rounding mode for //, default for quo
	    "mod"		sets "rounding" mode for %, default for mod
	    "sqrt"		sets rounding mode for sqrt
	    "appr"		sets rounding mode for appr
	    "cfappr"		sets rounding mode for cfappr
	    "cfsim"		sets rounding mode for cfsim
	    "round"		sets rounding mode for round and bround
	    "outround"		sets rounding mode for printing of numbers
	    "leadzero"		enables/disables printing of 0 as in 0.5
	    "fullzero"		enables/disables padding zeros as in .5000
	    "maxscan"		maximum number of scan errors before abort
	    "prompt"		default interactive prompt
	    "more"		default interactive multi-line input prompt
	    "blkmaxprint"	number of block octets to print, 0 means all
	    "blkverbose"	TRUE=>print all lines, FALSE=>skip duplicates
	    "blkbase"		block output base
	    "blkfmt"		block output format
	    "lib_debug"		calc library script debug level
	    "calc_debug"	internal calc debug level
	    "user_debug"	user defined debug level


    The "all" config value allows one to save/restore the configuration
    set of values.  The return of:

	    config("all")

    is a CONFIG type which may be used as the 2rd arg in a later call.
    One may save, modify and restore the configuration state as follows:

	    oldstate = config("all")
	    ...
	    config("tab", 0)
	    config("mod", 10)
	    ...
	    config("all", oldstate)

    This save/restore method is useful within functions.
    It allows functions to control their configuration without impacting
    the calling function.

    There are two configuration state aliases that may be set.  To
    set the backward compatible standard configuration:

	    config("all", "oldstd")

    The "oldstd" will restore the configuration to the default at startup.

    A new configuration that some people prefer may be set by:

	    config("all", "newstd")

    The "newstd" is not backward compatible with the historic
    configuration.  Even so, some people prefer this configuration
    and place the config("all", "newstd") command in their CALCRC
    startup files.

    When nonzero, the "trace" parameter activates one or more features
    that may be useful for debugging.  These features correspond to
    powers of 2 which contribute additively to config("trace"):

	1: opcodes are displayed as functions are evaluated

	2: disables the inclusion of debug lines in opcodes for functions
	   whose definitions are introduced with a left-brace.

	4: the number of links for real and complex numbers are displayed
	   when the numbers are printed; for real numbers "#" or for
	   complex numbers "##", followed by the number of links, are
	   printed immediately after the number.

	8: the opcodes for a new functions are displayed when the function
	   is successfully defined.

    See also lib_debug, calc_debug and user_debug below for more debug levels.

    The "display" parameter specifies the maximum number of digits after
    the decimal point to be printed in real or exponential mode in
    normal unformatted printing (print, strprint, fprint) or in
    formatted printing (printf, strprintf, fprintf) when precision is not
    specified.  The initial value is 20.  This parameter does not change
    the stored value of a number.  Where rounding is necessary, the type
    of rounding to be used is controlled by "outround".

    The "epsilon" parameter specifies the default accuracy for the
    calculation of functions for which exact values are not possible or
    not desired.  For most functions, the

	 	remainder = exact value - calculated value

    has absolute value less than epsilon, but, except when the sign of
    the remainder is controlled by an appropriate parameter, the
    absolute value of the remainder usually does not exceed epsilon/2.
    Functions which require an epsilon value accept an
    optional argument which overrides this default epsilon value for
    that single call.  (The value v can be assigned to the "epsilon"
    parameter by epsilon(v) as well as by config("epsilon", v), and the
    current value obtained by epsilon() as well as by config("epsilon").)
    For the transcendental functions and the functions sqrt() and
    appr(), the calculated value is always a multiple of epsilon.

    The "mode" parameter is a string specifying the mode for printing of
    numbers by the unformatted print functions, and the default
    ("%d" specifier) for formatted print functions.  The initial mode
    is "real".  The available modes are:

	    "frac"		decimal fractions
	    "int"		decimal integer
	    "real"		decimal floating point
	    "exp"		decimal exponential
	    "hex"		hex fractions
	    "oct"		octal fractions
	    "bin"		binary fractions

    The "maxprint" parameter specifies the maximum number of elements to
    be displayed when a matrix or list is printed.  The initial value is 16.

    Mul2 and sq2 specify the sizes of numbers at which calc switches
    from its first to its second algorithm for multiplying and squaring.
    The first algorithm is the usual method of cross multiplying, which
    runs in a time of O(N^2).  The second method is a recursive and
    complicated method which runs in a time of O(N^1.585).  The argument
    for these parameters is the number of binary words at which the
    second algorithm begins to be used.  The minimum value is 2, and
    the maximum value is very large.  If 2 is used, then the recursive
    algorithm is used all the way down to single digits, which becomes
    slow since the recursion overhead is high.  If a number such as
    1000000 is used, then the recursive algorithm is never used, causing
    calculations for large numbers to slow down.  For a typical example
    on a 386, the two algorithms are about equal in speed for a value
    of 20, which is about 100 decimal digits.  A value of zero resets
    the parameter back to its default value.  Usually there is no need
    to change these parameters.

    Pow2 specifies the sizes of numbers at which calc switches from
    its first to its second algorithm for calculating powers modulo
    another number.  The first algorithm for calculating modular powers
    is by repeated squaring and multiplying and dividing by the modulus.
    The second method uses the REDC algorithm given by Peter Montgomery
    which avoids divisions.  The argument for pow2 is the size of the
    modulus at which the second algorithm begins to be used.

    Redc2 specifies the sizes of numbers at which calc switches from
    its first to its second algorithm when using the REDC algorithm.
    The first algorithm performs a multiply and a modular reduction
    together in one loop which runs in O(N^2).  The second algorithm
    does the REDC calculation using three multiplies, and runs in
    O(N^1.585).  The argument for redc2 is the size of the modulus at
    which the second algorithm begins to be used.

    Config("tilde") controls whether or not a leading tilde ('~') is
    printed to indicate that a number has not been printed exactly
    because the number of decimal digits required would exceed the
    specified maximum number.  The initial "tilde" value is 1.

    Config ("tab") controls the printing of a tab before results
    automatically displayed when working interactively.  It does not
    affect the printing by the functions print, printf, etc.  The initial
    "tab" value is 1.

    The "quomod", "quo", "mod", "sqrt", "appr", "cfappr", "cfsim", and
    "round" control the way in which any necessary rounding occurs.
    Rounding occurs when for some reason, a calculated or displayed
    value (the "approximation") has to differ from the "true value",
    e.g. for quomod and quo, the quotient is to be an integer, for sqrt
    and appr, the approximation is to be a multiple of an explicit or
    implicit "epsilon", for round and bround (both controlled by
    config("round")) the number of decimal places or fractional bits
    in the approximation is limited.  Zero value for any of these
    parameters indicates that the true value is greater than the approximation,
    i.e. the rounding is "down", or in the case of mod, that the
    residue has the same sign as the divisor.  If bit 4 of the
    parameter is set, the rounding of to the nearest acceptable candidate
    when this is uniquely determined; in the remaining ambiguous cases,
    the type of rounding is determined by the lower bits of the parameter
    value.  If bit 3 is set, the rounding for quo, appr and sqrt,
    is to the nearest even integer or the nearest even multiple of epsilon,
    and for round to the nearest even "last decimal place".  The effects
    of the 3 lowest bits of the parameter value are as follows:

	Bit 0: Unconditional reversal (down to up, even to odd, etc.)
	Bit 1: Reversal if the exact value is negative
	Bit 2: Reversal if the divisor or epsilon is negative

    (Bit 2 is irrelevant for the functions round and bround since the
    equivalent epsilon (a power of 1/10 or 1/2) is always positive.)

    For quomod, the quotient is rounded to an integer value as if
    evaluating quo with config("quo") == config("quomod").  Similarly,
    quomod and mod give the same residues if config("mod") == config("quomod").

    For the sqrt function, if bit 5 of config("sqrt") is set, the exact
    square-root is returned when this is possible; otherwise the
    result is rounded to a multiple of epsilon as determined by the
    five lower order bits.  Bit 6 of config("sqrt") controls whether the
    principal or non-principal square-root is returned.

    For the functions cfappr and cfsim, whether the "rounding" is down
    or up, etc. is controlled by the appropriate bits of config("cfappr")
    and config("cfsim") as for quomod, quo, etc.

    The "outround" parameter determines the type of rounding to be used
    by the various kinds of printing to the output: bits 0, 1, 3 and 4
    are used in the same way as for the functions round and bround.

    The "leadzero" parameter controls whether or not a 0 is printed
    before the decimal point in non-zero fractions with absolute value
    less than 1, e.g. whether 1/2 is printed as 0.5 or .5.   The
    initial value is 0, corresponding to the printing .5.

    The "fullzero" parameter controls whether or not in decimal floating-
    point printing, the digits are padded with zeros to reach the
    number of digits specified by config("display") or by a precision
    specification in formatted printing.  The initial value for this
    parameter is 0, so that, for example, if config("display") >= 2,
    5/4 will print in "real" mode as 1.25.

    The maxscan value controls how many scan errors are allowed
    before the compiling phase of a computation is aborted.  The initial
    value of "maxscan" is 20.  Setting maxscan to 0 disables this feature.

    The default prompt when in interactive mode is "> ".  One may change
    this prompt to a more cut-and-paste friendly prompt by:

	    config("prompt", "; ")

    On windowing systems that support cut/paste of a line, one may
    cut/copy an input line and paste it directly into input.  The
    leading ';' will be ignored.

    When inside multi-line input, the more prompt is used.  One may
    change it by:

	    config("more", ";; ")

    The "blkmaxprint" config value limits the number of octets to print
    for a block.  A "blkmaxprint" of 0 means to print all octets of a
    block, regardless of size.

    The default is to print only the first 256 octets.

    The "blkverbose" determines if all lines, including duplicates
    should be printed.  If TRUE, then all lines are printed.  If false,
    duplicate lines are skipped and only a "*" is printed in a style
    similar to od.  This config value has not meaning if "blkfmt" is "str".

    The default value for "blkverbose" is FALSE: duplicate lines are
    not printed.

    The "blkbase" determines the base in which octets of a block
    are printed.  Possible values are:

	"hexadecimal"		Octets printed in 2 digit hex
	"hex"

	"octal"			Octets printed in 3 digit octal
	"oct"

	"character"		Octets printed as chars with non-printing
	"char"			    chars as \123 or \n, \t, \r

	"binary"		Octets printed as 0 or 1 chars
	"bin"

	"raw"			Octets printed as is, i.e. raw binary
	"none"

    The default "blkbase" is "hex".

    The "blkfmt" determines for format of how block are printed:

	"line"		print in lines of up to 79 chars + newline
	"lines"

	"str"		print as one long string
	"string"
	"strings"

	"od"		print in od-like format, with leading offset,
	"odstyle"	   followed by octets in the given base
	"od_style"

	"hd"		print in hex dump format, with leading offset,
	"hdstyle"	   followed by octets in the given base, followed
	"hd_style"	   by chars or '.' if no-printable or blank

    The default "blkfmt" is "hd".

    With regards to "lib_debug", "calc_debug" and "user_debug":
    higher absolute values result in more detailed debugging and
    more verbose debug messages.  The default value is 0 in which
    a very amount of debugging will be performed with nil messages.
    The -1 value is reserved for no debugging or messages.  Any
    value <-1 will perform debugging silently (presumably collecting
    data to be displayed at a later time).  Values >0 result in a
    greater degree of debugging and more verbose messages.

    The "lib_debug" is reserved by convention for calc library scripts.
    This config parameter takes the place of the lib_debug global variable.
    By convention, "lib_debug" has the following meanings:

	<-1	no debug messages are printed though some internal
		    debug actions and information may be collected

	-1	no debug messages are printed, no debug actions will be taken

	0	only usage message regarding each important object are
		    printed at the time of the read (default)

	>0	messages regarding each important object are
		    printed at the time of the read in addition
		    to other debug messages

    The "calc_debug" is reserved by convention for internal calc routines.
    The output of "calc_debug" will change from release to release.
    Generally this value is used by calc wizards and by the regress.cal
    routine (make check).  By convention, "calc_debug" has the following
    meanings:

	<-1	reserved for future use

	-1	no debug messages are printed, no debug actions will be taken

	0	very little, if any debugging is performed (and then mostly
		    in alpha test code).  The only output is as a result of
		    internal fatal errors (typically either math_error() or
		    exit() will be called). (default)

	>0	a greater degree of debugging is performed and more
		    verbose messages are printed (regress.cal uses 1).

    The "user_debug" is provided for use by users.  Calc ignores this value
    other than to set it to 0 by default (for both "oldstd" and "newstd").
    No calc code or shipped library will change this value other than
    during startup or during a config("all", xyz) call.

    The following is suggested as a convention for use of "user_debug".
    These are only suggestions: feel free to use it as you like:

	<-1	no debug messages are printed though some internal
		    debug actions and information may be collected

	-1	no debug messages are printed, no debug actions will be taken

	0	very little, if any debugging is performed.  The only output
		    are from fatal errors. (default)

	>0	a greater degree of debugging is performed and more
		    verbose messages are printed

    The following are synonyms for true:

	"on"   "yes"   "y"   "true"   "t"   "1"   any non-zero number

    The following are synonyms for false:

	"off"  "no"    "n"   "false"  "f"   "0"   the number zero (0)

    Examples of setting some parameters are:

	    config("mode", "exp");	    exponential output
	    config("display", 50);	    50 digits of output
	    epsilon(epsilon() / 8);	    3 bits more accuracy
	    config("tilde", 0)	    	    disable roundoff tilde printing
	    config("tab", "off")	    disable leading tab printing

*************
* custom
*************

NAME
    custom - custom builtin interface

SYNOPSIS
    custom([custname [, arg ...]])

TYPES
    custname	string
    arg		any

    return	any

DESCRIPTION
    This function will invoke the custom function interface.  Custom
    functions are accessed by the custname argument.  The remainder
    of the args, if any, are passed to the custom function.  The
    custom function may return any value, including null.  Calling
    custom with no args is equivalent to the command 'show custom'.

    In order to use the custom interface, two things must happen:

	1) Calc must be built to allow custom functions.  By default,
	   the master Makefile is shipped with ALLOW_CUSTOM= -DCUSTOM
	   which causes custom functions to be compiled in.

	2) Calc must be invoked with an argument of -C as in:

		calc -C

    In other words, explicit action must be taken in order to
    enable the use of custom functions.  By default (no -C arg)
    custom functions are compiled in but disabled so that only
    portable calc scripts may be used.

    The main focus for calc is to provide a portable platform for
    multi-precision calculations in a C-like environment.  You should
    consider implementing algorithms in the calc language as a first
    choice.  Sometimes an algorithm requires use of special hardware, a
    non-portable OS or pre-compiled C library.  In these cases a custom
    interface may be needed.

    The custom function interface is intended to make is easy for
    programmers to add functionality that would be otherwise
    un-suitable for general distribution.  Functions that are
    non-portable (machine, hardware or OS dependent) or highly
    specialized are possible candidates for custom functions.

    To add a new custom function requires access to calc source.
    For information on how to add a new custom function, try:

	    help new_custom

    To serve as examples, calc is shipped with a few custom functions.
    If calc if invoked with -C, then either of the following will
    display information about the custom functions that are available:

	    show custom
    or:

	    custom()

    A few library script that uses these function are also provided
    to serve as usage examples.

    We welcome submissions for new custom functions.  For information
    on how to submit new custom functions for general distribution, see:

	    help contrib

EXAMPLE
    If calc compiled with ALLOW_CUSTOM= (custom disabled):

    > print custom("sysinfo", "baseb")
	    Calc was built with custom functions disabled
    Error 10195

    If calc compiled with ALLOW_CUSTOM= -DCUSTOM and is invoked without -C:

    > print custom("sysinfo", "baseb")
	    Calc must be run with a -C argument to use custom function
    Error 10194

    If calc compiled with ALLOW_CUSTOM= -DCUSTOM and is invoked with -C:

    > print custom("sysinfo", "baseb")
    32

LIMITS
    By default, custom is limited to 100 args.

LIBRARY
    none

SEE ALSO
    custom_cal, new_custom, contrib

*************
* define
*************

Function definitions

    Function definitions are introduced by the 'define' keyword.
    Other than this, the basic structure of an ordinary definition
    is like in that in C: parameters are specified for the function
    within parenthesis, the function body is introduced by a left brace,
    variables may declared for the function, statements implementing the
    function may follow, any value to be returned by the function is specified
    by a return statement, and the function definition is ended with a
    right brace.

    There are some subtle differences, however.  The types of parameters
    and variables are not defined at compile time, and may vary during
    execution and be different in different calls to the function.  For
    example, a two-argument function add may be defined by

		define add(a,b) {
			return a + b;
		}

    and be called with integer, fractional, or complex number values for a
    and b, or, under some compatibility conditions, matrices or objects.
    Any variable, not already defined as global, used in a definition has
    to be declared as local, global or static, and retains this character
    until its scope is terminated by the end of the definition, the end of
    the file being read or some other condition (see help variable for
    details).

    For example, the following function computes the factorial of n, where
    we may suppose it is to be called only with positive integral values
    for n:

	    define factorial(n)
	    {
		    local	ans;

		    ans = 1;
		    while (n > 1)
			    ans *= n--;
		    return ans;
	    }

    (In calc, this definition is unncessary since there is a built-in
    function fact(n), also expressible as n!, which returns the factorial
    of n.)

    Any functions used in the body of the definition need not have already
    been defined; it is sufficient that they have been defined when they are
    encountered during evaluation when the function is called.

    If a function definition is sufficiently simple and does not require
    local or static variables, it may be defined in shortened manner by
    using an equals sign following by an expression involving some or all
    of the parameters and already existing global variables.

    In this case, the definition is terminated by a newline character
    (which may be preceded by a semicolon), and the value the function
    returns when called will be determined by the specified expression.
    Loops and "if" statements are not allowed (but ? : expressions and the
    logical operators ||, && and !  are permitted).  As an example, the
    average of two numbers could be defined as:

	    define average(a, b) = (a + b) / 2;

    (Again, this function is not necessary, as the same result is
    returned by the builtin function avg() when called with the
    two arguments a, b.)

    Function definitions can be very complicated.  Functions may be
    defined on the command line if desired, but editing of partial
    functions is not possible past a single line.  If an error is made
    on a previous line, then the function must be finished (with probable
    errors) and reentered from the beginning.  Thus for complicated
    functions, it is best to use an editor to create the definition in a
    file, and then enter the calculator and read in the file containing
    the definition.

    The parameters of a function can be referenced by name, as in
    normal C usage, or by using the 'param' function.  This function
    returns the specified parameter of the function it is in, where
    the parameters are numbered starting from 1.  The total number
    of parameters to the function is returned by using 'param(0)'.
    Using this function allows you to implement varargs-like routines
    which can handle up to 100 calling parameters.  For example:

	    define sc()
	    {
		    local s, i;

		    s = 0;
		    for (i = 1; i <= param(0); i++)
			    s += param(i)^3;
		    return s;
	    }

    defines a function which returns the sum of the cubes of all its
    parameters.

    Any identifier other than a reserved word (if, for, etc.) and the
    name of a builtin function (abs, fact, sin, etc.) can be used when
    defining a new function or redefining an existing function.

    An indication of how a user-defined function is stored may be obtained
    by using the "show opcodes" command.  For example:

		> global alpha
		> define f(x) = 5 + alpha * x
		"f" defined
		> show opcodes f
		0: NUMBER 5
		2: GLOBALADDR alpha
		4: PARAMADDR 0
		6: MUL
		7: ADD
		8: RETURN


*************
* environment
*************

Environment variables

    CALCPATH

	A :-separated list of directories used to search for
	scripts filenames that do not begin with /, ./ or ~.

	If this variable does not exist, a compiled value
	is used.  Typically compiled in value is:

		    .:./lib:~/lib:${LIBDIR}/calc

	where ${LIBDIR} is usually:

		    /usr/local/lib/calc

	This value is used by the READ command.  It is an error
	if no such readable file is found.

	The CALCBINDINGS file searches the CALCPATH as well.


    CALCRC

	On startup (unless -h or -q was given on the command
	line), calc searches for files along the :-separated
	$CALCRC environment variable.

	If this variable does not exist, a compiled value
	is used.  Typically compiled in value is:

		    ${LIBDIR}/startup:~/.calcrc

	where ${LIBDIR} is usually:

		    /usr/local/lib/calc

	Missing files along the $CALCRC path are silently ignored.

    CALCBINDINGS

	On startup (unless -h or -q was given on the command
	line), calc reads key bindings from the filename specified
	in the $CALCRC environment variable.  These key bindings
	are used for command line editing and the command history.

	If this variable does not exist, a compiled value is used.
	Typically compiled in value is:

		    bindings
	or:
		    altbind		(bindings where ^D means exit)

	The bindings file is searched along the CALCPATH.  Unlike
	the READ command, a .cal extension is not added.

	If the file could not be opened, or if standard input is not
	a terminal, then calc will still run, but fancy command line
	editing is disabled.

    HOME

	This value is taken to be the home directory of the
	current user.  It is used when files begin with '~/'.

	If this variable does not exist, the home directory password
	entry of the current user is used.  If that information
	is not available, '.' is used.

    PAGER

	When invoking help, this environment variable is used
	to display a help file.

	If this variable does not exist, a compiled value
	is used.  Typically compiled in value is something
	such as 'more', 'less', 'pg' or 'cat'.

    SHELL

	When a !-command is used, the program indicated by
	this environment variable is used.

	If this variable does not exist, a compiled value
	is used.  Typically compiled in value is something
	such as 'sh' is used.

*************
* expression
*************

Expression sequences

    This is a sequence of statements, of which expression statements
    are the commonest case.  Statements are separated with semicolons,
    and the newline character generally ends the sequence.  If any
    statement is an expression by itself, or is associated with an
    'if' statement which is true, then two special things can happen.
    If the sequence is executed at the top level of the calculator,
    then the value of '.' is set to the value of the last expression.
    Also, if an expression is a non-assignment, then the value of the
    expression is automatically printed if its value is not NULL.
    Some operations such as	pre-increment and plus-equals are also
    treated as assignments.

    Examples of this are the following:

    expression		    sets '.' to		prints
    ----------		    -----------		------
    3+4				7		   7
    2*4; 8+1; fact(3)		6		8, 9, and 6
    x=3^2			9		   -
    if (3 < 2) 5; else 6	6		   6
    x++				old x		   -
    print fact(4)		-		   24
    null()			null()		   -

    Variables can be defined at the beginning of an expression sequence.
    This is most useful for local variables, as in the following example,
    which sums the square roots of the first few numbers:

    local s, i; s = 0; for (i = 0; i < 10; i++) s += sqrt(i); s

    If a return statement is executed in an expression sequence, then
    the result of the expression sequence is the returned value.  In
    this case, '.' is set to the value, but nothing is printed.

*************
* errorcodes
*************

Calc generated error codes (see the error help file):

    10001	Division by zero
    10002	Indeterminate (0/0)
    10003	Bad arguments for +
    10004	Bad arguments for binary -
    10005	Bad arguments for *
    10006	Bad arguments for /
    10007	Bad argument for unary -
    10008	Bad argument for squaring
    10009	Bad argument for inverse
    10010	Bad argument for ++
    10011	Bad argument for --
    10012	Bad argument for int
    10013	Bad argument for frac
    10014	Bad argument for conj
    10015	Bad first argument for appr
    10016	Bad second argument for appr
    10017	Bad third argument for appr
    10018	Bad first argument for round
    10019	Bad second argument for round
    10020	Bad third argument for round
    10021	Bad first argument for bround
    10022	Bad second argument for bround
    10023	Bad third argument for bround
    10024	Bad first argument for sqrt
    10025	Bad second argument for sqrt
    10026	Bad third argument for sqrt
    10027	Bad first argument for root
    10028	Bad second argument for root
    10029	Bad third argument for root
    10030	Bad argument for norm
    10031	Bad first argument for << or >>
    10032	Bad second argument for << or >>
    10033	Bad first argument for scale
    10034	Bad second argument for scale
    10035	Bad first argument for ^
    10036	Bad second argument for ^
    10037	Bad first argument for power
    10038	Bad second argument for power
    10039	Bad third argument for power
    10040	Bad first argument for quo or //
    10041	Bad second argument for quo or //
    10042	Bad third argument for quo
    10043	Bad first argument for mod or %
    10044	Bad second argument for mod or %
    10045	Bad third argument for mod
    10046	Bad argument for sgn
    10047	Bad first argument for abs
    10048	Bad second argument for abs
    10049	Scan error in argument for eval
    10050	Non-simple type for str
    10051	Non-real epsilon for exp
    10052	Bad first argument for exp
    10053	Non-file first argument for fputc
    10054	Bad second argument for fputc
    10055	File not open for writing for fputc
    10056	Non-file first argument for fgetc
    10057	File not open for reading for fgetc
    10058	Non-string arguments for fopen
    10059	Unrecognized mode for fopen
    10060	Non-file first argument for freopen
    10061	Non-string or unrecognized mode for freopen
    10062	Non-string third argument for freopen
    10063	Non-file argument for fclose
    10064	Non-file argument for fflush
    10065	Non-file first argument for fputs
    10066	Non-string argument after first for fputs
    10067	File not open for writing for fputs
    10068	Non-file argument for fgets
    10069	File not open for reading for fgets
    10070	Non-file first argument for fputstr
    10071	Non-string argument after first for fputstr
    10072	File not open for writing for fputstr
    10073	Non-file first argument for fgetstr
    10074	File not open for reading for fgetstr
    10075	Non-file argument for fgetline
    10076	File not open for reading for fgetline
    10077	Non-file argument for fgetword
    10078	File not open for reading for fgetword
    10079	Non-file argument for rewind
    10080	Non-integer argument for files
    10081	Non-string fmt argument for fprint
    10082	Stdout not open for writing to ???
    10083	Non-file first argument for fprintf
    10084	Non-string second (fmt) argument for fprintf
    10085	File not open for writing for fprintf
    10086	Non-string first (fmt) argument for strprintf
    10087	Error in attempting strprintf ???
    10088	Non-file first argument for fscan
    10089	File not open for reading for fscan
    10090	Non-string first argument for strscan
    10091	Non-file first argument for fscanf
    10092	Non-string second (fmt) argument for fscanf
    10093	Non-lvalue argument after second for fscanf
    10094	File not open for reading or other error for fscanf
    10095	Non-string first argument for strscanf
    10096	Non-string second (fmt) argument for strscanf
    10097	Non-lvalue argument after second for strscanf
    10098	Some error in attempting strscanf ???
    10099	Non-string first (fmt) argument for scanf
    10100	Non-lvalue argument after first for scanf
    10101	Some error in attempting scanf ???
    10102	Non-file argument for ftell
    10103	File not open or other error for ftell
    10104	Non-file first argument for fseek
    10105	Non-integer or negative second argument for fseek
    10106	File not open or other error for fseek
    10107	Non-file argument for fsize
    10108	File not open or other error for fsize
    10109	Non-file argument for feof
    10110	File not open or other error for feof
    10111	Non-file argument for ferror
    10112	File not open or other error for ferror
    10113	Non-file argument for ungetc
    10114	File not open for reading for ungetc
    10115	Bad second argument or other error for ungetc
    10116	Exponent too big in scanning
    10117	E_ISATTY1 is no longer used
    10118	E_ISATTY2 is no longer used
    10119	Non-string first argument for access
    10120	Bad second argument for access
    10121	Bad first argument for search
    10122	Bad second argument for search
    10123	Bad third argument for search
    10124	Bad fourth argument for search
    10125	Cannot find fsize or fpos for search
    10126	File not readable for search
    10127	Bad first argument for rsearch
    10128	Bad second argument for rsearch
    10129	Bad third argument for rsearch
    10130	Bad fourth argument for rsearch
    10131	Cannot find fsize or fpos for rsearch
    10132	File not readable for rsearch
    10133	Too many open files
    10134	Attempt to rewind a file that is not open
    10135	Bad argument type for strerror
    10136	Index out of range for strerror
    10137	Bad epsilon for cos
    10138	Bad first argument for cos
    10139	Bad epsilon for sin
    10140	Bad first argument for sin
    10141	Non-string argument for eval
    10142	Bad epsilon for arg
    10143	Bad first argument for arg
    10144	Non-real argument for polar
    10145	Bad epsilon for polar
    10146	Non-integral argument for fcnt
    10147	Non-variable first argument for matfill
    10148	Non-matrix first argument-value for matfill
    10149	Non-matrix argument for matdim
    10150	Non-matrix argument for matsum
    10151	E_ISIDENT is no longer used
    10152	Non-matrix argument for mattrans
    10153	Non-two-dimensional matrix for mattrans
    10154	Non-matrix argument for det
    10155	Matrix for det not of dimension 2
    10156	Non-square matrix for det
    10157	Non-matrix first argument for matmin
    10158	Non-positive-integer second argument for matmin
    10159	Second argument for matmin exceeds dimension
    10160	Non-matrix first argument for matmin
    10161	Second argument for matmax not positive integer
    10162	Second argument for matmax exceeds dimension
    10163	Non-matrix argument for cp
    10164	Non-one-dimensional matrix for cp
    10165	Matrix size not 3 for cp
    10166	Non-matrix argument for dp
    10167	Non-one-dimensional matrix for dp
    10168	Different-size matrices for dp
    10169	Non-string argument for strlen
    10170	Non-string argument for strcat
    10171	Non-string first argument for strcat
    10172	Non-non-negative integer second argument for strcat
    10173	Bad argument for char
    10174	Non-string argument for ord
    10175	Non-list-variable first argument for insert
    10176	Non-integral second argument for insert
    10177	Non-list-variable first argument for push
    10178	Non-list-variable first argument for append
    10179	Non-list-variable first argument for delete
    10180	Non-integral second argument for delete
    10181	Non-list-variable argument for pop
    10182	Non-list-variable argument for remove
    10183	Bad epsilon argument for ln
    10184	Non-numeric first argument for ln
    10185	Non-integer argument for error
    10186	Argument outside range for error
    10187	Attempt to eval at maximum input depth
    10188	Unable to open string for reading
    10189	First argument for rm is not a non-empty string
    10190	Unable to remove a file
    10191	Operation allowed because calc mode disallows read operations
    10192	Operation allowed because calc mode disallows write operations
    10193	Operation allowed because calc mode disallows exec operations
    10194	Unordered arguments for min
    10195	Unordered arguments for max
    10196	Unordered items for minimum of list
    10197	Unordered items for maximum of list
    10198	Size undefined for argument type
    10199	Calc must be run with a -C argument to use custom function
    10200	Calc was built with custom functions disabled
    10201	Custom function unknown, try: show custom
    10202	Non-integral length for block
    10203	Negative or too-large length for block
    10204	Non-integral chunksize for block
    10205	Negative or too-large chunksize for block
    10206	Named block does not exist for blkfree
    10207	Non-integral id specification for blkfree
    10208	Block with specified id does not exist
    10209	Block already freed
    10210	No-realloc protection prevents blkfree
    10211	Non-integer argument for blocks
    10212	Non-allocated index number for blocks
    10213	Non-integer or negative source index for copy
    10214	Source index too large for copy
    10215	E_COPY3 is no longer used
    10216	Non-integer or negative number for copy
    10217	Number too large for copy
    10218	Non-integer or negative destination index for copy
    10219	Destination index too large for copy
    10220	Freed block source for copy
    10221	Unsuitable source type for copy
    10222	Freed block destinction for copy
    10223	Unsuitable destination type for copy
    10224	Incompatible source and destination for copy
    10225	No-copy-from source variable
    10226	No-copy-to destination variable
    10227	No-copy-from source named block
    10228	No-copy-to destination named block
    10229	No-relocation destination for copy
    10230	File not open for copy
    10231	fseek or fsize failure for copy
    10232	fwrite error for copy
    10233	fread error for copy
    10234	Non-variable first argument for protect
    10235	Non-integer second argument for protect
    10236	Out-of-range second argument for protect
    10237	No-copy-to destination for matfill
    10238	No-assign-from source for matfill
    10239	Non-matrix argument for mattrace
    10240	Non-two-dimensional argument for mattrace
    10241	Non-square argument for mattrace
    10242	Bad epsilon for tan
    10243	Bad argument for tan
    10244	Bad epsilon for cot
    10245	Bad argument for cot
    10246	Bad epsilon for sec
    10247	Bad argument for sec
    10248	Bad epsilon for csc
    10249	Bad argument for csc
    10250	Bad epsilon for sinh
    10251	Bad argument for sinh
    10252	Bad epsilon for cosh
    10253	Bad argument for cosh
    10254	Bad epsilon for tanh
    10255	Bad argument for tanh
    10256	Bad epsilon for coth
    10257	Bad argument for coth
    10258	Bad epsilon for sech
    10259	Bad argument for sech
    10260	Bad epsilon for csch
    10261	Bad argument for csch
    10262	Bad epsilon for asin
    10263	Bad argument for asin
    10264	Bad epsilon for acos
    10265	Bad argument for acos
    10266	Bad epsilon for atan
    10267	Bad argument for atan
    10268	Bad epsilon for acot
    10269	Bad argument for acot
    10270	Bad epsilon for asec
    10271	Bad argument for asec
    10272	Bad epsilon for acsc
    10273	Bad argument for acsc
    10274	Bad epsilon for asin
    10275	Bad argument for asinh
    10276	Bad epsilon for acosh
    10277	Bad argument for acosh
    10278	Bad epsilon for atanh
    10279	Bad argument for atanh
    10280	Bad epsilon for acoth
    10281	Bad argument for acoth
    10282	Bad epsilon for asech
    10283	Bad argument for asech
    10284	Bad epsilon for acsch
    10285	Bad argument for acsch
    10286	Bad epsilon for gd
    10287	Bad argument for gd
    10288	Bad epsilon for agd
    10289	Bad argument for agd
    10290	Log of zero or infinity
    10291	String addition failure
    10292	String multiplication failure
    10293	String reversal failure
    10294	String subtraction failure
    10295	Bad argument type for bit
    10296	Index too large for bit
    10297	Non-integer second argument for setbit
    10298	Out-of-range index for setbit
    10299	Non-string first argument for setbit
    10300	Bad argument for or
    10301	Bad argument for and
    10302	Allocation failure for string or
    10303	Allocation failure for string and
    10304	Bad argument for xorvalue
    10305	Bad argument for comp
    10306	Allocation failure for string diff
    10307	Allocation failure for string comp
    10308	Bad first argument for segment
    10309	Bad second argument for segment
    10310	Bad third argument for segment
    10311	Failure for string segment
    10312	Bad argument type for highbit
    10313	Non-integer argument for highbit
    10314	Bad argument type for lowbit
    10315	Non-integer argument for lowbit
    10316	Bad argument type for unary hash op
    10317	Bad argument type for binary hash op
    10318	Bad first argument for head
    10319	Bad second argument for head
    10320	Failure for strhead
    10321	Bad first argument for tail
    10322	Bad second argument for tail
    10323	Failure for strtail
    10324	Failure for strshift
    10325	Non-string argument for strcmp
    10326	Bad argument type for strncmp
    10327	Varying types of argument for xor
    10328	Bad argument type for xor
    10329	Bad argument type for strcpy
    10330	Bad argument type for strncpy
    10331	Bad argument type for unary backslash
    10332	Bad argument type for setminus
    20000	base of user defined errors

*************
* file
*************

Using files

    The calculator provides some functions which allow the program to
    read or write text files.  These functions use stdio internally,
    and the functions appear similar to some of the stdio functions.
    Some differences do occur, as will be explained here.

    Names of files are subject to ~ expansion just like the C or
    Korn shell.  For example, the file name:

	    ~/.rc.cal

    refers to the file '.rc.cal' under your home directory.  The
    file name:

	    ~chongo/.rc.cal

    refers to the a file 'rc.cal' under the home directory of 'chongo'.

    A file can be opened for either reading, writing, or appending.
    To do this, the 'fopen' function is used, which accepts a filename
    and an open mode, both as strings.  You use 'r' for reading, 'w'
    for writing, and 'a' for appending.  For example, to open the file
    'foo' for reading, the following could be used:

	    fd = fopen('foo', 'r');

    If the open is unsuccessful, the numeric value of errno is returned.
    If the open is successful, a value of type 'file' will be returned.
    You can use the 'isfile' function to test the return value to see
    if the open succeeded.  You should assign the return value of fopen
    to a variable for later use.  File values can be copied to more than
    one variable, and using any of the variables with the same file value
    will produce the same results.

    If you overwrite a variable containing a file value or don't save the
    result of an 'fopen', the opened file still remains open.  Such 'lost'
    files can be recovered by using the 'files' function.  This function
    either takes no arguments or else takes one integer argument.  If no
    arguments are given, then 'files' returns the maximum number of opened
    files.  If an argument is given, then the 'files' function uses it as
    an index into an internal table of open files, and returns a value
    referring to one the open files.  If that entry in the table is not
    in use, then the null value is returned instead.  Index 0 always
    refers to standard input, index 1 always refers to standard output,
    and index 2 always refers to standard error.  These three files are
    already open by the calculator and cannot be closed.  As an example
    of using 'files', if you wanted to assign a file value which is
    equivalent to stdout, you could use:

	    stdout = files(1);

    The 'fclose' function is used to close a file which had been opened.
    When this is done, the file value associated with the file remains
    a file value, but appears 'closed', and cannot be used in further
    file-related calls (except fclose) without causing errors.  This same
    action occurs to all copies of the file value.  You do not need to
    explicitly close all the copies of a file value.  The 'fclose'
    function returns the numeric value of errno if there had been an
    error using the file, or the null value if there was no error.

    The builtin 'errno' can be use to convert an errno number into
    a slightly more meaningful error message:

	    badfile = fopen("not_a_file", "r");
	    if (!isfile(badfile)) {
		print "error #" : badfile : ":", errno(badfile);
	    }

    File values can be printed.  When this is done, the filename of the
    opened file is printed inside of quote marks.  If the file value had
    been closed, then the null string is printed.  If a file value is the
    result of a top-level expression, then in addition to the filename,
    the open mode, file position, and possible EOF, error, and closed
    status is also displayed.

    File values can be used inside of 'if' tests.  When this is done,
    an opened file is TRUE, and a closed file is FALSE.  As an example
    of this, the following loop will print the names of all the currently
    opened non-standard files with their indexes, and then close them:

	    for (i = 3; i < files(); i++) {
		    if (files(i)) {
			    print i, files(i);
			    fclose(files(i));
		    }
	    }

    The functions to read from files are 'fgetline' and 'fgetc'.
    The 'fgetline' function accepts a file value, and returns the next
    input line from a file.  The line is returned as a string value, and
    does not contain the end of line character.  Empty lines return the
    null string.  When the end of file is reached, fgetline returns the
    null value.  (Note the distinction between a null string and a null
    value.)  If the line contained a numeric value, then the 'eval'
    function can then be used to convert the string to a numeric value.
    Care should be used when doing this, however, since eval will
    generate an error if the string doesn't represent a valid expression.
    The 'fgetc' function returns the next character from a file as a
    single character string.  It returns the null value when end of file
    is reached.

    The 'printf' and 'fprintf' functions are used to print results to a
    file (which could be stdout or stderr).  The 'fprintf' function
    accepts a file variable, whereas the 'printf' function assumes the
    use of 'files(1)' (stdout).  They both require a format string, which
    is used in almost the same way as in normal C.  The differences come
    in the interpretation of values to be printed for various formats.
    Unlike in C, where an unmatched format type and value will cause
    problems, in the calculator nothing bad will happen.  This is because
    the calculator knows the types of all values, and will handle them
    all reasonably.  What this means is that you can (for example), always
    use %s or %d in your format strings, even if you are printing a non-
    string or non-numeric value.  For example, the following is valid:

	    printf("Two values are %d and %s\n", "fred", 4567);

    and will print "Two values are fred and 4567".

    Using particular format characters, however, is still useful if
    you wish to use width or precision arguments in the format, or if
    you wish to print numbers in a particular format.  The following
    is a list of the possible numeric formats:

	    %d		print in currently defined numeric format
	    %f		print as floating point
	    %e		print as exponential
	    %r		print as decimal fractions
	    %x		print as hex fractions
	    %o		print as octal fractions
	    %b		print as binary fractions

    Note then, that using %d in the format makes the output configurable
    by using the 'config' function to change the output mode, whereas
    the other formats override the mode and force the output to be in
    the specified format.

    Using the precision argument will override the 'config' function
    to set the number of decimal places printed.  For example:

	    printf("The number is %.100f\n", 1/3);

    will print 100 decimal places no matter what the display configuration
    value is set to.

    The %s and %c formats are identical, and will print out the string
    representation of the value.  In these cases, the precision argument
    will truncate the output the same way as in standard C.

    If a matrix or list is printed, then the output mode and precision
    affects the printing of each individual element.  However, field
    widths are ignored since these values print using multiple lines.
    Field widths are also ignored if an object value prints on multiple
    lines.

    The functions 'fputc' and 'fputs' write a character and string to
    a file respectively.

    The final file-related functions are 'fflush', 'ferror', and 'feof'.
    The 'fflush' function forces buffered output to a file.  The 'ferror'
    function returns nonzero if an error had occurred to a file.  The
    'feof' function returns nonzero if end of file has been reached
    while reading a file.

    The 'strprintf' function formats output similarly to 'printf',
    but the output is returned as a string value instead of being
    printed.

*************
* history
*************

Command history

    There is a command line editor and history mechanism built
    into calc, which is active when stdin is a terminal.  When
    stdin is not a terminal, then the command line editor is
    disabled.

    Lines of input to calc are always terminated by the return
    (or enter) key.  When the return key is typed, then the current
    line is executed and is also saved into a command history list
    for future recall.

    Before the return key is typed, the current line can be edited
    using emacs-like editing commands.  As examples, ^A moves to
    the beginning of the line, ^F moves forwards through the line,
    backspace removes characters from the line, and ^K kills the
    rest of the line.

    Previously entered commands can be recalled by using the history
    list.  The history list functions in a LRU manner, with no
    duplicated lines.  This means that the most recently entered
    lines are always at the end of the history list where they are
    easiest to recall.

    Typing <esc>h lists all of the commands in the command history
    and numbers the lines.  The most recently executed line is always
    number 1, the next most recent number 2, and so on.  The numbering
    for a particular command therefore changes as lines are entered.

    Typing a number at the beginning of a line followed by <esc>g
    will recall that numbered line.  So that for example, 2<esc>g
    will recall the second most recent line that was entered.

    The ^P and ^N keys move up and down the lines in the history list.
    If they attempt to go off the top or bottom of the list, then a
    blank line is shown to indicate this, and then they wrap around
    to the other end of the list.

    Typing a string followed by a ^R will search backwards through
    the history and recall the most recent command which begins
    with that string.

    Typing ^O inserts the current line at the end of the history list
    without executing it, and starts a new line.  This is useful to
    rearrange old history lines to become recent, or to save a partially
    completed command so that another command can be typed ahead of it.

    If your terminal has arrow keys which generate escape sequences
    of a particular kind (<esc>[A and so on), then you can use
    those arrow keys in place of the ^B, ^F, ^P, and ^N keys.

    The actual keys used for editing are defined in a bindings file,
    usually called /usr/local/lib/calc/bindings.  Changing the entries
    in this file will change the key bindings used for editing.  If the
    file is not readable, then a message will be output and command
    line editing is disabled.  In this case you can only edit each
    line as provided by the terminal driver in the operating system.

    A shell command can be executed by typing '!cmd', where cmd
    is the command to execute.  If cmd is not given, then a shell
    command level is started.

*************
* interrupt
*************

Interrupts

    While a calculation is in progress, you can generate the SIGINT
    signal, and the calculator will catch it.  At appropriate points
    within a calculation, the calculator will check that the signal
    has been given, and will abort the calculation cleanly.  If the
    calculator is in the middle of a large calculation, it might be
    a while before the interrupt has an effect.

    You can generate the SIGINT signal multiple times if necessary,
    and each time the calculator will abort the calculation at a more
    risky place within the calculation.  Each new interrupt prints a
    message of the form:

	    [Abort level n]

    where n ranges from 1 to 3.  For n equal to 1, the calculator will
    abort calculations at the next statement boundary.  For n equal to 2,
    the calculator will abort calculations at the next opcode boundary.
    For n equal to 3, the calculator will abort calculations at the next
    lowest level arithmetic operation boundary.

    If a final interrupt is given when n is 3, the calculator will
    immediately abort the current calculation and longjmp back to the
    top level command level.  Doing this may result in corrupted data
    structures and unpredictable future behavior, and so should only
    be done as a last resort.  You are advised to quit the calculator
    after this has been done.

*************
* list
*************

NAME
    list - create list of specified values

SYNOPSIS
    list([x, [x, ... ]])

TYPES
    x		any, &any

    return	list

DESCRIPTION
    This function returns a list that is composed of the arguments x.
    If no args are given, an empty list is returned.

    Lists are a sequence of values which are doubly linked so that
    elements can be removed or inserted anywhere within the list.
    The function 'list' creates a list with possible initial elements.
    For example,

	    x = list(4, 6, 7);

    creates a list in the variable x of three elements, in the order
    4, 6, and 7.

    The 'push' and 'pop' functions insert or remove an element from
    the beginning of the list.  The 'append' and 'remove' functions
    insert or remove an element from the end of the list.  The 'insert'
    and 'delete' functions insert or delete an element from the middle
    (or ends) of a list.  The functions which insert elements return
    the null value, but the functions which remove an element return
    the element as their value.  The 'size' function returns the number
    of elements in the list.

    Note that these functions manipulate the actual list argument,
    instead of returning a new list.  Thus in the example:

	    push(x, 9);

    x becomes a list of four elements, in the order 9, 4, 6, and 7.
    Lists can be copied by assigning them to another variable.

    An arbitrary element of a linked list can be accessed by using the
    double-bracket operator.  The beginning of the list has index 0.
    Thus in the new list x above, the expression x[[0]] returns the
    value of the first element of the list, which is 9.  Note that this
    indexing does not remove elements from the list.

    Since lists are doubly linked in memory, random access to arbitrary
    elements can be slow if the list is large.  However, for each list
    a pointer is kept to the latest indexed element, thus relatively
    sequential accesses to the elements in a list will not be slow.

    Lists can be searched for particular values by using the 'search'
    and 'rsearch' functions.  They return the element number of the
    found value (zero based), or null if the value does not exist in
    the list.

EXAMPLE
    > list(2,"three",4i)

    list (3 elements, 3 nonzero):
      [[0]] = 2
      [[1]] = "three"
      [[2]] = 4i

    > list()
	    list (0 elements, 0 nonzero)

LIMITS
    none

LIBRARY
    none

SEE ALSO
    append, delete, insert, islist, pop, push, remove, rsearch, search, size

*************
* mat
*************

Using matrices

    Matrices can have from 1 to 4 dimensions, and are indexed by a
    normal-sized integer.  The lower and upper bounds of a matrix can
    be specified at runtime.  The elements of a matrix are defaulted
    to zeroes, but can be assigned to be of any type.  Thus matrices
    can hold complex numbers, strings, objects, etc.  Matrices are
    stored in memory as an array so that random access to the elements
    is easy.

    Matrices are normally indexed using square brackets.  If the matrix
    is multi-dimensional, then an element can be indexed either by
    using multiple pairs of square brackets (as in C), or else by
    separating the indexes by commas.  Thus the following two statements
    reference the same matrix element:

	    x = name[3][5];
	    x = name[3,5];

    The double-square bracket operator can be used on any matrix to
    make references to the elements easy and efficient.  This operator
    bypasses the normal indexing mechanism, and treats the array as if
    it was one-dimensional and with a lower bound of zero.  In this
    indexing mode, elements correspond to the normal indexing mode where
    the rightmost index increases most frequently.  For example, when
    using double-square bracket indexing on a two-dimensional matrix,
    increasing indexes will reference the matrix elements left to right,
    row by row.  Thus in the following example, 'x' and 'y' are copied
    from the same matrix element:

	    mat m[1:2, 1:3];
	    x = m[2,1];
	    y = m[[3]];

    There are functions which return information about a matrix.
    The 'size' functions returns the total number of elements.
    The 'matdim', 'matmin', and 'matmax' functions return the number
    of dimensions of a matrix, and the lower and upper index bounds
    for a dimension of a matrix.  For square matrices, the 'det'
    function calculates the determinant of the matrix.

    Some functions return matrices as their results.  These	functions
    do not affect the original matrix argument, but instead return
    new matrices.  For example, the 'mattrans' function returns the
    transpose of a matrix, and 'inverse' returns the inverse of a
    matrix.  So to invert a matrix called 'x', you could use:

	    x = inverse(x);

    The 'matfill' function fills all elements of a matrix with the
    specified value, and optionally fills the diagonal elements of a
    square matrix with a different value.  For example:

	    matfill(x,1);

    will fill any matrix with ones, and:

	    matfill(x, 0, 1);

    will create an identity matrix out of any square matrix.  Note that
    unlike most matrix functions, this function does not return a matrix
    value, but manipulates the matrix argument itself.

    Matrices can be multiplied by numbers, which multiplies each element
    by the number.  Matrices can also be negated, conjugated, shifted,
    rounded, truncated, fractioned, and modulo'ed.  Each of these
    operations is applied to each element.

    Matrices can be added or multiplied together if the operation is
    legal.  Note that even if the dimensions of matrices are compatible,
    operations can still fail because of mismatched lower bounds.  The
    lower bounds of two matrices must either match, or else one of them
    must have a lower bound of zero.  Thus the following code:

	    mat x[3:3];
	    mat y[4:4];
	    z = x + y;

    fails because the calculator does not have a way of knowing what
    the bounds should be on the resulting matrix.  If the bounds match,
    then the resulting matrix has the same bounds.  If exactly one of
    the lower bounds is zero, then the resulting matrix will have the
    nonzero lower bounds.  Thus means that the bounds of a matrix are
    preserved when operated on by matrices with lower bounds of zero.
    For example:

	    mat x[3:7];
	    mat y[5];
	    z = x + y;

    will succeed and assign the variable 'z' a matrix whose
    bounds are 3-7.

    Vectors are matrices of only a single dimension.  The 'dp' and 'cp'
    functions calculate the dot product and cross product of a vector
    (cross product is only defined for vectors of size 3).

    Matrices can be searched for particular values by using the 'search'
    and 'rsearch' functions.  They return the element number of the
    found value (zero based), or null if the value does not exist in the
    matrix.  Using the element number in double-bracket indexing will
    then refer to the found element.

*************
* obj
*************

Using objects

    Objects are user-defined types which are associated with user-
    defined functions to manipulate them.  Object types are defined
    similarly to structures in C, and consist of one or more elements.
    The advantage of an object is that the user-defined routines are
    automatically called by the calculator for various operations,
    such as addition, multiplication, and printing.  Thus they can be
    manipulated by the user as if they were just another kind of number.

    An example object type is "surd", which represents numbers of the form

	    a + b*sqrt(D),

    where D is a fixed integer, and 'a' and 'b' are arbitrary rational
    numbers.  Addition, subtraction, multiplication, and division can be
    performed on such numbers, and the result can be put unambiguously
    into the same form.  (Complex numbers are an example of surds, where
    D is -1.)

    The "obj" statement defines either an object type or an actual
    variable of that type.  When defining the object type, the names of
    its elements are specified inside of a pair of braces.  To define
    the surd object type, the following could be used:

	    obj surd {a, b};

    Here a and b are the element names for the two components of the
    surd object.  An object type can be defined more than once as long
    as the number of elements and their names are the same.

    When an object is created, the elements are all defined with zero
    values.  A user-defined routine should be provided which will place
    useful values in the elements.  For example, for an object of type
    'surd', a function called 'surd' can be defined to set the two
    components as follows:

	    define surd(a, b)
	    {
		    local x;

		    obj surd x;
		    x.a = a;
		    x.b = b;
		    return x;
	    }

    When an operation is attempted for an object, user functions with
    particular names are automatically called to perform the operation.
    These names are created by concatenating the object type name and
    the operation name together with an underscore.  For example, when
    multiplying two objects of type surd, the function "surd_mul" is
    called.

    The user function is called with the necessary arguments for that
    operation.  For example, for "surd_mul", there are two arguments,
    which are the two numbers.  The order of the arguments is always
    the order of the binary operands.  If only one of the operands to
    a binary operator is an object, then the user function for that
    object type is still called.  If the two operands are of different
    object types, then the user function that is called is the one for
    the first operand.

    The above rules mean that for full generality, user functions
    should detect that one of their arguments is not of its own object
    type by using the 'istype' function, and then handle these cases
    specially.  In this way, users can mix normal numbers with object
    types.  (Functions which only have one operand don't have to worry
    about this.)  The following example of "surd_mul" demonstrates how
    to handle regular numbers when used together with surds:

	    define surd_mul(a, b)
	    {
		    local x;

		    obj surd x;
		    if (!istype(a, x)) {
			    /* a not of type surd */
			    x.a = b.a * a;
			    x.b = b.b * a;
		    } else if (!istype(b, x)) {
			    /* b not of type surd */
			    x.a = a.a * b;
			    x.b = a.b * b;
		    } else {
			    /* both are surds */
			    x.a = a.a * b.a + D * a.b * b.b;
			    x.b = a.a * b.b + a.b * b.a;
		    }
		    if (x.b == 0)
			    return x.a;	/* normal number */
		    return x;		/* return surd */
	    }

    In order to print the value of an object nicely, a user defined
    routine can be provided.  For small amounts of output, the print
    routine should not print a newline.  Also, it is most convenient
    if the printed object looks like the call to the creation routine.
    For output to be correctly collected within nested output calls,
    output should only go to stdout.  This means use the 'print'
    statement, the 'printf' function, or the 'fprintf' function with
    'files(1)' as the output file.  For example, for the "surd" object:

	    define surd_print(a)
	    {
		    print "surd(" : a.a : "," : a.b : ")" : ;
	    }

    It is not necessary to provide routines for all possible operations
    for an object, if those operations can be defaulted or do not make
    sense for the object.  The calculator will attempt meaningful
    defaults for many operations if they are not defined.  For example,
    if 'surd_square' is not defined to square a number, then 'surd_mul'
    will be called to perform the squaring.  When a default is not
    possible, then an error will be generated.

    Please note: Arguments to object functions are always passed by
    reference (as if an '&' was specified for each variable in the call).
    Therefore, the function should not modify the parameters, but should
    copy them into local variables before modifying them.  This is done
    in order to make object calls quicker in general.

    The double-bracket operator can be used to reference the elements
    of any object in a generic manner.  When this is done, index 0
    corresponds to the first element name, index 1 to the second name,
    and so on.  The 'size' function will return the number of elements
    in an object.

    The following is a list of the operations possible for objects.
    The 'xx' in each function name is replaced with the actual object
    type name.  This table is displayed by the 'show objfuncs' command.

	    Name	Args	Comments

	    xx_print    1	print value, default prints elements
	    xx_one      1	multiplicative identity, default is 1
	    xx_test     1	logical test (false,true => 0,1),
				default tests elements
	    xx_add      2
	    xx_sub      2	subtraction, default adds negative
	    xx_neg      1	negative
	    xx_mul      2
	    xx_div      2	non-integral division, default multiplies
				by inverse
	    xx_inv      1	multiplicative inverse
	    xx_abs      2	absolute value within given error
	    xx_norm     1	square of absolute value
	    xx_conj     1	conjugate
	    xx_pow      2	integer power, default does multiply,
				square, inverse
	    xx_sgn      1	sign of value (-1, 0, 1)
	    xx_cmp      2	equality (equal,non-equal => 0,1),
				default tests elements
	    xx_rel      2	inequality (less,equal,greater => -1,0,1)
	    xx_quo      2	integer quotient
	    xx_mod      2	remainder of division
	    xx_int      1	integer part
	    xx_frac     1	fractional part
	    xx_inc      1	increment, default adds 1
	    xx_dec      1	decrement, default subtracts 1
	    xx_square   1	default multiplies by itself
	    xx_scale    2	multiply by power of 2
	    xx_shift    2	shift left by n bits (right if negative)
	    xx_round    2	round to given number of decimal places
	    xx_bround   2	round to given number of binary places
	    xx_root     3	root of value within given error
	    xx_sqrt     2	square root within given error
	    xx_or	2	boolean or
	    xx_and	2	boolean and
	    xx_not	1	boolean not
	    xx_fact	1	factorial


    Also see the library files:

	    dms.cal
	    mod.cal
	    poly.cal
	    quat.cal
	    surd.cal

*************
* operator
*************

operators

    The operators are similar to C, but there are some differences in
    the associativity and precedence rules for some operators.  In
    addition, there are several operators not in C, and some C
    operators are missing.  A more detailed discussion of situations
    that may be unexpected for the C programmer may be found in
    the 'unexpected' help file.

    Below is a list giving the operators arranged in order of
    precedence, from the least tightly binding to the most tightly
    binding.  Except where otherwise indicated, operators at the same
    level of precedence associate from left to right.

    Unlike C, calc has a definite order for evaluation of terms (addends
    in a sum, factors in a product, arguments for a function or a
    matrix, etc.).  This order is always from left to right. but
    skipping of terms may occur for ||, && and ? : .  For example,
    an expression of the form:

	    A * B + C * D

    is evaluated in the following order:

	    A
	    B
	    A * B
	    C
	    D
	    C * D
	    A * B + C * D

    This order of evaluation is significant if evaluation of a
    term changes a variable on which a later term depends.  For example:

	    x++ * x++ + x++ * x++

    returns the value of:

	    x * (x + 1) + (x + 2) * (x + 3)

    and increments x as if by x += 4.  Similarly, for functions f, g,
    the expression:

	    f(x++, x++) + g(x++)

    evaluates to:

	    f(x, x + 1) + g(x + 2)

    and increments x three times.

    In A || B, B is read only if A tests as false;  in A && B, B is
    read only if A tests as true.  Thus if x is nonzero,
    x++ || x++ returns x and increments x once; if x is zero,
    it returns x + 1 and increments x twice.


    ,	Comma operator.
	    a, b returns the value of b.
	    For situations in which a comma is used for another purpose
	    (function arguments, array indexing, and the print statement),
	    parenthesis must be used around the comma operator expression.
	    E.g., if A is a matrix, A[(a, b), c] evaluates a, b, and c, and
	    returns the value of A[b, c].

    +=  -=  *=  /=  %=  //=  &=  |=  <<=  >>=  ^=  **=
	 Operator-with-assignments.
	    These associate from left to right, e.g. a += b *= c has the
	    effect of a = (a + b) * c, where only a is required to be an
	    lvalue.  For the effect of b *= c; a += b; when both a and b
	    are lvalues, use a += (b *= c).

    =	Assignment.
	    As in C, this, when repeated, this associates from right to left,
	    e.g. a = b = c has the effect of a = (b = c).  Here both a and b
	    are to be lvalues.

    ? :	Conditional value.
	    a ? b : c  returns b if a tests as true (i.e. nonzero if
	    a is a number), c otherwise.  Thus it is equivalent to:
	    if (a) return b; else return c;.
	    All that is required of the arguments in this function
	    is that the "is-it-true?" test is meaningful for a.
	    As in C, this operator associates from right to left,
	    i.e. a ? b : c ? d : e is evaluated as a ? b : (c ? d : e).

    ||	Logical OR.
	    Unlike C, the result for a || b is one of the operands
	    a, b rather than one of the numbers 0 and 1.
	    a || b is equivalent to a ? a : b, i.e. if a tests as
	    true, a is returned, otherwise b.  The effect in a
	    test like "if (a || b) ... " is the same as in C.

    &&	Logical AND.
	    Unlike C, the result for a && b is one of the operands
	    a, b rather than one of the numbers 0 and 1.
	    a && b is equivalent to a ? b : a, i.e. if a tests as
	    true, b is returned, otherwise a.  The effect in a
	    test like "if (a && b) ... " is the same as in C.

    ==  !=  <=  >=  <  >
	    Relations.

    +  -
	    Binary plus and minus and unary plus and minus when applied to
	    a first or only term.

    *  /  //  %
	    Multiply, divide, and modulo.
	    Please Note: The '/' operator is a fractional divide,
	    whereas the '//' is an integral divide.  Thus think of '/'
	    as division of real numbers, and think of '//' as division
	    of integers (e.g., 8 / 3 is 8/3 whereas 8 // 3 is 2).
	    The '%' is integral or fractional modulus (e.g., 11%4 is 3,
	    and 10%pi() is ~.575222).

    |	Bitwise OR.
	    In a | b, both a and b are to be real integers;
	    the signs of a and b are ignored, i.e.
	    a | b = abs(a) | abs(b) and the result will
	    be a non-negative integer.

    &	Bitwise AND.
	    In a & b, both a and b are to be real integers;
	    the signs of a and b are ignored as for a | b.

    ^  **  <<  >>
	    Powers and shifts.
	    The '^' and '**' are both exponentiation, e.g. 2^3
	    returns 8, 2^-3 returns .125.  In a ^ b, b has to be
	    an integer and if a is zero, nonnegative.  0^0 returns
	    the value 1.

	    For the shift operators both arguments are to be
	    integers, or if the first is complex, it is to have
	    integral real and imaginary parts.  Changing the
	    sign of the second argument reverses the shift, e.g.
	    a >> -b = a << b.  The result has the same sign as
	    the first argument except that a nonzero value is
	    reduced to zero by a sufficiently long shift to the
	    right.  These operators associate right to left,
	    e.g.  a << b ^ c = a << (b ^ c).

    +  -  !
            Plus (+) and minus (-) have their usual meanings as unary
            prefix operators at this level of precedence when applied to
	    other than a first or only term.

	    As a prefix operator, '!' is the logical NOT: !a returns 0 if
	    a tests as nonzero, and 1 if a tests as zero, i.e. it is
	    equivalent to a ? 0 : 1.  Be careful about
	    using this as the first character of a top level command,
	    since it is also used for executing shell commands.

	    As a postfix operator ! gives the factorial function, i.e.
	    a! = fact(a).

    ++  --
	    Pre or post incrementing or decrementing.
	    These are applicable only to variables.

    [ ]  [[ ]]  .  ( )
	    Indexing, double-bracket indexing, element references,
	    and function calls.  Indexing can only be applied to matrices,
	    element references can only be applied to objects, but
	    double-bracket indexing can be applied to matrices, objects,
	    or lists.

    variables  constants  .  ( )
	    These are variable names and constants, the special '.' symbol,
	    or a parenthesized expression.  Variable names begin with a
	    letter, but then can contain letters, digits, or underscores.
	    Constants are numbers in various formats, or strings inside
	    either single or double quote marks.


    The most significant difference from the order of precedence in
    C is that | and & have higher precedence than ==, +, -, *, / and %.
    For example, in C a == b | c * d is interpreted as:

	    (a == b) | (c * d)

    and calc it is:

	    a == ((b | c) * d)


    Most of the operators will accept any real or complex numbers
    as arguments.  The exceptions are:

    /  //  %
	    Second argument must be nonzero.

    ^
	    The exponent must be an integer.  When raising zero
	    to a power, the exponent must be non-negative.

    |  &
	    Both both arguments must be integers.

    <<  >>
	    The shift amount must be an integer.  The value being
	    shifted must be an integer or a complex number with
	    integral real and imaginary parts.


    See the 'unexpected' help file for a list of unexpected
    surprises in calc syntax/usage.  Persons familiar with C should
    read the 'unexpected' help file to avoid confusion.

*************
* statement
*************

Statements

    Statements are very much like C statements.  Most statements act
    identically to those in C, but there are minor differences and
    some additions.  The following is a list of the statement types,
    with explanation of the non-C statements.  In this list, upper
    case words identify the keywords which are actually in lower case.
    Statements are generally terminated with semicolons, except if the
    statement is the compound one formed by matching braces.  Various
    expressions are optional and may be omitted (as in RETURN).


    NOTE: Calc commands are in lower case.   UPPER case is used below
	  for emphasis only, and should be considered in lower case.


    IF (expr) statement
    IF (expr) statement ELSE statement
    FOR (optionalexpr ; optionalexpr ; optionalexpr) statement
    WHILE (expr) statement
    DO statement WHILE (expr)
    CONTINUE
    BREAK
    GOTO label
	    These all work like in normal C.

    RETURN optionalexpr
	    This returns a value from a function.  Functions always
	    have a return value, even if this statement is not used.
	    If no return statement is executed, or if no expression
	    is specified in the return statement, then the return
	    value from the function is the null type.

    SWITCH (expr) { caseclauses }
	    Switch statements work similarly to C, except for the
	    following.  A switch can be done on any type of value,
	    and the case statements can be of any type of values.
	    The case statements can also be expressions calculated
	    at runtime.  The calculator compares the switch value
	    with each case statement in the order specified, and
	    selects the first case which matches.  The default case
	    is the exception, and only matches once all other cases
	    have been tested.

    { statements }
	    This is a normal list of statements, each one ended by
	    a semicolon.  Unlike the C language, no declarations are
	    permitted within an inner-level compound statement.
	    Declarations are only permitted at the beginning of a
	    function definition, or at the beginning of an expression
	    sequence.

    MAT variable [dimension] [dimension] ...
    MAT variable [dimension, dimension, ...]
    MAT variable [] = { value, ... }
	    This creates a matrix variable with the specified dimensions.
	    Matrices can have from 1 to 4 dimensions.  When specifying
	    multiple dimensions, you can use either the standard C syntax,
	    or else you can use commas for separating the dimensions.
	    For example, the following two statements are equivalent,
	    and so will create the same two dimensional matrix:

		    mat foo[3][6];
		    mat foo[3,6];

	    By default, each dimension is indexed starting at zero,
	    as in normal C, and contains the specified number of
	    elements.  However, this can be changed if a colon is
	    used to separate two values.  If this is done, then the
	    two values become the lower and upper bounds for indexing.
	    This is convenient, for example, to create matrices whose
	    first row and column begin at 1.  Examples of matrix
	    definitions are:

		    mat x[3]	one dimension, bounds are 0-2
		    mat foo[4][5]	two dimensions, bounds are 0-3 and 0-4
		    mat a[-7:7]	one dimension, bounds are (-7)-7
		    mat s[1:9,1:9]	two dimensions, bounds are 1-9 and 1-9

	    Note that the MAT statement is not a declaration, but is
	    executed at runtime.  Within a function, the specified
	    variable must already be defined, and is just converted to
	    a matrix of the specified size, and all elements are set
	    to the value of zero.  For convenience, at the top level
	    command level, the MAT command automatically defines a
	    global variable of the specified name if necessary.

	    Since the MAT statement is executed, the bounds on the
	    matrix can be full expressions, and so matrices can be
	    dynamically allocated.  For example:

		    size = 20;
		    mat data[size*2];

	    allocates a matrix which can be indexed from 0 to 39.

	    Initial values for the elements of a matrix can be specified
	    by following the bounds information with an equals sign and
	    then a list of values enclosed in a pair of braces.  Even if
	    the matrix has more than one dimension, the elements must be
	    specified as a linear list.  If too few values are specified,
	    the remaining values are set to zero.  If too many values are
	    specified, a runtime error will result.  Examples of some
	    initializations are:

		    mat table1[5] = {77, 44, 22};
		    mat table2[2,2] = {1, 2, 3, 4};

	    When an initialization is done, the bounds of the matrix
	    can optionally be left out of the square brackets, and the
	    correct bounds (zero based) will be set.  This can only be
	    done for one-dimensional matrices.  An example of this is:

		    mat fred[] = {99, 98, 97};

	    The MAT statement can also be used in declarations to set
	    variables as being matrices from the beginning.  For example:

		    local mat temp[5];
		    static mat strtable[] = {"hi", "there", "folks");

    OBJ type { elementnames } optionalvariables
    OBJ type variable
	    These create a new object type, or create one or more
	    variables of the specified type.  For this calculator,
	    an object is just a structure which is implicitly acted
	    on by user defined routines.  The user defined routines
	    implement common operations for the object, such as plus
	    and minus, multiply and divide, comparison and printing.
	    The calculator will automatically call these routines in
	    order to perform many operations.

	    To create an object type, the data elements used in
	    implementing the object are specified within a pair
	    of braces, separated with commas.  For example, to
	    define an object will will represent points in 3-space,
	    whose elements are the three coordinate values, the
	    following could be used:

		    obj point {x, y, z};

	    This defines an object type called point, whose elements
	    have the names x, y, and z.  The elements are accessed
	    similarly to structure element accesses, by using a period.
	    For example, given a variable 'v' which is a point object,
	    the three coordinates of the point can be referenced by:

		    v.x
		    v.y
		    v.z

	    A particular object type can only be defined once, and
	    is global throughout all functions.  However, different
	    object types can be used at the same time.

	    In order to create variables of an object type, they
	    can either be named after the right brace of the object
	    creation statement, or else can be defined later with
	    another obj statement.  To create two points using the
	    second (and most common) method, the following is used:

		    obj point p1, p2;

	    This statement is executed, and is not a declaration.
	    Thus within a function, the variables p1 and p2 must have
	    been previously defined, and are just changed to be the
	    new object type.  For convenience, at the top level command
	    level, object variables are automatically defined as being
	    global when necessary.

	    Initial values for an object can be specified by following
	    the variable name by an equals sign and a list of values
	    enclosed in a pair of braces.  For example:

		    obj point pt = {5, 6};

	    The OBJ statement can also be used in declarations to set
	    variables as being objects from the beginning.  If multiple
	    variables are specified, then each one is defined as the
	    specified object type.  Examples of declarations are:

		    local obj point temp1;
		    static obj point temp2 = {4, 3};
		    global obj point p1, p2, p3;

    EXIT string
    QUIT string
	    This command is used in two cases.  At the top command
	    line level, quit will exit from the calculator.  This
	    is the normal way to leave the calculator.  In any other
	    use, quit will abort the current calculation as if an
	    error had occurred.  If a string is given, then the string
	    is printed as the reason for quitting, otherwise a general
	    quit message is printed.  The routine name and line number
	    which executed the quit is also printed in either case.

	    Quit is useful when a routine detects invalid arguments,
	    in order to stop a calculation cleanly.  For example,
	    for a square root routine, an error can be given if the
	    supplied parameter was a negative number, as in:

		    define mysqrt(n)
		    {
			    if (n < 0)
				    quit "Negative argument";
			    ...
		    }

	    Exit is an alias for quit.


    PRINT exprs
	    For interactive expression evaluation, the values of all
	    typed-in expressions are automatically displayed to the
	    user.  However, within a function or loop, the printing of
	    results must be done explicitly.  This can be done using
	    the 'printf' or 'fprintf' functions, as in standard C, or
	    else by using the built-in 'print' statement.  The advantage
	    of the print statement is that a format string is not needed.
	    Instead, the given values are simply printed with zero or one
	    spaces between each value.

	    Print accepts a list of expressions, separated either by
	    commas or colons.  Each expression is evaluated in order
	    and printed, with no other output, except for the following
	    special cases.  The comma which separates expressions prints
	    a single space, and a newline is printed after the last
	    expression unless the statement ends with a colon.  As
	    examples:

		    print 3, 4;		prints "3 4" and newline.
		    print 5:;		prints "5" with no newline.
		    print 'a' : 'b' , 'c';	prints "ab c" and newline.
		    print;			prints a newline.

	    For numeric values, the format of the number depends on the
	    current "mode" configuration parameter.  The initial mode
	    is to print real numbers, but it can be changed to other
	    modes such as exponential, decimal fractions, or hex.

	    If a matrix or list is printed, then the elements contained
	    within the matrix or list will also be printed, up to the
	    maximum number specified by the "maxprint" configuration
	    parameter.  If an element is also a matrix or a list, then
	    their values are not recursively printed.  Objects are printed
	    using their user-defined routine.  Printing a file value
	    prints the name of the file that was opened.


    SHOW item
	    This command displays some information.

		    builtin		built in functions
		    global		global variables
		    function	user-defined functions
		    objfunc		possible object functions
		    config		config parameters and values
		    objtype		defined objects

	    Only the first 4 characters of item are examined, so:

		    show globals
		    show global
		    show glob

	    do the same thing.


    Also see the help topic:

	    command         top level commands

*************
* stdlib
*************

# Copyright (c) 1997 David I. Bell and Landon Curt Noll
# Permission is granted to use, distribute, or modify this source,
# provided that this copyright notice remains intact.

The following calc library files are provided because they serve as
examples of how use the calc language, and/or because the authors thought
them to be useful!

If you write something that you think is useful, please send it to:

    dbell@auug.org.au
    chongo@toad.com                 {uunet,pyramid,sun}!hoptoad!chongo

By convention, a lib file only defines and/or initializes functions,
objects and variables.  (The regression test is an exception.)  Also by
convention, the a usage message regarding each important object and
function is printed at the time of the read.

If a lib file needs to load another lib file, it should use the -once
version of read:

    /* pull in needed library files */
    read -once "surd"
    read -once "lucas"

This will cause the needed library files to be read once.  If these
files have already been read, the read -once will act as a noop.

By convention, the config parameter "lib_debug"  is used to control
the verbosity of debug information printed by lib files.  By default,
the "lib_debug" has a value of 0.

The "lib_debug" config parameter takes the place of the lib_debug
global variable.  By convention, "lib_debug" has the following meanings:

	<-1	no debug messages are printed though some internal
		    debug actions and information may be collected

	-1	no debug messages are printed, no debug actions will be taken

	0	only usage message regarding each important object are
		    printed at the time of the read (default)

	>0	messages regarding each important object are
		    printed at the time of the read in addition
		    to other debug messages

To conform to the above convention, your lib files should end with
lines of the form:

	if (config("lib_debug") >= 0) {
		print "obj xyz defined";
		print "funcA(side_a, side_b, side_c) defined";
		print "funcB(size, mass) defined";
	}


=-=

beer.cal

    Calc's contribution to the 99 Bottles of Beer web page:

	http://www.ionet.net/~timtroyr/funhouse/beer.html#calc


bernoulli.cal

    B(n)

    Calculate the nth Bernoulli number.


bigprime.cal

    bigprime(a, m, p)

    A prime test, base a, on p*2^x+1 for even x>m.


chrem.cal

    chrem(r1,m1 [,r2,m2, ...])
    chrem(rlist, mlist)

    Chinese remainder theorem/problem solver.


deg.cal

    dms(deg, min, sec)
    dms_add(a, b)
    dms_neg(a)
    dms_sub(a, b)
    dms_mul(a, b)
    dms_print(a)

    Calculate in degrees, minutes, and seconds.


ellip.cal

    factor(iN, ia, B, force)

    Attempt to factor using the elliptic functions: y^2 = x^3 + a*x + b.


hello.cal

    Calc's contribution to the Hello World! page:

	http://www.latech.edu/~acm/HelloWorld.shtml
	http://www.latech.edu/~acm/helloworld/calc.html


lucas.cal

    lucas(h, n)

    Perform a primality test of h*2^n-1, with 1<=h<2*n.


lucas_chk.cal

    lucas_chk(high_n)

    Test all primes of the form h*2^n-1, with 1<=h<200 and n <= high_n.
    Requires lucas.cal to be loaded.  The highest useful high_n is 1000.

    Used by regress.cal during the 2100 test set.


lucas_tbl.cal

    Lucasian criteria for primality tables.


mersenne.cal

    mersenne(p)

    Perform a primality test of 2^p-1, for prime p>1.


mfactor.cal

    mfactor(n [, start_k=1 [, rept_loop=10000 [, p_elim=17]]])

    Return the lowest factor of 2^n-1, for n > 0.  Starts looking for factors
    at 2*start_k*n+1.  Skips values that are multiples of primes <= p_elim.
    By default, start_k == 1, rept_loop = 10000 and p_elim = 17.

    The p_elim == 17 overhead takes ~3 minutes on an 200 Mhz r4k CPU and
    requires about ~13 Megs of memory.  The p_elim == 13 overhead
    takes about 3 seconds and requires ~1.5 Megs of memory.

    The value p_elim == 17 is best for long factorizations.  It is the
    fastest even thought the initial startup overhead is larger than
    for p_elim == 13.

mod.cal

    mod(a)
    mod_print(a)
    mod_one()
    mod_cmp(a, b)
    mod_rel(a, b)
    mod_add(a, b)
    mod_sub(a, b)
    mod_neg(a)
    mod_mul(a, b)
    mod_square(a)
    mod_inc(a)
    mod_dec(a)
    mod_inv(a)
    mod_div(a, b)
    mod_pow(a, b)

    Routines to handle numbers modulo a specified number.


natnumset.cal

    isset(a)
    setbound(n)
    empty()
    full()
    isin(a, b)
    addmember(a, n)
    rmmember(a, n)
    set()
    mkset(s)
    primes(a, b)
    set_max(a)
    set_min(a)
    set_not(a)
    set_cmp(a, b)
    set_rel(a, b)
    set_or(a, b)
    set_and(a, b)
    set_comp(a)
    set_setminus(a, b)
    set_diff(a,b)
    set_content(a)
    set_add(a, b)
    set_sub(a, b)
    set_mul(a, b)
    set_square(a)
    set_pow(a, n)
    set_sum(a)
    set_plus(a)
    interval(a, b)
    isinterval(a)
    set_mod(a, b)
    randset(n, a, b)
    polyvals(L, A)
    polyvals2(L, A, B)
    set_print(a)

    Demonstration of how the string operators and functions may be used
    for defining and working with sets of natural numbers not exceeding a
    user-specified bound.


pell.cal

    pellx(D)
    pell(D)

    Solve Pell's equation; Returns the solution X to: X^2 - D * Y^2 = 1.
    Type the solution to pells equation for a particular D.


pi.cal

    qpi(epsilon)

    Calculate pi within the specified epsilon using the quartic convergence
    iteration.


pix.cal

    pi_of_x(x)

    Calculate the number of primes < x using A(n+1)=A(n-1)+A(n-2).  This
    is a SLOW painful method ... the builtin pix(x) is much faster.
    Still, this method is interesting.


pollard.cal

    factor(N, N, ai, af)

    Factor using Pollard's p-1 method.


poly.cal

    Calculate with polynomials of one variable.  There are many functions.
    Read the documentation in the library file.


prompt.cal

    adder()
    showvalues(str)

    Demonstration of some uses of prompt() and eval().


psqrt.cal

    psqrt(u, p)

    Calculate square roots modulo a prime


quat.cal

    quat(a, b, c, d)
    quat_print(a)
    quat_norm(a)
    quat_abs(a, e)
    quat_conj(a)
    quat_add(a, b)
    quat_sub(a, b)
    quat_inc(a)
    quat_dec(a)
    quat_neg(a)
    quat_mul(a, b)
    quat_div(a, b)
    quat_inv(a)
    quat_scale(a, b)
    quat_shift(a, b)

    Calculate using quaternions of the form: a + bi + cj + dk.  In these
    functions, quaternians are manipulated in the form: s + v, where
    s is a scalar and v is a vector of size 3.


randbitrun.cal

    randbitrun([run_cnt])

    Using randbit(1) to generate a sequence of random bits, determine if
    the number and kength of identical bits runs match what is expected.
    By default, run_cnt is to test the next 65536 random values.

    This tests the a55 generator.


randmprime.cal

    randmprime(bits, seed [,dbg])

    Find a prime of the form h*2^n-1 >= 2^bits for some given x.  The initial
    search points for 'h' and 'n' are selected by a cryptographic pseudo-random
    number generator.  The optional argument, dbg, if set to 1, 2 or 3
    turn on various debugging print statements.


randombitrun.cal

    randombitrun([run_cnt])

    Using randombit(1) to generate a sequence of random bits, determine if
    the number and kength of identical bits runs match what is expected.
    By default, run_cnt is to test the next 65536 random values.

    This tests the Blum-Blum-Shub generator.


randomrun.cal

    randomrun([run_cnt])

    Perform the "G. Run test" (pp. 65-68) as found in Knuth's "Art of
    Computer Programming - 2nd edition", Volume 2, Section 3.3.2 on
    the builtin rand() function.  This function will generate run_cnt
    64 bit values.  By default, run_cnt is to test the next 65536
    random values.

    This tests the Blum-Blum-Shub generator.


randrun.cal

    randrun([run_cnt])

    Perform the "G. Run test" (pp. 65-68) as found in Knuth's "Art of
    Computer Programming - 2nd edition", Volume 2, Section 3.3.2 on
    the builtin rand() function.  This function will generate run_cnt
    64 bit values.  By default, run_cnt is to test the next 65536
    random values.

    This tests the a55 generator.


regress.cal

    Test the correct execution of the calculator by reading this library file.
    Errors are reported with '****' mssages, or worse.  :-)


seedrandom.cal

    seedrandom(seed1, seed2, bitsize [,trials])

    Given:
	seed1 - a large random value (at least 10^20 and perhaps < 10^93)
	seed2 - a large random value (at least 10^20 and perhaps < 10^93)
 	size - min Blum modulus as a power of 2 (at least 100, perhaps > 1024)
	trials - number of ptest() trials (default 25) (optional arg)

    Returns:
	the previous random state

    Seed the cryptographically strong Blum generator.  This functions allows
    one to use the raw srandom() without the burden of finding appropriate
    Blum primes for the modulus.


solve.cal

    solve(low, high, epsilon)

    Solve the equation f(x) = 0 to within the desired error value for x.
    The function 'f' must be defined outside of this routine, and the low
    and high values are guesses which must produce values with opposite signs.


sumsq.cal

    ss(p)

    Determine the unique two positive integers whose squares sum to the
    specified prime.  This is always possible for all primes of the form
    4N+1, and always impossible for primes of the form 4N-1.


surd.cal

    surd(a, b)
    surd_print(a)
    surd_conj(a)
    surd_norm(a)
    surd_value(a, xepsilon)
    surd_add(a, b)
    surd_sub(a, b)
    surd_inc(a)
    surd_dec(a)
    surd_neg(a)
    surd_mul(a, b)
    surd_square(a)
    surd_scale(a, b)
    surd_shift(a, b)
    surd_div(a, b)
    surd_inv(a)
    surd_sgn(a)
    surd_cmp(a, b)
    surd_rel(a, b)

    Calculate using quadratic surds of the form: a + b * sqrt(D).


test1700.cal

    value

    This script is used by regress.cal to test the read and use keywords.


test2600.cal

    global defaultverbose
    global err
    testismult(str, n, verbose)
    testsqrt(str, n, eps, verbose)
    testexp(str, n, eps, verbose)
    testln(str, n, eps, verbose)
    testpower(str, n, b, eps, verbose)
    testgcd(str, n, verbose)
    cpow(x, n, eps)
    cexp(x, eps)
    cln(x, eps)
    mkreal()
    mkcomplex()
    mkbigreal()
    mksmallreal()
    testappr(str, n, verbose)
    checkappr(x, y, z, verbose)
    checkresult(x, y, z, a)
    test2600(verbose, tnum)

    This script is used by regress.cal to test some of builtin functions
    in terms of accuracy and roundoff.


test2700.cal

    global defaultverbose
    mknonnegreal()
    mkposreal()
    mkreal_2700()
    mknonzeroreal()
    mkposfrac()
    mkfrac()
    mksquarereal()
    mknonsquarereal()
    mkcomplex_2700()
    testcsqrt(str, n, verbose)
    checksqrt(x, y, z, v)
    checkavrem(A, B, X, eps)
    checkrounding(s, n, t, u, z)
    iscomsq(x)
    test2700(verbose, tnum)

    This script is used by regress.cal to test sqrt() for real and complex
    values.


test3100.cal

    obj res
    global md
    res_test(a)
    res_sub(a, b)
    res_mul(a, b)
    res_neg(a)
    res_inv(a)
    res(x)

    This script is used by regress.cal to test determinants of a matrix


test3300.cal

    global defaultverbose
    global err
    testi(str, n, N, verbose)
    testr(str, n, N, verbose)
    test3300(verbose, tnum)

    This script is used by regress.cal to provide for more determinant tests.


test3400.cal

    global defaultverbose
    global err
    test1(str, n, eps, verbose)
    test2(str, n, eps, verbose)
    test3(str, n, eps, verbose)
    test4(str, n, eps, verbose)
    test5(str, n, eps, verbose)
    test6(str, n, eps, verbose)
    test3400(verbose, tnum)

    This script is used by regress.cal to test trig functions.
    containing objects.

test4000.cal

    global defaultverbose
    global err
    global BASEB
    global BASE
    global COUNT
    global SKIP
    global RESIDUE
    global MODULUS
    global K1
    global H1
    global K2
    global H2
    global K3
    global H3
    plen(N) defined
    rlen(N) defined
    clen(N) defined
    ptimes(str, N, n, count, skip, verbose) defined
    ctimes(str, N, n, count, skip, verbose) defined
    crtimes(str, a, b, n, count, skip, verbose) defined
    ntimes(str, N, n, count, skip, residue, mod, verbose) defined
    testnextcand(str, N, n, cnt, skip, res, mod, verbose) defined
    testnext1(x, y, count, skip, residue, modulus) defined
    testprevcand(str, N, n, cnt, skip, res, mod, verbose) defined
    testprev1(x, y, count, skip, residue, modulus) defined
    test4000(verbose, tnum) defined

    This script is used by regress.cal to test ptest, nextcand and
    prevcand buildins.

test4100.cal

    global defaultverbose
    global err
    global K1
    global K2
    global BASEB
    global BASE
    rlen_4100(N) defined
    olen(N) defined
    test1(x, y, m, k, z1, z2) defined
    testall(str, n, N, M, verbose) defined
    times(str, N, n, verbose) defined
    powtimes(str, N1, N2, n, verbose) defined
    inittimes(str, N, n, verbose) defined
    test4100(verbose, tnum) defined

    This script is used by regress.cal to test REDC operations.

test4600.cal

    stest(str [, verbose]) defined
    ttest([m, [n [,verbose]]]) defined
    sprint(x) defined
    findline(f,s) defined
    findlineold(f,s) defined
    test4600(verbose, tnum) defined

    This script is used by regress.cal to test searching in files.

test5100.cal

    global a5100
    global b5100
    test5100(x) defined

    This script is used by regress.cal to test the new code generator
    declaration scope and order.

test5200.cal

    global a5200
    static a5200
    f5200(x) defined
    g5200(x) defined
    h5200(x) defined

    This script is used by regress.cal to test the fix of a global/static bug.

unitfrac.cal

    unitfrac(x)

    Represent a fraction as sum of distinct unit fractions.


varargs.cal

    sc(a, b, ...)

    Example program to use 'varargs'.  Program to sum the cubes of all
    the specified numbers.

xx_print.cal

    isoctet(a) defined
    list_print(a) defined
    mat_print (a) defined
    octet_print(a) defined
    blk_print(a) defined
    nblk_print (a) defined
    strchar(a) defined
    file_print(a) defined
    error_print(a) defined

    Demo for the xx_print object routines.

*************
* types
*************

Builtin types

    The calculator has the following built-in types.

    null value
	    This is the undefined value type.  The function 'null'
	    returns this value.  Functions which do not explicitly
	    return a value return this type.  If a function is called
	    with fewer parameters than it is defined for, then the
	    missing parameters have the null type.  The null value is
	    false if used in an IF test.

    rational numbers
	    This is the basic data type of the calculator.
	    These are fractions whose numerators and denominators
	    can be arbitrarily large.  The fractions are always
	    in lowest terms.  Integers have a denominator of 1.
	    The numerator of the number contains the sign, so that
	    the denominator is always positive.  When a number is
	    entered in floating point or exponential notation, it is
	    immediately converted to the appropriate fractional value.
	    Printing a value as a floating point or exponential value
	    involves a conversion from the fractional representation.

	    Numbers are stored in binary format, so that in general,
	    bit tests and shifts are quicker than multiplies and divides.
	    Similarly, entering or displaying of numbers in binary,
	    octal, or hex formats is quicker than in decimal.  The
	    sign of a number does not affect the bit representation
	    of a number.

    complex numbers
	    Complex numbers are composed of real and imaginary parts,
	    which are both fractions as defined above.  An integer which
	    is followed by an 'i' character is a pure imaginary number.
	    Complex numbers such as "2+3i" when typed in, are processed
	    as the sum of a real and pure imaginary number, resulting
	    in the desired complex number.  Therefore, parenthesis are
	    sometimes necessary to avoid confusion, as in the two values:

		    1+2i ^2		(which is -3)
		    (1+2i) ^2	(which is -3+4i)

	    Similar care is required when entering fractional complex
	    numbers.  Note the differences below:

		    3/4i		(which is -(3/4)i)
		    3i/4		(which is (3/4)i)

	    The imaginary unit itself is input using "1i".

    strings
	    Strings are a sequence of zero or more characters.
	    They are input using either of the single or double
	    quote characters.  The quote mark which starts the
	    string also ends it.  Various special characters can
	    also be inserted using back-slash.  Example strings:

		    "hello\n"
		    "that's all"
		    'lots of """"'
		    'a'
		    ""

	    There is no distinction between single character and
	    multi-character strings.  The 'str' and 'ord' functions
	    will convert between a single character string and its
	    numeric value.  The 'str' and 'eval' functions will
	    convert between longer strings and the corresponding
	    numeric value (if legal).  The 'strcat', 'strlen', and
	    'substr' functions are also useful.

    matrices
	    These are one to four dimensional matrices, whose minimum
	    and maximum bounds can be specified at runtime.  Unlike C,
	    the minimum bounds of a matrix do not have to start at 0.
	    The elements of a matrix can be of any type.  There are
	    several built-in functions for matrices.  Matrices are
	    created using the 'mat' statement.

    associations
	    These are one to four dimensional matrices which can be
	    indexed by arbitrary values, instead of just integers.
	    These are also known as associative arrays.  The elements of
	    an association can be of any type.  Very few operations are
	    permitted on an association except for indexing.  Associations
	    are created using the 'assoc' function.

    lists
	    These are a sequence of values, which are linked together
	    so that elements can be easily be inserted or removed
	    anywhere in the list.  The values can be of any type.
	    Lists are created using the 'list' function.

    files
	    These are text files opened using stdio.  Files may be opened
	    for sequential reading, writing, or appending.  Opening a
	    file using the 'fopen' function returns a value which can
	    then be used to perform I/O to that file.  File values can
	    be copied by normal assignments between variables, or by
	    using the result of the 'files' function.  Such copies are
	    indistinguishable from each other.

*************
* usage
*************

Calc command line

    Calc has the following command line:

	calc [-C] [-e] [-h] [-i] [-m mode] [-n] [-p] [-q] [-u] [calc_cmd ...]

	-C  Permit the execution of custom builtin functions.  Without
	    this flag, calling the custom() builtin function will
	    simply generate an error.

	    Use if this flag may cause calc to execute functions that
	    are non-standard and that are not portable.  Custom builtin
	    functions are disabled by default for this reason.

	-e  Ignore any environment variables on startup.  The
	    getenv() builtin will still return values, however.

	-h  Print a help message.  This option implies  -q.  This
	    is equivalent to the calc command help help.  The help
	    facility is disabled unless the mode is 5 or 7.  See -m.

	-i  Do not about if the error count exceeds maxerr().

	-m mode
	   This flag sets the permission mode of calc.  It
	   controls the ability for calc to open files and execute
	   programs. Mode may be a number from 0 to 7.

	   The mode value is interpreted in a way similar to that
	   of the chmod(1) octal mode:

		0  do not open any file, do not execute progs
		1  do not open any file
		2  do not open files for reading, do not execute progs
		3  do not open files for reading
		4  do not open files for writing, do not execute progs
		5  do not open files for writing
		6  do not execute any program
		7  allow everything (default mode)

	   If one wished to run calc from a privledged user, one
	   might want to use -m 0 in an effort to make calc more
	   secure.

	   Mode bits for reading and writing apply only on an
	   open.  Files already open are not effected. Thus if one
	   wanted to use the -m 0 in an effort to make calc more
	   secure, but still wanted to read and write a specific
	   file, one might want to do:

		     calc -m 0 3<a.file

	   Files presented to calc in this way are opened in an
	   unknown mode. Calc will attempt to read or write them
	   if directed.

	   If the mode disables opening of files for reading, then
	   the startup library scripts are disabled as of -q was
	   given.  The reading of key bindings is also disabled
	   when the mode disables opening of files for reading.

	-n  Use the new configutation defaults instead of the old
	    default classic defaults.  This flag as the same effect
	    as executing config("all", "newcfg") at startup time.

	-p  Pipe processing is enabled by use of -p.  For example:

		     echo "print 2^21701-1, 2^23209-1" | calc -p | fizzbin

	    In pipe mode, calc does not prompt, does not print
	    leading tabs and does not print the initial header.

	-q  Disable the use of the $CALCRC startup scripts.

	-u  Disable buffering of stdin and stdout.

    Without `calc_cmd', calc operates interactively.  If one or more
    `calc_cmd' are given on the command line, calc will execute them and
    exit.  The printing of leading tabs on output is disabled as if
    config("tab",0) had been executed.

    Normally on startup, calc attempts to execute a collection of
    library scripts.  The environment variable $CALCRC (if non-existent
    then a compiled in value) contains a :  separated list of startup
    library scripts.  No error conditions are produced if these startup
    library scripts are not found.

    If the mode disables opening of files for reading, then the startup
    library scripts are disabled as of -q was given and $CALCRC as well
    as the default compiled in value are ignored.

    Filenames are subject to ``~'' expansion (see below).  The
    environment variable $CALCPATH (if non-existent then a compiled in
    value) contains a : separated list of search directories.  If a
    file does not begin with /, ~ or ./, then it is searched for under
    each directory listed in the $CALCPATH.  It is an error if no such
    readable file is found.

    Calc treats all open files, other than stdin, stdout and
    stderr as files available for reading and writing. One may
    present calc with an already open file in the following way:

        calc 3<open_file 4<open_file2

    For more information use the following calc commands:

       help help
       help overview
       help usage
       help environment
       help config

*************
* unexpected
*************

Unexpected

    While calc is C-like, users of C will find some unexpected
    surprises in calc syntax and usage.  Persons familiar with C should
    review this file.


    The Comma
    =========

    The comma is also used for continuation of obj and mat creation
    expressions and for separation of expressions to be used for
    arguments or values in function calls or initialization lists.  The
    precedence order of these different uses is:  continuation,
    separator, comma operator.  For example, assuming the variables a,
    b, c, d, e, and object type xx have been defined, the arguments
    passed to f in:

	    f(a, b, c, obj xx d, e)

    are a, b, c, and e, with e having the value of a newly created xx
    object.  In:

	    f((a, b), c, (obj xx d), e)

    the arguments of f are b, c, d, e, with only d being a newly
    created xx object.

    In combination with other operators, the continuation use of the
    comma has the same precedence as [] and ., the separator use the
    same as the comma operator.  For example, assuming xx.mul() has
    been defined:

	    f(a = b, obj xx c, d = {1,2} * obj xx e = {3,4})

    passes two arguments: a (with value b) and the product d * e of two
    initialized xx objects.


    ^ is not xor
    ============

    In C, ^ is the xor operator.  Like the '**', '^' is the
    exponentiation operator.  The expression:

	    a^b

    yields "a to the b power", NOT "a xor b".

    Note that 'b' must be an integer.  Also if 'a' == 0, 'b'
    must be >= 0 as well.

    To raise to a non-integer power, use the power() builtin function.


    ** is exponentiation
    ====================

    As was suggested in the '^ is not xor' section, the expression:

	    a**b

    yields "a to the b power", NOT "a xor b".

    Note that 'b' must be an integer.  Also if 'a' == 0, 'b'
    must be >= 0 as well.

    To raise to a non-integer power, use the power() builtin function.


    op= operators associate left to right
    =====================================

    Operator-with-assignments:

	    +=  -=  *=  /=  %=  //=  &=  |=  <<=  >>=  ^=  **=

    associate from left to right instead of right to left as in C.
    For example:

	    a += b *= c

    has the effect of:

	    a = (a + b) * c

    where only 'a' is required to be an lvalue.  For the effect of:

	    b *= c; a += b

    when both 'a' and 'b' are lvalues, use:

	    a += (b *= c)


    || yields values other than 0 or 1
    ==================================

    In C:

	    a || b

    will produce 0 or 1 depending on the logical evaluation
    of the expression.  In calc, this expression will produce
    either 'a' or 'b' and is equivalent to the expression:

	    a ? a : b

    In other words, if 'a' is true, then 'a' is returned, otherwise
    'b' is returned.


    && yields values other than 0 or 1
    ==================================

    In C:

	    a && b

    will produce 0 or 1 depending on the logical evaluation
    of the expression.  In calc, this expression will produce
    either 'a' or 'b' and is equivalent to the expression:

	    a ? b : a

    In other words, if 'a' is true, then 'b' is returned, otherwise
    'a' is returned.


    / is fractional divide, // is integral divide
    =============================================

    In C:

	    x/y

    performs integer division when 'x' and 'y' are integer types.
    In calc, this expression yields a rational number.

    Calc uses:

	    x//y

    to perform division with integer truncation and is the equivalent to:

	    int(x/y)


    | and & have higher precedence than ==, +, -, *, / and %
    ========================================================

    Is C:

	    a == b | c * d

    is interpreted as:

	    (a == b) | (c * d)

    and calc it is interpreted as:

	    a == ((b | c) * d)


    calc always evaluates terms from left to right
    ==============================================

    Calc has a definite order for evaluation of terms (addends in a
    sum, factors in a product, arguments for a function or a matrix,
    etc.).  This order is always from left to right. but skipping of
    terms may occur for ||, && and ? : .

    Consider, for example:

	    A * B + C * D

    In calc above expression is evaluated in the following order:

	    A
	    B
	    A * B
	    C
	    D
	    C * D
	    A * B + C * D

    This order of evaluation is significant if evaluation of a
    term changes a variable on which a later term depends.  For example:

	    x++ * x++ + x++ * x++

    in calc returns the value:

	    x * (x + 1) + (x + 2) * (x + 3)

    and increments x as if by x += 4.  Similarly, for functions f, g,
    the expression:

	    f(x++, x++) + g(x++)

    evaluates to:

	    f(x, x + 1) + g(x + 2)

    and increments x three times.


    &A[0] and A are different things in calc
    ========================================

    In calc, value of &A[0] is the address of the first element, whereas
    A is the entire array.


    *X may be used to to return the value of X
    ==========================================

    If the current value of a variable X is an octet, number or string,
    *X may be used to to return the value of X; in effect X is an
    address and *X is the value at X.


    freeing a variable has the effect of assigning the null value to it
    ===================================================================

    The freeglobals(), freestatics(), freeredc() and free() free
    builtins to not "undefine" the variables, but have the effect of
    assigning the null value to them, and so frees the memory used for
    elements of a list, matrix or object.

    Along the same lines:

	    undefine *

    undefines all current user-defined functions.  After executing
    all the above freeing functions (and if necessary free(.) to free
    the current "old value"), the only remaining numbers as displayed by

	    show numbers

    should be those associated with epsilon(), and if it has been
    called, qpi().

*************
* variable
*************

Variable declarations

    Variables can be declared as either being global, local, or static.
    Global variables are visible to all functions and on the command
    line, and are permanent.  Local variables are visible only within
    a single function or command sequence.  When the function or command
    sequence returns, the local variables are deleted.  Static variables
    are permanent like global variables, but are only visible within the
    same input file or function where they are defined.

    To declare one or more variables, the 'local', 'global', or 'static'
    keywords are used, followed by the desired list of variable names,
    separated by commas.  The definition is terminated with a semicolon.
    Examples of declarations are:

	    local	x, y, z;
	    global	fred;
	    local	foo, bar;
	    static	var1, var2, var3;

    Variables may have initializations applied to them.  This is done
    by following the variable name by an equals sign and an expression.
    Global and local variables are initialized each time that control
    reaches them (e.g., at the entry to a function which contains them).
    Static variables are initialized once only, at the time that control
    first reaches them (but in future releases the time of initialization
    may change).  Unlike in C, expressions for static variables may
    contain function calls and refer to variables.  Examples of such
    initializations are:

	    local	a1 = 7, a2 = 3;
	    static	b = a1 + sin(a2);

    Within function declarations, all variables must be defined.
    But on the top level command line, assignments automatically define
    global variables as needed.  For example, on the top level command
    line, the following defines the global variable x if it had not
    already been defined:

	    x = 7

    The static keyword may be used at the top level command level to
    define a variable which is only accessible interactively, or within
    functions defined interactively.

    Variables have no fixed type, thus there is no need or way to
    specify the types of variables as they are defined.  Instead, the
    types of variables change as they are assigned to or are specified
    in special statements such as 'mat' and 'obj'.  When a variable is
    first defined using 'local', 'global', or 'static', it has the
    value of zero.

    If a procedure defines a local or static variable name which matches
    a global variable name, or has a parameter name which matches a
    global variable name, then the local variable or parameter takes
    precedence within that procedure, and the global variable is not
    directly accessible.

    The MAT and OBJ keywords may be used within a declaration statement
    in order to initially define variables as that type.  Initialization
    of these variables are also allowed.  Examples of such declarations
    are:

	    static mat table[3] = {5, 6, 7};
	    local obj point p1, p2;

    There are no pointers in the calculator language, thus all
    arguments to user-defined functions are normally passed by value.
    This is true even for matrices, strings, and lists.  In order
    to circumvent this, the '&' operator is allowed before a variable
    when it is an argument to a function.  When this is done, the
    address of the variable is passed to the function instead of its
    value.  This is true no matter what the type of the variable is.
    This allows for fast calls of functions when the passed variable
    is huge (such as a large array).  However, the passed variable can
    then be changed by the function if the parameter is assigned into.
    The function being called does not need to know if the variable
    is being passed by value or by address.

    Built-in functions and object functions always accept their
    arguments as addresses, thus there is no need to use '&' when
    calling built-in functions.

*************
* altbind
*************

# Alternate key bindings for calc line editing functions

map	base-map
default	insert-char
^@	set-mark
^A	start-of-line
^B	backward-char
^D	quit
^E	end-of-line
^F	forward-char
^H	backward-kill-char
^J	new-line
^K	kill-line
^L	refresh-line
^M	new-line
^N	forward-history
^O	save-line
^P	backward-history
^R	reverse-search
^T	swap-chars
^U	flush-input
^V	quote-char
^W	kill-region
^Y	yank
^?	delete-char
^[	ignore-char	esc-map

map	esc-map
default	ignore-char	base-map
G	start-of-line
H	backward-history
P	forward-history
K	backward-char
M	forward-char
O	end-of-line
S	delete-char
g	goto-line
s	backward-word
t	forward-word
d	forward-kill-word
u	uppercase-word
l	lowercase-word
h	list-history
^[	flush-input
[	arrow-key

*************
* bindings
*************

# Default key bindings for calc line editing functions

map	base-map
default	insert-char
^@	set-mark
^A	start-of-line
^B	backward-char
^D	delete-char
^E	end-of-line
^F	forward-char
^H	backward-kill-char
^J	new-line
^K	kill-line
^L	refresh-line
^M	new-line
^N	forward-history
^O	save-line
^P	backward-history
^R	reverse-search
^T	swap-chars
^U	flush-input
^V	quote-char
^W	kill-region
^Y	yank
^?	backward-kill-char
^[	ignore-char	esc-map

map	esc-map
default	ignore-char	base-map
G	start-of-line
H	backward-history
P	forward-history
K	backward-char
M	forward-char
O	end-of-line
S	delete-char
g	goto-line
s	backward-word
t	forward-word
d	forward-kill-word
u	uppercase-word
l	lowercase-word
h	list-history
^[	flush-input
[	arrow-key

*************
* custom_cal
*************

Calc command line

    Calc has the following command line:

	calc [-C] [-e] [-h] [-i] [-m mode] [-n] [-p] [-q] [-u] [calc_cmd ...]

	-C  Permit the execution of custom builtin functions.  Without
	    this flag, calling the custom() builtin function will
	    simply generate an error.

	    Use if this flag may cause calc to execute functions that
	    are non-standard and that are not portable.  Custom builtin
	    functions are disabled by default for this reason.

	-e  Ignore any environment variables on startup.  The
	    getenv() builtin will still return values, however.

	-h  Print a help message.  This option implies  -q.  This
	    is equivalent to the calc command help help.  The help
	    facility is disabled unless the mode is 5 or 7.  See -m.

	-i  Do not about if the error count exceeds maxerr().

	-m mode
	   This flag sets the permission mode of calc.  It
	   controls the ability for calc to open files and execute
	   programs. Mode may be a number from 0 to 7.

	   The mode value is interpreted in a way similar to that
	   of the chmod(1) octal mode:

		0  do not open any file, do not execute progs
		1  do not open any file
		2  do not open files for reading, do not execute progs
		3  do not open files for reading
		4  do not open files for writing, do not execute progs
		5  do not open files for writing
		6  do not execute any program
		7  allow everything (default mode)

	   If one wished to run calc from a privledged user, one
	   might want to use -m 0 in an effort to make calc more
	   secure.

	   Mode bits for reading and writing apply only on an
	   open.  Files already open are not effected. Thus if one
	   wanted to use the -m 0 in an effort to make calc more
	   secure, but still wanted to read and write a specific
	   file, one might want to do:

		     calc -m 0 3<a.file

	   Files presented to calc in this way are opened in an
	   unknown mode. Calc will attempt to read or write them
	   if directed.

	   If the mode disables opening of files for reading, then
	   the startup library scripts are disabled as of -q was
	   given.  The reading of key bindings is also disabled
	   when the mode disables opening of files for reading.

	-n  Use the new configutation defaults instead of the old
	    default classic defaults.  This flag as the same effect
	    as executing config("all", "newcfg") at startup time.

	-p  Pipe processing is enabled by use of -p.  For example:

		     echo "print 2^21701-1, 2^23209-1" | calc -p | fizzbin

	    In pipe mode, calc does not prompt, does not print
	    leading tabs and does not print the initial header.

	-q  Disable the use of the $CALCRC startup scripts.

	-u  Disable buffering of stdin and stdout.

    Without `calc_cmd', calc operates interactively.  If one or more
    `calc_cmd' are given on the command line, calc will execute them and
    exit.  The printing of leading tabs on output is disabled as if
    config("tab",0) had been executed.

    Normally on startup, calc attempts to execute a collection of
    library scripts.  The environment variable $CALCRC (if non-existent
    then a compiled in value) contains a :  separated list of startup
    library scripts.  No error conditions are produced if these startup
    library scripts are not found.

    If the mode disables opening of files for reading, then the startup
    library scripts are disabled as of -q was given and $CALCRC as well
    as the default compiled in value are ignored.

    Filenames are subject to ``~'' expansion (see below).  The
    environment variable $CALCPATH (if non-existent then a compiled in
    value) contains a : separated list of search directories.  If a
    file does not begin with /, ~ or ./, then it is searched for under
    each directory listed in the $CALCPATH.  It is an error if no such
    readable file is found.

    Calc treats all open files, other than stdin, stdout and
    stderr as files available for reading and writing. One may
    present calc with an already open file in the following way:

        calc 3<open_file 4<open_file2

    For more information use the following calc commands:

       help help
       help overview
       help usage
       help environment
       help config

*************
* libcalc
*************

	USING THE ARBITRARY PRECISION ROUTINES IN A C PROGRAM

Part of the calc release consists of an arbitrary precision math library.
This library is used by the calc program to perform its own calculations.
If you wish, you can ignore the calc program entirely and call the arbitrary
precision math routines from your own C programs.

The library is called libcalc.a, and provides routines to handle arbitrary
precision arithmetic with integers, rational numbers, or complex numbers.
There are also many numeric functions such as factorial and gcd, along
with some transcendental functions such as sin and exp.

Take a look at the sample sub-directory.  It contains a few simple
examples of how to use libcalc.a that might be helpful to look at
after you have read this file.

------------------
FIRST THINGS FIRST
------------------

...............................................................................
.									      .
. You MUST call libcalc_call_me_first() prior to using libcalc lib functions! .
.									      .
...............................................................................

The function libcalc_call_me_first() takes no args and returns void.  You
need call libcalc_call_me_first() only once.

-------------
INCLUDE FILES
-------------

To use any of these routines in your own programs, you need to include the
appropriate include file.  These include files are:

	zmath.h		(for integer arithmetic)
	qmath.h		(for rational arithmetic)
	cmath.h		(for complex number arithmetic)

You never need to include more than one of the above files, even if you wish
to use more than one type of arithmetic, since qmath.h automatically includes
zmath.h, and cmath.h automatically includes qmath.h.

The prototypes for the available routines are listed in the above include
files.  Some of these routines are meant for internal use, and so aren't
convenient for outside use.  So you should read the source for a routine
to see if it really does what you think it does.  I won't guarantee that
obscure internal routines won't change or disappear in future releases!

When calc is installed, all of the include files needed to build
libcalc.a along with the library itself (and the lint library
llib-lcalc.ln, if made) are installed into /usr/lib/calc.

External programs may want to compile with:

	-I/usr/lib/calc -L/usr/lib/calc -lcalc

--------------
ERROR HANDLING
--------------

Your program MUST provide a function called math_error.  This is called by
the math routines on an error condition, such as malloc failures or a
division by zero.  The routine is called in the manner of printf, with a
format string and optional arguments.  (However, none of the low level math
routines currently uses formatting, so if you are lazy you can simply use
the first argument as a simple error string.)  For example, one of the
error calls you might expect to receive is:

	math_error("Division by zero");

Your program can handle errors in basically one of two ways.  Firstly, it
can simply print the error message and then exit.  Secondly, you can make
use of setjmp and longjmp in your program.  Use setjmp at some appropriate
level in your program, and use longjmp in the math_error routine to return
to that level and so recover from the error.  This is what the calc program
does.

For convenience, the library libcalc.a contains a math_error routine.
By default, this routine simply prints a message to stderr and then exits.
By simply linking in this library, any calc errors will result in a
error message on stderr followed by an exit.

External programs that wish to use this math_error may want to compile with:

	-I/usr/lib/calc -L/usr/lib/calc -lcalc

If one sets up calc_jmp_buf, and then sets calc_jmp to non-zero then
this routine will longjmp back (with the value of calc_jmp) instead.
In addition, the last calc error message will be found in calc_error;
this error is not printed to stderr.  The calc error message will
not have a trailing newline.

For example:

    #include <setjmp.h>

    extern jmp_buf calc_jmp_buf;
    extern int calc_jmp;
    extern char *calc_error;
    int error;

    ...

    if ((error = setjmp(calc_jmp_buf)) != 0) {

	    /* reinitialize calc after a longjmp */
	    reinitialize();

	    /* report the error */
	    printf("Ouch: %s\n", calc_error);
    }
    calc_jmp = 1;

---------------
OUTPUT ROUTINES
---------------

The output from the routines in the library normally goes to stdout.  You
can divert that output to either another FILE handle, or else to a string.
Read the routines in zio.c to see what is available.  Diversions can be
nested.

You use math_setfp to divert output to another FILE handle.  Calling
math_setfp with stdout restores output to stdout.

Use math_divertio to begin diverting output into a string.  Calling
math_getdivertedio will then return a string containing the output, and
clears the diversion.  The string is reallocated as necessary, but since
it is in memory, there are obviously limits on the amount of data that can
be diverted into it.  The string needs freeing when you are done with it.

Calling math_cleardiversions will clear all the diversions to strings, and
is useful on an error condition to restore output to a known state.  You
should also call math_setfp on errors if you had changed that.

If you wish to mix your own output with numeric output from the math routines,
then you can call math_chr, math_str, math_fill, math_fmt, or math_flush.
These routines output single characters, output null-terminated strings,
output strings with space filling, output formatted strings like printf, and
flush the output.  Output from these routines is diverted as described above.

You can change the default output mode by calling math_setmode, and you can
change the default number of digits printed by calling math_setdigits.  These
routines return the previous values.  The possible modes are described in
zmath.h.

--------------
USING INTEGERS
--------------

The arbitrary precision integer routines define a structure called a ZVALUE.
This is defined in zmath.h.  A ZVALUE contains a pointer to an array of
integers, the length of the array, and a sign flag.  The array is allocated
using malloc, so you need to free this array when you are done with a
ZVALUE.  To do this, you should call zfree with the ZVALUE as an argument
(or call freeh with the pointer as an argument) and never try to free the
array yourself using free.  The reason for this is that sometimes the pointer
points to one of two statically allocated arrays which should NOT be freed.

The ZVALUE structures are passed to routines by value, and are returned
through pointers.  For example, to multiply two small integers together,
you could do the following:

	ZVALUE	z1, z2, z3;

	itoz(3L, &z1);
	itoz(4L, &z2);
	zmul(z1, z2, &z3);

Use zcopy to copy one ZVALUE to another.  There is no sharing of arrays
between different ZVALUEs even if they have the same value, so you MUST
use this routine.  Simply assigning one value into another will cause
problems when one of the copies is freed.  However, the special ZVALUE
values _zero_ and _one_ CAN be assigned to variables directly, since their
values of 0 and 1 are so common that special checks are made for them.

For initial values besides 0 or 1, you need to call itoz to convert a long
value into a ZVALUE, as shown in the above example.  Or alternatively,
for larger numbers you can use the atoz routine to convert a string which
represents a number into a ZVALUE.  The string can be in decimal, octal,
hex, or binary according to the leading digits.

Always make sure you free a ZVALUE when you are done with it or when you
are about to overwrite an old ZVALUE with another value by passing its
address to a routine as a destination value, otherwise memory will be
lost.  The following shows an example of the correct way to free memory
over a long sequence of operations.

	ZVALUE z1, z2, z3;

	z1 = _one_;
	atoz("12345678987654321", &z2);
	zadd(z1, z2, &z3);
	zfree(z1);
	zfree(z2);
	zsquare(z3, &z1);
	zfree(z3);
	itoz(17L, &z2);
	zsub(z1, z2, &z3);
	zfree(z1);
	zfree(z2);
	zfree(z3);

There are some quick checks you can make on integers.  For example, whether
or not they are zero, negative, even, and so on.  These are all macros
defined in zmath.h, and should be used instead of checking the parts of the
ZVALUE yourself.  Examples of such checks are:

	ziseven(z)	(number is even)
	zisodd(z)	(number is odd)
	ziszero(z)	(number is zero)
	zisneg(z)	(number is negative)
	zispos(z)	(number is positive)
	zisunit(z)	(number is 1 or -1)
	zisone(z)	(number is 1)
	zisnegone(z)	(number is -1)
	zistwo(z)	(number is 2)
	zisabstwo(z)	(number is 2 or -2)
	zisabsleone(z)	(number is -1, 0 or 1)
	zislezero(z)	(number is <= 0)
	zisleone(z)	(number is <= 1)
	zge16b(z)	(number is >= 2^16)
	zge24b(z)	(number is >= 2^24)
	zge31b(z)	(number is >= 2^31)
	zge32b(z)	(number is >= 2^32)
	zge64b(z)	(number is >= 2^64)

Typically the largest unsigned long is typedefed to FULL.  The following
macros are useful in dealing with this data type:

	MAXFULL		(largest positive FULL value)
	MAXUFULL	(largest unsigned FULL value)
	zgtmaxfull(z)	(number is > MAXFULL)
	zgtmaxufull(z)	(number is > MAXUFULL)
	zgtmaxlong(z)	(number is > MAXLONG, largest long value)
	zgtmaxulong(z)	(number is > MAXULONG, largest unsigned long value)

If zgtmaxufull(z) is false, then one may quickly convert the absolute
value of number into a full with the macro:

	ztofull(z)	(convert abs(number) to FULL)
	ztoulong(z)	(convert abs(number) to an unsigned long)
	ztolong(z)	(convert abs(number) to a long)

If the value is too large for ztofull(), ztoulong() or ztolong(), only
the low order bits converted.

There are two types of comparisons you can make on ZVALUEs.  This is whether
or not they are equal, or the ordering on size of the numbers.  The zcmp
function tests whether two ZVALUEs are equal, returning TRUE if they differ.
The zrel function tests the relative sizes of two ZVALUEs, returning -1 if
the first one is smaller, 0 if they are the same, and 1 if the first one
is larger.

---------------
USING FRACTIONS
---------------

The arbitrary precision fractional routines define a structure called NUMBER.
This is defined in qmath.h.  A NUMBER contains two ZVALUEs for the numerator
and denominator of a fraction, and a count of the number of uses there are
for this NUMBER.  The numerator and denominator are always in lowest terms,
and the sign of the number is contained in the numerator.  The denominator
is always positive.  If the NUMBER is an integer, the denominator has the
value 1.

Unlike ZVALUEs, NUMBERs are passed using pointers, and pointers to them are
returned by functions.  So the basic type for using fractions is not really
(NUMBER), but is (NUMBER *).  NUMBERs are allocated using the qalloc routine.
This returns a pointer to a number which has the value 1.  Because of the
special property of a ZVALUE of 1, the numerator and denominator of this
returned value can simply be overwritten with new ZVALUEs without needing
to free them first.  The following illustrates this:

	NUMBER *q;

	q = qalloc();
	itoz(55L, &q->num);

A better way to create NUMBERs with particular values is to use the itoq,
iitoq, or atoq functions.  Using itoq makes a long value into a NUMBER,
using iitoq makes a pair of longs into the numerator and denominator of a
NUMBER (reducing them first if needed), and atoq converts a string representing
a number into the corresponding NUMBER.  The atoq function accepts input in
integral, fractional, real, or exponential formats.  Examples of allocating
numbers are:

	NUMBER *q1, *q2, *q3;

	q1 = itoq(66L);
	q2 = iitoq(2L, 3L);
	q3 = atoq("456.78");

Also unlike ZVALUEs, NUMBERs are quickly copied.  This is because they contain
a link count, which is the number of pointers there are to the NUMBER.  The
qlink macro is used to copy a pointer to a NUMBER, and simply increments
the link count and returns the same pointer.  Since it is a macro, the
argument should not be a function call, but a real pointer variable.  The
qcopy routine will actually make a new copy of a NUMBER, with a new link
count of 1.  This is not usually needed.

NUMBERs are deleted using the qfree routine.  This decrements the link count
in the NUMBER, and if it reaches zero, then it will deallocate both of
the ZVALUEs contained within the NUMBER, and then puts the NUMBER structure
onto a free list for quick reuse.  The following is an example of allocating
NUMBERs, copying them, adding them, and finally deleting them again.

	NUMBER *q1, *q2, *q3;

	q1 = itoq(111L);
	q2 = qlink(q1);
	q3 = qqadd(q1, q2);
	qfree(q1);
	qfree(q2);
	qfree(q3);

Because of the passing of pointers and the ability to copy numbers easily,
you might wish to use the rational number routines even for integral
calculations.  They might be slightly slower than the raw integral routines,
but are more convenient to program with.

The prototypes for the fractional routines are defined in qmath.h.
Many of the definitions for integer functions parallel the ones defined
in zmath.h.  But there are also functions used only for fractions.
Examples of these are qnum to return the numerator, qden to return the
denominator, qint to return the integer part of, qfrac to return the
fractional part of, and qinv to invert a fraction.

There are some transcendental functions in the library, such as sin and cos.
These cannot be evaluated exactly as fractions.  Therefore, they accept
another argument which tells how accurate you want the result.  This is an
"epsilon" value, and the returned value will be within that quantity of
the correct value.  This is usually an absolute difference, but for some
functions (such as exp), this is a relative difference.  For example, to
calculate sin(0.5) to 100 decimal places, you could do:

	NUMBER *q, *ans, *epsilon;

	q = atoq("0.5");
	epsilon = atoq("1e-100");
	ans = qsin(q, epsilon);

There are many convenience macros similar to the ones for ZVALUEs which can
give quick information about NUMBERs.  In addition, there are some new ones
applicable to fractions.  These are all defined in qmath.h.  Some of these
macros are:

	qiszero(q)	(number is zero)
	qisneg(q)	(number is negative)
	qispos(q)	(number is positive)
	qisint(q)	(number is an integer)
	qisfrac(q)	(number is fractional)
	qisunit(q)	(number is 1 or -1)
	qisone(q)	(number is 1)
	qisnegone(q)	(number is -1)
	qistwo(q)	(number is 2)
	qiseven(q)	(number is an even integer)
	qisodd(q)	(number is an odd integer)
	qistwopower(q)	(number is a power of 2 >= 1)

The comparisons for NUMBERs are similar to the ones for ZVALUEs.  You use the
qcmp and qrel functions.

There are four predefined values for fractions.  You should qlink them when
you want to use them.  These are _qzero_, _qone_, _qnegone_, and _qonehalf_.
These have the values 0, 1, -1, and 1/2.  An example of using them is:

	NUMBER *q1, *q2;

	q1 = qlink(&_qonehalf_);
	q2 = qlink(&_qone_);

---------------------
USING COMPLEX NUMBERS
---------------------

The arbitrary precision complex arithmetic routines define a structure
called COMPLEX.  This is defined in cmath.h.  This contains two NUMBERs
for the real and imaginary parts of a complex number, and a count of the
number of links there are to this COMPLEX number.

The complex number routines work similarly to the fractional routines.
You can allocate a COMPLEX structure using comalloc (NOT calloc!).
You can construct a COMPLEX number with desired real and imaginary
fractional parts using qqtoc.  You can copy COMPLEX values using clink
which increments the link count.  And you free a COMPLEX value using cfree.
The following example illustrates this:

	NUMBER *q1, *q2;
	COMPLEX *c1, *c2, *c3;

	q1 = itoq(3L);
	q2 = itoq(4L);
	c1 = qqtoc(q1, q2);
	qfree(q1);
	qfree(q2);
	c2 = clink(c1);
	c3 = cmul(c1, c2);
	cfree(c1);
	cfree(c2);
	cfree(c3);

As a shortcut, when you want to manipulate a COMPLEX value by a real value,
you can use the caddq, csubq, cmulq, and cdivq routines.  These accept one
COMPLEX value and one NUMBER value, and produce a COMPLEX value.

There is no direct routine to convert a string value into a COMPLEX value.
But you can do this yourself by converting two strings into two NUMBERS,
and then using the qqtoc routine.

COMPLEX values are always returned from these routines.  To split out the
real and imaginary parts into normal NUMBERs, you can simply qlink the
two components, as shown in the following example:

	COMPLEX *c;
	NUMBER *rp, *ip;

	c = calloc();
	rp = qlink(c->real);
	ip = qlink(c->imag);

There are many macros for checking quick things about complex numbers,
similar to the ZVALUE and NUMBER macros.  In addition, there are some
only used for complex numbers.  Examples of macros are:

	cisreal(c)	(number is real)
	cisimag(c)	(number is pure imaginary)
	ciszero(c)	(number is zero)
	cisnegone(c)	(number is -1)
	cisone(c)	(number is 1)
	cisrunit(c)	(number is 1 or -1)
	cisiunit(c)	(number is i or -i)
	cisunit(c)	(number is 1, -1, i, or -i)
	cistwo(c)	(number is 2)
	cisint(c)	(number is has integer real and imaginary parts)
	ciseven(c)	(number is has even real and imaginary parts)
	cisodd(c)	(number is has odd real and imaginary parts)

There is only one comparison you can make for COMPLEX values, and that is
for equality.  The ccmp function returns TRUE if two complex numbers differ.

There are three predefined values for complex numbers.  You should clink
them when you want to use them.  They are _czero_, _cone_, and _conei_.
These have the values 0, 1, and i.

----------------
LAST THINGS LAST
----------------

If you wish, when you are all doen you can call libcalc_call_me_last()
to free a small amount of storage associated with the libcalc_call_me_first()
call.  This is not required, but is does bring things to a closure.

The function libcalc_call_me_last() takes no args and returns void.  You
need call libcalc_call_me_last() only once.

*************
* new_custom
*************

Calc command line

    Calc has the following command line:

	calc [-C] [-e] [-h] [-i] [-m mode] [-n] [-p] [-q] [-u] [calc_cmd ...]

	-C  Permit the execution of custom builtin functions.  Without
	    this flag, calling the custom() builtin function will
	    simply generate an error.

	    Use if this flag may cause calc to execute functions that
	    are non-standard and that are not portable.  Custom builtin
	    functions are disabled by default for this reason.

	-e  Ignore any environment variables on startup.  The
	    getenv() builtin will still return values, however.

	-h  Print a help message.  This option implies  -q.  This
	    is equivalent to the calc command help help.  The help
	    facility is disabled unless the mode is 5 or 7.  See -m.

	-i  Do not about if the error count exceeds maxerr().

	-m mode
	   This flag sets the permission mode of calc.  It
	   controls the ability for calc to open files and execute
	   programs. Mode may be a number from 0 to 7.

	   The mode value is interpreted in a way similar to that
	   of the chmod(1) octal mode:

		0  do not open any file, do not execute progs
		1  do not open any file
		2  do not open files for reading, do not execute progs
		3  do not open files for reading
		4  do not open files for writing, do not execute progs
		5  do not open files for writing
		6  do not execute any program
		7  allow everything (default mode)

	   If one wished to run calc from a privledged user, one
	   might want to use -m 0 in an effort to make calc more
	   secure.

	   Mode bits for reading and writing apply only on an
	   open.  Files already open are not effected. Thus if one
	   wanted to use the -m 0 in an effort to make calc more
	   secure, but still wanted to read and write a specific
	   file, one might want to do:

		     calc -m 0 3<a.file

	   Files presented to calc in this way are opened in an
	   unknown mode. Calc will attempt to read or write them
	   if directed.

	   If the mode disables opening of files for reading, then
	   the startup library scripts are disabled as of -q was
	   given.  The reading of key bindings is also disabled
	   when the mode disables opening of files for reading.

	-n  Use the new configutation defaults instead of the old
	    default classic defaults.  This flag as the same effect
	    as executing config("all", "newcfg") at startup time.

	-p  Pipe processing is enabled by use of -p.  For example:

		     echo "print 2^21701-1, 2^23209-1" | calc -p | fizzbin

	    In pipe mode, calc does not prompt, does not print
	    leading tabs and does not print the initial header.

	-q  Disable the use of the $CALCRC startup scripts.

	-u  Disable buffering of stdin and stdout.

    Without `calc_cmd', calc operates interactively.  If one or more
    `calc_cmd' are given on the command line, calc will execute them and
    exit.  The printing of leading tabs on output is disabled as if
    config("tab",0) had been executed.

    Normally on startup, calc attempts to execute a collection of
    library scripts.  The environment variable $CALCRC (if non-existent
    then a compiled in value) contains a :  separated list of startup
    library scripts.  No error conditions are produced if these startup
    library scripts are not found.

    If the mode disables opening of files for reading, then the startup
    library scripts are disabled as of -q was given and $CALCRC as well
    as the default compiled in value are ignored.

    Filenames are subject to ``~'' expansion (see below).  The
    environment variable $CALCPATH (if non-existent then a compiled in
    value) contains a : separated list of search directories.  If a
    file does not begin with /, ~ or ./, then it is searched for under
    each directory listed in the $CALCPATH.  It is an error if no such
    readable file is found.

    Calc treats all open files, other than stdin, stdout and
    stderr as files available for reading and writing. One may
    present calc with an already open file in the following way:

        calc 3<open_file 4<open_file2

    For more information use the following calc commands:

       help help
       help overview
       help usage
       help environment
       help config

*************
* stdlib
*************

# Copyright (c) 1997 David I. Bell and Landon Curt Noll
# Permission is granted to use, distribute, or modify this source,
# provided that this copyright notice remains intact.

The following calc library files are provided because they serve as
examples of how use the calc language, and/or because the authors thought
them to be useful!

If you write something that you think is useful, please send it to:

    dbell@auug.org.au
    chongo@toad.com                 {uunet,pyramid,sun}!hoptoad!chongo

By convention, a lib file only defines and/or initializes functions,
objects and variables.  (The regression test is an exception.)  Also by
convention, the a usage message regarding each important object and
function is printed at the time of the read.

If a lib file needs to load another lib file, it should use the -once
version of read:

    /* pull in needed library files */
    read -once "surd"
    read -once "lucas"

This will cause the needed library files to be read once.  If these
files have already been read, the read -once will act as a noop.

By convention, the config parameter "lib_debug"  is used to control
the verbosity of debug information printed by lib files.  By default,
the "lib_debug" has a value of 0.

The "lib_debug" config parameter takes the place of the lib_debug
global variable.  By convention, "lib_debug" has the following meanings:

	<-1	no debug messages are printed though some internal
		    debug actions and information may be collected

	-1	no debug messages are printed, no debug actions will be taken

	0	only usage message regarding each important object are
		    printed at the time of the read (default)

	>0	messages regarding each important object are
		    printed at the time of the read in addition
		    to other debug messages

To conform to the above convention, your lib files should end with
lines of the form:

	if (config("lib_debug") >= 0) {
		print "obj xyz defined";
		print "funcA(side_a, side_b, side_c) defined";
		print "funcB(size, mass) defined";
	}


=-=

beer.cal

    Calc's contribution to the 99 Bottles of Beer web page:

	http://www.ionet.net/~timtroyr/funhouse/beer.html#calc


bernoulli.cal

    B(n)

    Calculate the nth Bernoulli number.


bigprime.cal

    bigprime(a, m, p)

    A prime test, base a, on p*2^x+1 for even x>m.


chrem.cal

    chrem(r1,m1 [,r2,m2, ...])
    chrem(rlist, mlist)

    Chinese remainder theorem/problem solver.


deg.cal

    dms(deg, min, sec)
    dms_add(a, b)
    dms_neg(a)
    dms_sub(a, b)
    dms_mul(a, b)
    dms_print(a)

    Calculate in degrees, minutes, and seconds.


ellip.cal

    factor(iN, ia, B, force)

    Attempt to factor using the elliptic functions: y^2 = x^3 + a*x + b.


hello.cal

    Calc's contribution to the Hello World! page:

	http://www.latech.edu/~acm/HelloWorld.shtml
	http://www.latech.edu/~acm/helloworld/calc.html


lucas.cal

    lucas(h, n)

    Perform a primality test of h*2^n-1, with 1<=h<2*n.


lucas_chk.cal

    lucas_chk(high_n)

    Test all primes of the form h*2^n-1, with 1<=h<200 and n <= high_n.
    Requires lucas.cal to be loaded.  The highest useful high_n is 1000.

    Used by regress.cal during the 2100 test set.


lucas_tbl.cal

    Lucasian criteria for primality tables.


mersenne.cal

    mersenne(p)

    Perform a primality test of 2^p-1, for prime p>1.


mfactor.cal

    mfactor(n [, start_k=1 [, rept_loop=10000 [, p_elim=17]]])

    Return the lowest factor of 2^n-1, for n > 0.  Starts looking for factors
    at 2*start_k*n+1.  Skips values that are multiples of primes <= p_elim.
    By default, start_k == 1, rept_loop = 10000 and p_elim = 17.

    The p_elim == 17 overhead takes ~3 minutes on an 200 Mhz r4k CPU and
    requires about ~13 Megs of memory.  The p_elim == 13 overhead
    takes about 3 seconds and requires ~1.5 Megs of memory.

    The value p_elim == 17 is best for long factorizations.  It is the
    fastest even thought the initial startup overhead is larger than
    for p_elim == 13.

mod.cal

    mod(a)
    mod_print(a)
    mod_one()
    mod_cmp(a, b)
    mod_rel(a, b)
    mod_add(a, b)
    mod_sub(a, b)
    mod_neg(a)
    mod_mul(a, b)
    mod_square(a)
    mod_inc(a)
    mod_dec(a)
    mod_inv(a)
    mod_div(a, b)
    mod_pow(a, b)

    Routines to handle numbers modulo a specified number.


natnumset.cal

    isset(a)
    setbound(n)
    empty()
    full()
    isin(a, b)
    addmember(a, n)
    rmmember(a, n)
    set()
    mkset(s)
    primes(a, b)
    set_max(a)
    set_min(a)
    set_not(a)
    set_cmp(a, b)
    set_rel(a, b)
    set_or(a, b)
    set_and(a, b)
    set_comp(a)
    set_setminus(a, b)
    set_diff(a,b)
    set_content(a)
    set_add(a, b)
    set_sub(a, b)
    set_mul(a, b)
    set_square(a)
    set_pow(a, n)
    set_sum(a)
    set_plus(a)
    interval(a, b)
    isinterval(a)
    set_mod(a, b)
    randset(n, a, b)
    polyvals(L, A)
    polyvals2(L, A, B)
    set_print(a)

    Demonstration of how the string operators and functions may be used
    for defining and working with sets of natural numbers not exceeding a
    user-specified bound.


pell.cal

    pellx(D)
    pell(D)

    Solve Pell's equation; Returns the solution X to: X^2 - D * Y^2 = 1.
    Type the solution to pells equation for a particular D.


pi.cal

    qpi(epsilon)

    Calculate pi within the specified epsilon using the quartic convergence
    iteration.


pix.cal

    pi_of_x(x)

    Calculate the number of primes < x using A(n+1)=A(n-1)+A(n-2).  This
    is a SLOW painful method ... the builtin pix(x) is much faster.
    Still, this method is interesting.


pollard.cal

    factor(N, N, ai, af)

    Factor using Pollard's p-1 method.


poly.cal

    Calculate with polynomials of one variable.  There are many functions.
    Read the documentation in the library file.


prompt.cal

    adder()
    showvalues(str)

    Demonstration of some uses of prompt() and eval().


psqrt.cal

    psqrt(u, p)

    Calculate square roots modulo a prime


quat.cal

    quat(a, b, c, d)
    quat_print(a)
    quat_norm(a)
    quat_abs(a, e)
    quat_conj(a)
    quat_add(a, b)
    quat_sub(a, b)
    quat_inc(a)
    quat_dec(a)
    quat_neg(a)
    quat_mul(a, b)
    quat_div(a, b)
    quat_inv(a)
    quat_scale(a, b)
    quat_shift(a, b)

    Calculate using quaternions of the form: a + bi + cj + dk.  In these
    functions, quaternians are manipulated in the form: s + v, where
    s is a scalar and v is a vector of size 3.


randbitrun.cal

    randbitrun([run_cnt])

    Using randbit(1) to generate a sequence of random bits, determine if
    the number and kength of identical bits runs match what is expected.
    By default, run_cnt is to test the next 65536 random values.

    This tests the a55 generator.


randmprime.cal

    randmprime(bits, seed [,dbg])

    Find a prime of the form h*2^n-1 >= 2^bits for some given x.  The initial
    search points for 'h' and 'n' are selected by a cryptographic pseudo-random
    number generator.  The optional argument, dbg, if set to 1, 2 or 3
    turn on various debugging print statements.


randombitrun.cal

    randombitrun([run_cnt])

    Using randombit(1) to generate a sequence of random bits, determine if
    the number and kength of identical bits runs match what is expected.
    By default, run_cnt is to test the next 65536 random values.

    This tests the Blum-Blum-Shub generator.


randomrun.cal

    randomrun([run_cnt])

    Perform the "G. Run test" (pp. 65-68) as found in Knuth's "Art of
    Computer Programming - 2nd edition", Volume 2, Section 3.3.2 on
    the builtin rand() function.  This function will generate run_cnt
    64 bit values.  By default, run_cnt is to test the next 65536
    random values.

    This tests the Blum-Blum-Shub generator.


randrun.cal

    randrun([run_cnt])

    Perform the "G. Run test" (pp. 65-68) as found in Knuth's "Art of
    Computer Programming - 2nd edition", Volume 2, Section 3.3.2 on
    the builtin rand() function.  This function will generate run_cnt
    64 bit values.  By default, run_cnt is to test the next 65536
    random values.

    This tests the a55 generator.


regress.cal

    Test the correct execution of the calculator by reading this library file.
    Errors are reported with '****' mssages, or worse.  :-)


seedrandom.cal

    seedrandom(seed1, seed2, bitsize [,trials])

    Given:
	seed1 - a large random value (at least 10^20 and perhaps < 10^93)
	seed2 - a large random value (at least 10^20 and perhaps < 10^93)
 	size - min Blum modulus as a power of 2 (at least 100, perhaps > 1024)
	trials - number of ptest() trials (default 25) (optional arg)

    Returns:
	the previous random state

    Seed the cryptographically strong Blum generator.  This functions allows
    one to use the raw srandom() without the burden of finding appropriate
    Blum primes for the modulus.


solve.cal

    solve(low, high, epsilon)

    Solve the equation f(x) = 0 to within the desired error value for x.
    The function 'f' must be defined outside of this routine, and the low
    and high values are guesses which must produce values with opposite signs.


sumsq.cal

    ss(p)

    Determine the unique two positive integers whose squares sum to the
    specified prime.  This is always possible for all primes of the form
    4N+1, and always impossible for primes of the form 4N-1.


surd.cal

    surd(a, b)
    surd_print(a)
    surd_conj(a)
    surd_norm(a)
    surd_value(a, xepsilon)
    surd_add(a, b)
    surd_sub(a, b)
    surd_inc(a)
    surd_dec(a)
    surd_neg(a)
    surd_mul(a, b)
    surd_square(a)
    surd_scale(a, b)
    surd_shift(a, b)
    surd_div(a, b)
    surd_inv(a)
    surd_sgn(a)
    surd_cmp(a, b)
    surd_rel(a, b)

    Calculate using quadratic surds of the form: a + b * sqrt(D).


test1700.cal

    value

    This script is used by regress.cal to test the read and use keywords.


test2600.cal

    global defaultverbose
    global err
    testismult(str, n, verbose)
    testsqrt(str, n, eps, verbose)
    testexp(str, n, eps, verbose)
    testln(str, n, eps, verbose)
    testpower(str, n, b, eps, verbose)
    testgcd(str, n, verbose)
    cpow(x, n, eps)
    cexp(x, eps)
    cln(x, eps)
    mkreal()
    mkcomplex()
    mkbigreal()
    mksmallreal()
    testappr(str, n, verbose)
    checkappr(x, y, z, verbose)
    checkresult(x, y, z, a)
    test2600(verbose, tnum)

    This script is used by regress.cal to test some of builtin functions
    in terms of accuracy and roundoff.


test2700.cal

    global defaultverbose
    mknonnegreal()
    mkposreal()
    mkreal_2700()
    mknonzeroreal()
    mkposfrac()
    mkfrac()
    mksquarereal()
    mknonsquarereal()
    mkcomplex_2700()
    testcsqrt(str, n, verbose)
    checksqrt(x, y, z, v)
    checkavrem(A, B, X, eps)
    checkrounding(s, n, t, u, z)
    iscomsq(x)
    test2700(verbose, tnum)

    This script is used by regress.cal to test sqrt() for real and complex
    values.


test3100.cal

    obj res
    global md
    res_test(a)
    res_sub(a, b)
    res_mul(a, b)
    res_neg(a)
    res_inv(a)
    res(x)

    This script is used by regress.cal to test determinants of a matrix


test3300.cal

    global defaultverbose
    global err
    testi(str, n, N, verbose)
    testr(str, n, N, verbose)
    test3300(verbose, tnum)

    This script is used by regress.cal to provide for more determinant tests.


test3400.cal

    global defaultverbose
    global err
    test1(str, n, eps, verbose)
    test2(str, n, eps, verbose)
    test3(str, n, eps, verbose)
    test4(str, n, eps, verbose)
    test5(str, n, eps, verbose)
    test6(str, n, eps, verbose)
    test3400(verbose, tnum)

    This script is used by regress.cal to test trig functions.
    containing objects.

test4000.cal

    global defaultverbose
    global err
    global BASEB
    global BASE
    global COUNT
    global SKIP
    global RESIDUE
    global MODULUS
    global K1
    global H1
    global K2
    global H2
    global K3
    global H3
    plen(N) defined
    rlen(N) defined
    clen(N) defined
    ptimes(str, N, n, count, skip, verbose) defined
    ctimes(str, N, n, count, skip, verbose) defined
    crtimes(str, a, b, n, count, skip, verbose) defined
    ntimes(str, N, n, count, skip, residue, mod, verbose) defined
    testnextcand(str, N, n, cnt, skip, res, mod, verbose) defined
    testnext1(x, y, count, skip, residue, modulus) defined
    testprevcand(str, N, n, cnt, skip, res, mod, verbose) defined
    testprev1(x, y, count, skip, residue, modulus) defined
    test4000(verbose, tnum) defined

    This script is used by regress.cal to test ptest, nextcand and
    prevcand buildins.

test4100.cal

    global defaultverbose
    global err
    global K1
    global K2
    global BASEB
    global BASE
    rlen_4100(N) defined
    olen(N) defined
    test1(x, y, m, k, z1, z2) defined
    testall(str, n, N, M, verbose) defined
    times(str, N, n, verbose) defined
    powtimes(str, N1, N2, n, verbose) defined
    inittimes(str, N, n, verbose) defined
    test4100(verbose, tnum) defined

    This script is used by regress.cal to test REDC operations.

test4600.cal

    stest(str [, verbose]) defined
    ttest([m, [n [,verbose]]]) defined
    sprint(x) defined
    findline(f,s) defined
    findlineold(f,s) defined
    test4600(verbose, tnum) defined

    This script is used by regress.cal to test searching in files.

test5100.cal

    global a5100
    global b5100
    test5100(x) defined

    This script is used by regress.cal to test the new code generator
    declaration scope and order.

test5200.cal

    global a5200
    static a5200
    f5200(x) defined
    g5200(x) defined
    h5200(x) defined

    This script is used by regress.cal to test the fix of a global/static bug.

unitfrac.cal

    unitfrac(x)

    Represent a fraction as sum of distinct unit fractions.


varargs.cal

    sc(a, b, ...)

    Example program to use 'varargs'.  Program to sum the cubes of all
    the specified numbers.

xx_print.cal

    isoctet(a) defined
    list_print(a) defined
    mat_print (a) defined
    octet_print(a) defined
    blk_print(a) defined
    nblk_print (a) defined
    strchar(a) defined
    file_print(a) defined
    error_print(a) defined

    Demo for the xx_print object routines.

*************
* archive
*************

Where to get the the latest versions of calc

    Landon Noll maintains the official calc ftp archive at:

	ftp://ftp.uu.net/pub/calc

    Alpha test versions, complete with bugs, untested code and
    experimental features may be fetched (if you are brave) under:

	http://reality.sgi.com/chongo/calc/

    One may join the calc testing group by sending a request to:

	calc-tester-request@postofc.corp.sgi.com

    Your message body (not the subject) should consist of:

	subscribe calc-tester address
	end
	name your_full_name

    where "address" is your EMail address and "your_full_name"
    is your full name.

    See:

	http://prime.corp.sgi.com/csp/ioccc/noll/noll.html#calc

    for details.

Landon Curt Noll <chongo@toad.com> /\oo/\

*************
* bugs
*************

If you notice something wrong, strange or broken, try rereading:

   README.FIRST
   README
   BUGS (in particular the bottom problems or mis-features section)

If that does not help, cd to the calc source directory and try:

   make check

Look at the end of the output, it should say something like:

    9998: passed all tests  /\../\
    9999: Ending regression tests

If it does not, then something is really broken!

If you made and modifications to calc beyond the simple Makefile
configuration, try backing them out and see if things get better.

Check to see if the version of calc you are using is current.  Calc
distributions may be obtained from the official calc repository:

    ftp://ftp.uu.net/pub/calc

If you are an alpha or beta tester, you may have a special pre-released
version that is more advanced than what is in the ftp archive.

=-=

If you have tried all of the above and things still are not right,
then it may be time to send in a bug report.  You can send bug reports to:

    calc-tester@postofc.corp.sgi.com

When you send your report, please include the following information:

    * a description of the problem

    * the version of calc you are using (if you cannot get calc
      it to run, then send us the 4 #define lines from version.c)

    * if you modified calc from an official patch, send me the mods you made

    * the type of system you were using

    * the type of compiler you were using

    * cd to the calc source directory, and type:

	make debug > debug.out 2>&1		(sh, ksh, bash users)
	make debug >& debug.out			(csh, tcsh users)

      and send the contents of the 'debug.out' file.

Stack traces from core dumps are useful to send as well.

=-=

The official calc repository is located in:

    ftp://ftp.uu.net/pub/calc

If you don't have ftp access to that site, or if your version is more
recent than what has been released to the ftp archive, you may, as a
last resort, send EMail to:

    chongo@toad.com

Indicate the version you have and that you would like a more up to date version.

=-=

Send any comments, suggestions and most importantly, fixes (in the form
of a context diff patch) to:

    calc-tester@postofc.corp.sgi.com

=-=

Known problems or mis-features:

    * Many of and SEE ALSO sections of help files
      for builtins are either inconsistent or missing information.

    * Many of the LIBRARY sections are incorrect now that libcalc.a
      contains most of the calc system.

    * There is some places in the source with obscure variable names
      and not much in the way of comments.  We need some major cleanup
      and documentation.

*************
* changes
*************

Following is the change from calc version 2.10.3t5.38 to date:

    Fixed a bug discovered by Ernest Bowen related to matrix-to-matrix copies.

    Bitwise operations on integers have been extended so that negative
    integers are treated in the same way as the integer types in C.

    Some changes have been made to lib/regress.cal and lib/natnumset.cal.

    Removed V_STRLITERAL and V_STRALLOC string type constants and
    renumbered the V_protection types.

    Added popcnt(x, bitval) builtin which counts the number of
    bits in x that match bitval.

    Misc compiler warning fixes.

    Fixed improper use of putchar() and printf() when printing rationals
    (inside qio.c).

    Fixed previously reported bug in popcnt() in relation to . values.

    Calc man page changes per suggestion from Martin Buck
    <Martin-2.Buck@student.uni-ulm.de>.  The calc man page is
    edited with a few more parameters from the Makefile.

    Misc Makefile changes per Martin Buck <Martin-2.Buck@student.uni-ulm.de>.

    Removed trailing blanks from files.

    Consolidated in the Makefile, where the debug and check rules are found.
    Fixed the regress.cal dependency list.

    Make chk and check will exit with an error if check.awk detects
    a problem in the regression output.  (Martin Buck)

    Fixed print line for test #4404.

    Moved custom.c and custom.h to the upper level to fix unresolved symbols.

    Moved help function processing into help.c.

    Moved nearly everything into libcalc.a to allow programs access to
    higher level calc objects (e.g., list, assoc, matrix, block, ...).

    Renamed PATCH_LEVEL to MAJOR_PATCH and SUB_PATCH_LEVEL to MINOR_PATCH.
    Added integers calc_major_ver, calc_minor_ver, calc_major_patch
    and string calc_minor_patch to libcalc.a.  Added CALC_TITLE to hold
    the "C-style arbitrary precision calculator" string.

    The function version(), now returns a malloced version string
    without the title.


Following is the change from calc version 2.10.3t5.34 to 2.10.3t5.37:

    Per request from David I Bell, the README line:

      I am allowing this calculator to be freely distributed for personal uses

    to:

      I am allowing this calculator to be freely distributed for your enjoyment

    Added help files for:

	address agd arrow dereference free freeglobals freeredc freestatics
	gd isptr mattrace oldvalue saveval & * -> and .

    Fixed blkcpy() and copy() arg order and processing.  Now:

	A = blk() = {1,2,3,4}
	B = blk()
	blkcpy(B,A)
	blkcpy(B,A)

    will result in B being twice as long as A.

    Since "make chk" pipes the regression output to awk, we cannot
    assume that stdout and stderr are ttys.  Tests #5985 and #5986
    have been removed for this reason.  (thanks to Martin Buck
    <Martin-2.Buck@student.uni-ulm.de> for this report)

    Fixed the order of prints in regress.cal.  By convention, a print
    of a test line happens after the test.  This is because function
    parsed messages occur after the function is parsed.  Also the
    boolean tesrt of vrfy happens before any print statement.
    Therefore a non-test line is tested and printed as follows:

	y = sha();
	print '7125: y = sha()';

    The perm(a,b) and comb(a,b) have been extented to arbitrary real a and
    integer b.

    Fixed a bug in minv().

    Moved string.c into libcalc.a.

    The NUMBER union was converted back into a flat structure.  Changes
    where 'num' and 'next' symbols were changed to avoid #define conflicts
    were reverse since the #define's needed to support the union went away.

    Removed trailing blanks from files.

    Ernest Bowen <ernie@turing.une.edu.au> sent in the following patch
    which is described in the next 34 points:

    (0) In the past:

		    A = B = strcat("abc", "def");

	would store "abc" and "def" as literal strings never to be freed, and
	store "abcdef" once each for both A and  B.  Now the "abc" and "bcd"
	are freed immediately after they are concatenated and "abcdef" is stored
	only once, just as the number 47 would be stored only once for

		    A = B = 47;

	The new STRING structure that achieves this stores not only the
	address of the first character in the string, but also the "length"
	with which the string was created, the current "links" count, and
	when links == 0 (which indicates the string has been freed) the
	address of the next freed STRING.  Except for the null string "",
	all string values are "allocated"; the concept of literal string
	remains for names of variables, object types and elements, etc.

    (1) strings may now include '\0', as in A = "abc\0def".  In normal printing
	this prints as "abc" and strlen(A) returns 3, but its "real" length
	of 7 is given by size(A). (As before there is an 8th zero character
	and sizeof(A) returns 8.)

    (2) If A is an lvalue whose current value is a string of size n, then
	for 0 <= i < n, A[i] returns the character with index i as an addressed
	octet using the same structure as for blocks, i.e. there is no
	distinction between a string-octet and a block-octet.  The same
	operations and functions can be used for both, and as before, an octet
	is in some respects a number in [0,256) and in others a one-character
	string.  For example, for A = "abc\0def" one will have both A[0] == "a"
	and A[0] == 97.  Assignments to octets can be used to change
	characters in the string, e.g. A[0] = "A", A[1] = 0, A[2] -= 32,
	A[3] = " " will change the above A to "A\0C def".

    (3) "show strings" now displays the indices, links, length, and some or all
	of the early and late characters in all unfreed strings which are values
	of lvalues or occur as "constants" in function definitions,
	using "\n", "\t", "\0", "\252", etc. when appropriate.  For example,
	the string A in (1) would be displayed as in the definition there.
	Only one line is used for each string.  I've also changed the
	analogous "show numbers" so that only some digits of numbers that
	would require more than one line are displayed.

    (4) "show literals" is analogous to "show constants" for number "constants"
	in that it displays only the strings that have been introduced by
	literal strings as in A = "abc".  There is a major difference between
	strings and numbers in that there are operations by which characters
	in any string may be changed.  For example, after A = "abc",
	A[0] = "X" changes A to "Xbc".  It follows that if a literal string
	is to be constant in the sense of never changing, such a character-
	changing operation should never be applied to that string.

	In this connection, it should be noted that if B is string-valued, then

			    A = B

	results in A referring to exactly the same string as B rather than to
	a copy of what is in B.  Thie is like the use of character-pointers in
	C, as in

			    char *s1, *s2;
			    s1 = "abc";
			    s2 = s1;

	To achieve the effect of

			    s2 = (char *) malloc(4);
			    strcpy(s2, s1);

	I have extended the str() function to accept a string as argument.  Then

			    A = str(B);

	will create a new string at a different location from that of B but
	with the same length and characters.  One will then have A == B,
	*A == *B, but &*A != &*B, &A[0] != &B[0].

	To assist in analyzing this sort of thing, I have defined a links()
	function which for number or string valued argument returns the number
	of links to the occurrence of that argument that is being referred to.
	For example, supposing "abc" has not been used earlier:

			    > A = "abc"
			    > links(A)
				    2
			    > links(A)
				    1

	The two links in the first call are to A and the current "oldvalue";
	in the second call, the only link is to A, the oldvalue now being 2.


    (5) strcat(S1, S2, ...) works as before; contribution of a string stops when
	'\0' is encountered.  E.g.

		    strcat("abc\0def", "ghi")

	will return "abcghi".

    (6) For concatenation of full strings I have chosen to follow
	some other languages (like Java, but not Mathematica which uses "<>")
	and use "+" so that, e.g.

		    "abc\0def" + "ghi"

	returns the string "abc\0defghi".  This immediately gives obvious
	meanings to multiplication by positive integers as in

		    2 * "abc" = "abc" + "abc" = "abcabc",

	to negation to reverse as string as in

		    - "abc" = "cba",

	to multiplication by fractions as in

		    0.5 * "abcd" = "ab",

	(where the length is int(0.5 * size("abcd")), and finally, by combining
	these to

		     k * A    and      A * k

	for any real number k and any string A.   In the case of k == 1, these
	return a new string rather than A itself.  (This differs from
	"" + A and A + "" which return A.)

    (7) char(x) has been changed so that it will accept any integer x or octet
	as argument and return a string of size one with character value
	x % 256.  In the past calc has required 0 <= x < 256; now negative
	x is acceptable; for example, 1000 * char(-1) will now produce the
	same as 1000 * "\377" or 1000 * "\xff".

    (8) For a string s, test(s) now returns zero not only for the null string
	"" but also for a string all of whose characters are '\0'.

    (9) Similarly <, <=, etc. now compare all characters including occurrences
	of '\0' until a difference is encountered or the end of a string is
	reached.  If no difference is encountered but one string is longer than
	the other, the longer string is considered as greater even if the
	remaining characters are all '\0'.

    (10) To retain the C sense of comparison of null-terminated strings I have
	 defined strcmp(S1, S2), and then, for completeness, strncmp(S1, S2, n).
	 For similar reasons, strcpy(S1, S2) and strncpy(S1, S2, n) have been
	 defined.

    (11) For strings, I have defined | and & as bitwise "or" and "and"
	 functions, with S1 | S2 having the size of the larger of S1 and S2,
	 S1 & S2 having the size of the smaller of S1 and S2.  By using, say,
	 4-character strings, one can simulate a C integral type so far as the
	 | and & operations are concerned.   It then seemed appropriate to
	 use the operator ~ for a "bitwise complement" as in C.  Thus I have
	 defined ~s for a string s to be the string of the same size as s
	 with each character being complemented by the C ~ operation.

    (12) For boolean algebra work on strings it is convenient also to have
	 the bitwise xor and setminus binary operations.  Using C's '^' for xor
	 would be confusing when this is used elsewhere for powers, so I
	 decided to use ~.  For setminus, I adopted the commonly used '\'.
	 Strings of fixed size n can now be used for a boolean algebra
	 structure with 8 * n elements.  The zero element is n * char(0),
	 the unity is n * char(-1), and one have all of the usual laws like
	 A & (B | C) == A & B | A * C,  A \ B = A & ~B, etc.

    (13) Having extended the bitwise operations for strings, it was appropriate
	 to do the same for integers.  Definitions of the binary ~ and \
	 operations for non-negative integers are straightforward.  For
	 the unary ~ operation, I decided to do what C does with integer
	 types, and defined ~N to be -N - 1.  With the appropriate extensions of
	 |, &, \ and the binary ~, one gets in effect the boolean algebra of
	 finite sets of natural numbers and their complements, by identifying
	 the set with distinct integer elements i_1, i_2, ... with the integer

		    2^i_1 + 2^i_2 + ...

	 For ~N for non-integer real N, I have simply used -N.  There is some
	 logic in this and it is certainly better than an error value.
	 I have not defined the binary operations |, &, ~, \ for non-integral
	 arguments.

	 The use of ~N in this way conflicts with calc's method of displaying
	 a number when it has to be rounded to config("display") decimals.
	 To resolve this, my preference would be to replace the printing of
	 "~" as a prefix by a trailing ellipsis "...", the rounding always
	 being towards zero.  E.g. with config("display", 5), 1/7 would print
	 as ".14285..." rather than "~.14285".   The config("outround")
	 parameter would determine the type of rounding only for the
	 equivalent of config("tilde", 0).

    (14) For objects, users may create their own definitions for binary |,
	 &, ~ and \ with xx_or, xx_and, xx_xor, xx_setminus functions.
	 For unary ~ and \ operations, I have used the names xx_comp and
	 xx_backslash.

    (15) For the obviously useful feature corresponding to cardinality of a
	 set, I have defined #S for a string S to be the number of nonzero bits
	 in S.   For a degree of consistency, it was then appropriate to
	 define #N for a nonnegative integer N to be the number of nonzero bits
	 in the binary representation of N.  I've extended this to arbitrary
	 real N by using in effect #(abs(num(N))).  I feel it is better to make
	 this available to users rather than having #N invoke an error message
	 or return an error value.  For defining #X for an xx-object X, I
	 have used the name xx_content to suggest that it is appropriate for
	 something which has the sense of a content (like number of members of,
	 area, etc.).

    (16) Having recognized # as a token, it seemed appropriate to permit its
	 use for a binary operation.  For real numbers x and y I have defined
	 x # y to be abs(x - y).  (This is often symbolized by x ~ y, but it
	 would be confusing to have x ~ y meaning xor(x,y) for strings and
	 abs(x-y) for numbers.)  Because '#' is commonly called the hash symbol,
	 I have used xx_hashop to permit definition of x # y for xx-objects.

    (17) For a similar reason I've added one line of code to codegen.c so that
	 /A returns the inverse of A.

    (18) Also for a list L, +L now returns the sum of the elements of L.  For
	 an xx object A, +A requires and uses the definition of xx_plus.

    (19) I have given the unary operators ~, #, /, \, and except at the
	 beginning of an expression + and -, the same precedence with
	 right-to-left associativity.  This precedence is now weaker than
	 unary * and &, but stronger than binary & and the shift and power
	 operators.  One difference from before is that now

			    a ^ - b ^ c

	 evaluates as a ^ (- (b ^ c)) rather than a ^ ((- b) ^ c).


    (20) For octets o1, o2, I've defined o1 | o2, o1 & o2, o1 ~ o2, ~o1 so
	 that they return 1-character strings.  #o for an octet o returns the
	 number of nonzero bits in o.

    (21) For substrings I've left substr() essentially as before, but
	 for consistency with the normal block/matrix indexing, I've extended
	 the segment function to accept a string as first argument.  Then

		    segment(A, m, n)

	 returns essentially the string formed from the character with index m
	 to the character with index n, ignoring indices < 0 and indices >=
	 len(A); thus, if m and n are both in [0, size(A))
	 the string is of length abs(m - n) + 1, the order of the characters
	 being reversed if n < m.  Here the indices for a list of size len are
	 0, 1, ..., len - 1.  As it makes some sense, if 0 <= n < size(A),

		    segment(A, n)

	 now returns the one-character string with its character being that with
	 index n in A.  (I've made a corresponding modification to the segment
	 function for lists.)  Some examples, if A = "abcdef",

		    segment(A,2,4) = "cde",

		    segment(A,4,2) = "edc",

		    segment(A,3) = "d",

		    segment(A, -2, 8) = "abcdef",

		    segment(A,7,8) = "".

    (22) As essentially particular cases of segment(), I've defined
	 head(A, n) and tail(A, n) to be the strings formed by the first
	 or last abs(n) characters of A, the strings being4]5O~? reversed '
	 if n is negative.   I've changed the definitions of head and tail for
	 lists to be consistent with this interpretation of negative n.

    (23) Similarly I've left strpos ezsentially as at present, but search
	 and rsearch have been extended to strings.  For example,

		    search(A, B, m, n)

	 returns the index i of the first occurrence of the string B in A
	 if m <= i < n, or the null value if there is no such occurrence.
	 As for other uses of search, negative m is interpreted as
	 size(A) + m, negative n as size(A) + n.  For a match in this
	 search, all size(B) characters, including occurrences of '\0',
	 in B must match successive characters in A.

	 The function rsearch() behaves similarly but searches in reverse order
	 of the indices.

    (24) A string A of length N determines in obvious ways arrays of M = 8 * N
	 bits.  If the characters in increasing index order are c_0, c_1, ...
	 and the bits in increasing order in c_i are b_j, b_j+1, ..., b_j+7
	 where j = 8 * i, I've taken the array of bits determined by A to be

		    b_0, b_1, ..., b_M-1

	 For example, since "a" = char(97) and 97 = 0b01100001, and
	 "b" = char(98) = 0b01100010, the string "ab" determines the 16-bit
	 array

		    1000011001000110

	 in which the bits in the binary representations of "a" and "b" have
	 been reversed.

	 bit with index n in this array.   This is consistent with the use of
	 bit for a number ch in [0,256), i.e. bit(char(ch), n) = bit(ch, n).
	 For n < 0 or n >= size(A), bit(A,n) returns the null value.

    (25) For assigning values to specified bits in a string, I've defined
	 setbit(A, n) and setbit(A, n, v).  The first assigns the value 1 to
	 bit(A, n), the second assigns test(v) to bit(A, n).

    (26) For consistency with the corresponding number operations, the shift
	 operations A << n and A >> n have been defined to give what look
	 like right- and left-shifts, respectively.  For example, "ab" << 2
	 returns the 16-bit array

		    0010000110010001

	 in which the array for "ab" has been moved 2 bits to the right.

    (27) To achieve much the same as the C strcpy and strncpy functions for
	 null-terminated strings, strcpy(S1, S2) and strncpy(S1, S2, n) have
	 been defined.  Unlike the blkcpy() and copy() functions, the copying
	 for these is only from the beginning of the strings.  Also, unlike C,
	 no memory overflow can occur as the copying ceases when size(S1) is
	 reached.  Note that these overwrite the content of S1 (which affects
	 all strings linked to it) as well as returning S1.  Examples:

	    S = strcpy(6 * "x", "abc")      <=>  S = "abc\0xx"

	    S = strcpy(3 * "x", "abcdef")   <=>  S = "abc"

	    S = strncpy(6 * "x", "abcd", 2) <=>  S = "ab\0xxx"

	    S = strncpy(6 * "x", "ab", 4)   <=>  S = "ab\0\0xx"

	    S = strncpy(6 * "x", "ab", 20)  <=>  S = "ab\0\0\0\0"

	 If a new string S not linked to S1 is to be created, this can be
	 achieved by using str(S1) in place of S1.  For example, the strcpy in

	    A = "xxxxxx"
	    S = strcpy(str("xxxxxx"), "abc")

	 would not change the value of A.

    (28) I've extended the definitions of copy(A, B, ssi, num, dsi) and
	 blkcpy(B, A, num, ssi, dsi) to allow for string-to-string copying
	 and block-to-string copying, but num is now an upper bound for the
	 number of characters to be copied - copying will cease before num
	 characters are copied if the end of the data in the source A or the
	 end of the destination B is reached.  As with other character-changing
	 operations, copying to a string B will not change the locations of
	 B[0], B[1], ... or the size of B.

	 In the case of copying a string to itself, characters are copied in
	 order of increasing index, which is different from block-to-block
	 copying where a memmove is used.  This affects only copy from a
	 string to itself.  For example,

		    A = "abcdefg";
		    copy(A, A, , , 2);

	 will result in A == "abababa".  If the overwriting that occurs here
	 is not wanted, one may use

		    A = "abcdefg";
		    copy(str(A), A, , , 2);

	  which results in A == "ababcde".

    (29) perm(a,b) and comb(a,b) have been extended to accept any real a and
	 any integer b except for perm(a, b) with integer a such that b <= a < 0
	 which gives a "division by zero" error.  For positive b, both functions
	 are polynomials in a of degree b;  for negative b, perm(a,b) is a
	 rational function (1/((a + 1) * (a+2) ...) with abs(b) factors in the
	 denominator), and comb(a,b) = 0.  (An obvious "todo" is to extend this
	 to complex or other types of a.)

    (30) Although it is not illegal, it seems pointless to use a comma operator
	 with a constant or simple variable as in

		    > 2 * 3,14159
			    14159
		    > a = 4; b = 5;
		    > A = (a , b + 2);
		    > A
			    7

	 I have added a few lines to addop.c so that when this occurs a
	 "unused value ignored" message and the relevant line number are
	 displayed.  I have found this useful as I occasionally type ','
	 when I mean '.'.

	 There may be one or two other changes resulting from the way I have
	 rewritten the optimization code in addop.c.  I think there was a bug
	 that assumed that PTR_SIZE would be the same as sizeof(long).  By
	 the way, the new OP_STRING is now of index rather than pointer type.
	 It follows that pointers are now used in opcodes only for global
	 variables.  By introducing a table of addresses of global variables
	 like those used for "constants" and "literal strings", the use of
	 pointers in opcodes could be eliminated.

    (31) When calc has executed a quit (or exit) statement in a function or
	 eval evaluation, it has invoked a call to math_error() which causes
	 a long jump to an initial state without freeing any data on the
	 stack, etc.  Maybe more detail should be added to math_error(), but
	 to achieve the freeing of memory for a quit statement and at the same
	 time give more information about its occurrence I have changed the
	 way opcodes.c handles OP_QUIT.  Now it should free the local variables
	 and whatever is on the stack, and display the name and line-number,
	 for each of the functions currently being evaluated.  The last
	 function listed should be the "top-level" one with name "*".
	 Strings being eval-ed will have name "**".

	 Here is a demo:

	    > global a;
	    >
	    > define f(x) {local i = x^2; a++;
	    >> if (x > 5) quit "Too large!"; return i;}
	    f() defined
	    > define g(x) = f(x) + f(2*x);
	    g() defined
	    > g(2)
		    20
	    > g(3)
	    Too large!
		    "f": line 3
		    "g": line 0
		    "*": line 6
	    > eval("g(3)")
	    Too large!
		    "f": line 3
		    "g": line 0
		    "**": line 1
		    "*": line 7
	    > a
		    6

    (32) I've made several small changes like removing

		    if (vp->v_type == V_NUM) {
			    q = qinv(vp->v_num);
			    if (stack->v_type == V_NUM)
				    qfree(stack->v_num);
			    stack->v_num = q;
			    stack->v_type = V_NUM;
			    return;
		    }

	 from the definition of o_invert.  Presumably these lines were intended
	 to speed up execution for the common case of numerical argument.
	 Comparing the runtimes with and without these lines for inverting
	 thousands of large random numbers in a matrix suggest that execution
	 for real numbers is slightly faster without these lines.

	 Maybe this and other similar treatment of "special cases" should be
	 looked at more closely.

    (33) The new lib script lib/natnumset.cal demonstrates how the new
	 string operators and functions may be used for defining and
	 working with sets of natural numbers not exceeding a
	 user-specified bound.


Following is the change from calc version 2.10.3t5.28 to 2.10.3t5.33:

    Added hnrmod(v, h, n, r) builtin to compute:

	v % (h * 2^n + r), h>0, n>0, r = -1, 0 or 1

    Changed lucas.cal and mersenne.cal to make use of hnrmod().

    A number of changes from Ernest Bowen:

	(1) introduction of unary & and * analogous to those in C;

	    For an lvalue var, &var returns what I call a
	    value-pointer; this is a constant which may be assigned to
	    a variable as in p = &var, and then *p in expressions has
	    the same effect as var.  Here is a simple example of their use:

		> define s(L) {local v=0; while (size(L)) v+= *pop(L);return v;}
		s() defined
		> global a = 1, b = 2;
		> L = list(&a, &b);
		> print s(L)
		3
		> b = 3;
		> print s(L)
		4

	    Octet-pointers, number-pointers, and string-pointers in
	    much the same way, but have not attempted to do much with
	    the latter two.

	    To print a pointer, use the "%p" specifier.

	    Some arithmetic operations has been defined for corresponding
	    C operations.  For example:

		> A = mat[4];
		> p = &A[0];
		> *(p+2) == A[2]
		> ++p
		> *p == A[1]

	    There is at present no protection against "illegal" use of &
	    and *, e.g. if one attempts here to assign a value to *(p+5),
	    or to use p after assigning another value to A.

	    NOTE: Unlike C, in calc &A[0] and A are quite different things.

	    NOTE: If the current value of a variable X is an octet,
	    number or string, *X may be used to to return the value of
	    X; in effect X is an address and *X is the value at X.

	    Added isptr(p) builtin to return 0 is p is not a pointer,
	    >0 if it is a pointer.  The value of isptr(p) comes from the
	    V_XYZ #define (see the top of value.h) of the value to which
	    p points.

	    To allow & to be used as a C-like address operator, use of it
	    has been dropped in calls to user-defined functions.  For the
	    time being I have replaced it by the back-quote `.  For example:

		> global a
		> define f(a,b) = a = b
		> f(&a,5)
		> print a
		0
		> f(`a,5)
		> print a
		5

	   However, one may use & in a similar way as in:

		> define g(a,b) = *a = b
		> g(&a, 7)
		> print a
		7

	   There is no hashvalue for pointers. Thus, like error values,
	   they cannot be used as indices in an association.

	   The -> also works in calc. For example:

		> obj xy {x,y}
		> obj uvw {u, v, w}
		> obj xy A = {1,2}
		> obj uvw B = {3,4,5}
		> p = &A
		> q = &B
		> p->x
			1
		> p->y = 6
		> A
			obj xy {1, 6}
		> q -> u
			3
		> p->y = q
		> A
			obj xy {1, v-ptr: 1400474c0}
		> p->y->u
			3
		> p->y->u = 7
		> B
			obj uvw {7, 4, 5}
		> p -> y = p
		> A
			obj xy {1, v-ptr: 140047490}
		> p -> y -> x
			1
		> p->y->y
			v-ptr: 140047490
		> p->y->y-> x
			1
		> p->y->y->x = 8
		> A
			obj xy {8, v-ptr: 140047490}


	(2) a method of "protecting" variables;

	    For the various kinds of "protection", of an l_value var,
	    bits of var->v_subtype, of which only bits 0 and 1 have been
	    used in the past to indicate literal and allocated strings.
	    This has meant initialization of var->v_subtype when a new var
	    is introduced, and for assignments, etc., examination of the
	    appropriate bits to confirm that the operation is to be permitted.

	    See help/protect for details.

	(3) automatic "freeing" of constants that are no longer required.

	    For the "freeing" of constants, the definition of a NUMBER
	    structure so that a NUMBER * q could be regarded as a
	    pointing to a "freed number" if q->links = 0.

	    The old q->num was changed to a union q->nu which had a pointer
	    to the old q->num if q->links > 0 and to the next freed number
	    if q->links = 0.  The old "num" is #defined to "nu->n_num".

	    The prior method calc has used for handling "constants" amounted
	    to leakage.  After:

		> define f(x) = 27 + x;
		> a = 27;

	    It is of course necessary for the constant 27 to be stored, but
	    if one now redefines f and a by:

		> define f(x) = 45 + x;
		> a = 45;

	    There seems little point in retaining 27 as a constant and
	    therefore using up memory.  If this example seems trivial,
	    replace 27 with a few larger numbers like 2e12345, or better,
	    -2e12345, for which calc needs memory for both 2e12345 and
	    -2e12345!

	    Constants are automatically freed a definition when a
	    function is re- or un-defined.

	    The qalloc(q) and qfree(q) functions have been changed so
	    that that q->links = 0 is permitted and indicates that q
	    has been freed.  If a number has been introduced as a
	    constant, i.e. by a literal numeral as in the above
	    examples, its links becoming zero indicates that it is no
	    longer required and its position in the table of constants
	    becomes available for a later new constant.

	(4) extension of transcendental functions like tan, tanh, etc.
	    to complex arguments

	(5) definition of gd(z) and agd(z), i.e. the gudermannian and
	    inverse gudermannian

	(6) introduction of show options for displaying information about
	    current constants, global variables, static variables, and cached
	    redc moduli.

	    To help you follow what is going on, the following show
	    items have been introduced:

		show constants ==> display the currently stored constants
		show numbers   ==> display the currently stored numbers
		show redcdata  ==> display the currently stored redc moduli
		show statics   ==> display info about static variables
		show real      ==> display only real-valued variables

	    The constants are automatically initialized as constants and
	    should always appear, with links >= 1, in in the list of constants.

	    The show command:

		show globals

	    has been redefined so that it gives information about all
	    current global and still active static variables.

	(7) definition of functions for freeing globals, statics, redc values

	    To free memory used by different kinds of variable, the following
	    builtins have been added:

		freeglobals();		/* free all globals */
		freestatics();		/* free all statics */
		freeredc();		/* free redc moduli */
		free(a, b, ...);	/* free specific variables */

	   NOTE: These functions do not "undefine" the variables, but
	   have the effect of assigning the null value to them, and so
	   frees the memory used for elements of a list, matrix or object.

	   See 10) below for info about "undefine *".

	(8) enhancement of handling of "old value": having it return an
	    lvalue and giving option of disabling updating.

	    Now, by default, "." return an lvalue with the appropriate
	    value instead of copying the old value.

	    So that a string of commands may be given without changing
	    the "oldvalue", the new builtin:

		saveval(0)

	    function simply disables the updating of the "." value.
	    The default updating can be resumed by calling:

		saveval(1)

	    The "." value:

		> 2 + 2
		4
		> .
		4

	    can now be treated as an unnamed variable.  For example:

		> mat x[3,3]={1,2,3,4,5,6,7,8,9}
		> x
		> print .[1,2]
		6

	(9) for a list L defining L[i] to be same as L[[i]]

	(10) extending undefine to permit its application to all user-defined
	     functions by using "undefine *".

	     The command:

		undefine *

	     undefines all current user-defined functions.  After
	     executing all the above freeing functions (and if
	     necessary free(.) to free the current "old value"), the
	     only remaining numbers as displayed by:

		show numbers

	     should be those associated with epsilon(), and if it has been
	     called, qpi().

	(11) storing the most recently calculated value of qpi(epsilon)i and
	     epsilon so that when called again with the same epsilon it
	     is copied rather than recalculateed.

	(12) defining trace() for square matrices

	(13) expression in parentheses may now be followed by a qualifier
	     computible with its type

	     When an expression in parentheses evaluates to an lvalue
	     whose current value is a matrix, list or object, it may
	     now be followed by a qualifier computible with its type.

	     For example:

		> A = list(1,2,4);
		> B = mat[2,2] = {5,6,7,8};
		> define f(x) = (x ? A : B)[[1]];
		> print f(1), f(0)
		2 6

		> obj xy {x,y}
		> C = obj xy = {4,5}
		> p = &C
		> *p.x
		Not indexing matrix or object
		> (*p).x
		4

	(14) swap(a,b) now permits swapping of octets in the same or different
	     blocks.

	     For example:

		> A = blk() = {1,2,3}
		> B = blk() = {4,5,6}
		> swap(A[0], B[2])
		> A
			chunksize = 256, maxsize = 256, datalen = 3
			060203

    A few bug fixes from Ernest Bowen:

	B1: qcmpi(q, n) in qmath.c sometimes gave the wrong result if
		LONG_BITS > BASEB, len = 1 and nf = 0, since it then
		reduces to the value of (nf != q->num.v[1]) in which
		q->num.v[1] is not part of the size-1 array of HALFs for
		q->num.  At present this is used only for changing opcodes
		for ^2 and ^4 from sequences involving OP_POWER to
		sequences using OP_SQUARE, which has no effect on the
		results of calculations.

	B2: in matdet(m) in matfunc.c, a copy of the matrix m was not freed
		when the determinant turned out have zero value.

	B3: in f_search() in func.c, a qlinking of the NUMBER * storing the
		the size of a file was not qfreed.

	B4: in comalloc() in commath.c the initial zero values for real and
		imag parts are qlinked but not qfreed when nonzero values are
		assigned to them.  Rather than changing
		the definition of comalloc(), I have included any relevant
		qfrees with the calls to comalloc() as in
			c = comalloc();
			qfree(c->real);
			c->real = ...

	B5: in calls to matsum(), zeros are qlinked but not qfreed.  Rather
		than changing addnumeric(), I have changed the definition
		of matsum(m) so that it simply adds the components of m,
		which requires only that the relevant additions be defined,
		not that all components of m be numbers.


    Simple arithmetic expressions with literal numbers are evaluated
    during compilation rather than execution.  So:

	define f(x) = 2 + 3 + x;

    will be stored as if defined by:

	define f(x) = 5 + x;

    Fixed bug with lowhex2bin converstion in lib_util.c.  It did not
    correctly convert from hex ASCII to binary values due to a table
    loading error.

    Fixed porting problem for NetBSD and FreeBSD by renaming the
    qdiv() function in qmath.c to qqdiv().

    Improved the speed of mfactor (from mfactor.cal library) for
    long Mersenne factorizations.  The default reporting loop
    is now 10000 cycles.

    SGI Mips r10k compile set is speced for IRIX6.5 with v7.2
    compilers.  A note for pre-IRIX6.5 and/or pre-v7.2 compilers
    is given in the compile set.

    Added regression tests related to saveval(), dot and pointers.


Following is the change from calc version 2.10.3t5.11 to 2.10.3t5.27:

    The todo help file as been updated with the in-progress items:

	XXX - block print function is not written yet ...

    Expanded the role of blk() to produce unnamed blocks as in:

		B = blk(len, chunk)

    and named blocks as in:

		B = blk(str, len, chunk)

    A block may be changed (with possible loss of data only if len is less
    than the old len) by:

		C = blk(B, len, chunk)

    For an unnamed block B, this creates a new block C and copies
    min(len, oldlen) octets to it, B remaining unchanged.   For a named
    block, the block B is changed and C refers to the same block as B,
    so that for example, C[i] = x will result in B[i] == x.  Thus, for a
    named block, "B = " does nothing (other than B = B) in:

		B = blk(B, len, chunk)

    but is necessary for changing an unnamed block.

    Renamed rmblk() to blkfree().

    The builtin function blkfree(val) will free memory allocated to block.
    If val is a named block, or the name of a named block, or the
    identifying index for a named block, blkfree(val) frees the
    memory block allocated to this named block.  The block remains
    in existence with the same name, identifying index, and chunksize,
    but its size and maxsize becomes zero and the pointer for the start
    of its data block null.

    The builtin function blocks() returns the number of blocks that
    have been created but not freed by the blkfree() function.  When called
    as blocks(id) and the argument id less than the number of named
    blocks that have been created, blocks(id) returns the named block
    with identifying index id.

    Removed the artifical limit of 20 named blocks.

    Added name() builtin to return the name of a type of value
    as a string.

    Added isdefined() to determine of a value is defined.

    Added isobjtype() to determine the type of an object.

    The isatty(v) builtin will return 1 if v is a file that associated
    with a tty (terminal, xterm, etc.) and 0 otherwise.  The isatty(v)
    builtin will no longer return an error if v is not a file or
    is a closed file.

    The isident(m) builtin will return 1 if m is a  identity matrix
    and 0 otherwise.  The isident(m) builtin will no longer return an
    error if m is not a matrix.

    Added extensive testing of isxxx() builtins and their operations
    on various types.

    Added md5() builtin to perform the MD5 Message-Digest Algorithm.

    Renamed isset() to bit().

    Blocks will expand when required by the copy() builtin function:

	> f = fopen("help/full", "r")
	> B = blk()
	> B
		chunksize = 256, maxsize = 256, datalen = 0
	> copy(B, f)
	> B
		chunksize = 256, maxsize = 310272, datalen = 310084
		2a2a2a2a2a2a2a2a2a2a2a2a2a0a2a20696e74726f0a2a2a2a2a2a2a2a2a...

	NOTE: Your results will differ because changes to help/full.

    The blkcpy() builtin args now more closely match that
    of memcpy(), strncpy:

	blkcpy(dst, src [, num [, dsi [, ssi]]])

    The copy() builtin args now more closely match that the cp command:

	copy(src, dst [, num [, ssi [, dsi]]])

    but otherwise does the same thing as blkcpy.

    Fixed lint problems for SunOS.

    Added have_memmv.c and HAVE_MEMMOVE Makefile variable to control
    use of memmove().  If empty, then memmove() is tested for and if
    not found, or if HAVE_MEMMOVE= -DHAVE_NO_MEMMOVE then an internal
    version of memmove() is used instead.

    Added regression tests for sha, sha1 and md5 builtin hash functions.

    Added xx_print to to the list of object routines are definable.
    Added xx_print.cal to the library to demo this feature.

    Moved blkcpy() routines have been moved to blkcpy.[ch].

    The blkcpy() & copy() builtings can not copy to/from numbers.
    For purposes of the copy, only the numerator is ignored.

    Resolved a number of missing symbols for libcalc users.

    Added lib_util.{c,h} to the calc source to support users of
    libcalc.a.  These utility routines are not directly used by
    calc but are otherwise have utility to those programmers who
    directly use libcalc.a instead.

    Added sample sub-directory.  This sub-directory contains a few
    sample programs that use libcalc.a.  These sample programs are
    built via the all rule because they will help check to see that
    libcalc.a library does not contain external references that
    cannot be resolved.  At the current time none of these sample
    programs are installed.

    Added a libcalc_call_me_last() call to return storage created
    by the libcalc_call_me_first() call.  This allows users of libcalc.a
    to free up a small amount of storage.

    Fixed some memory leaks associated with the random() Blum generator.

    Fixed fseek() file operations for SunOS.

    Fixed convz2hex() fencepost error.  It also removes leading 0's.

    Plugged a memory leak relating to pmod.  The following calculation:

	pmod(2, x, something)

    where x was not 2^n-1 would leak memory.  This has been fixed.


Following is the change from calc version 2.10.3t5.1 to 2.10.3t5.10:

    Misc printf warning bug fixes.

    Calc now permits chains of initializations as in:

		obj point {x,y} P = {1,2} = {3,4} = {5,6}

    Here the initializations are applied from left to right.  It may
    look silly, but the 1, 2, ... could be replaced by expressions with
    side effects.  As an example of its use suppose A and B are
    expressions with side effects:

		P = {A, B}

    has the effect of P.x = A; P.y = B.  Sometimes one might want these in
    the reverse order: P.y = B; P.x = A.  This is achieved by:

		P = { , B} = {A}

    Another example of its use:

		obj point Q = {P, P} = {{1, 2}, {3, 4}}

    which results in Q having Q.x.x = 1, Q.x.y = 2, etc.

    The role of the comma in has been changed.  Expressions such as:

                mat A[2], B[3]

    are equivalent to:

                (mat A[2]), (mat B[3])

    Now, expr1, expr2  returns type of expr2 rather than EXPR_RVALUE.  This
    permits expressions such as:

		(a = 2, b) = 3

    Also, expr1 ? expr2 : expr3  returns type(expr2) | type(expr3).
    This will make the result an lvalue (i.e. EXPR_RVALUE bit not set)
    For example, if both expr2 and expr3 are lvalues.  Then:

		a ? b : c = d

    has the effect of b = d if a is "nonzero", otherwise c = d.

    This may be compared with

		d = a ? b : c

    which does d = b if a is "nonzero", otherwise d = c.

    And now, expr1 || expr2 and expr1 && expr2 each return
    htype(expr1)| type(expr2).  So for example:

		a || b = c

    has the effect of a = c if a is "nonzero", otherwise b = c.
    And for example:

		a && b = c

    has the effect of a = c if a is "zero", otherwise b = c.

    At top level, newlines are neglected between '(' and the matching
    ')' in expressions and function calls.  For example, if f() has been
    already defined, then:


		a = (
			2
			+
			f
			(
			3
			)
		    )

    and

		b = sqrt (
			20
			,
			1
		    )

    will be accepted, and in interactive mode the continue-line prompt
    will be displayed.

    When calc sees a "for", "while", "do", or "switch", newlines will be
    ignored (and the line-continuation prompt displayed in interactive mode)
    until the expected conditions and statements are completed.
    For example:

	s = 0;
	for (i = 0; i < 5; i++)
	{
		s += i;
	}
	print s;

    Now 's' will print '10' instead of '5'.

    Added more regression tests to regress.cal.  Changed the error
    counter from 'err' to 'prob'.  The errmax() is set very high and
    the expected value of errcount() is kept in ecnt.

    Added the 'unexpected' help file which gives some unexpected
    surprises that C programmers may encounter.

    Updated the 'help', 'intro' and 'overview' to reflect the
    full ilst of non-builtin function help files.  Reorered the
    'full' help file.

    The blkalloc() builtin has been renamed blk().

    Only a "fixed" type of BLOCK will be used.  Other types of
    blocks in the future will be different VALUE types.

    Introduced an undefine command so that

		    undefine f, g, ...

    frees the memory used to store code for user-defined functions f,
    g, ..., effectively removing them from the list of defined
    functions.

    When working from a terminal or when config("lib_debug") > 0 advice
    that a function has been defined, undefined, or redefined is
    displayed in format "f() defined".

    Some experimental changes to block and octet handling, so that after:

		    B = blk(N)

    B[i] for 0 <= i < N behaves for some operations like an lvalue for
    a USB8 in B.

    xx_assign added to object functions to permit the possibility of
    specifying what A = B will do if A is an xx-object.  Normal
    assignment use of = is restored by the command: undefine
    xx_assign.

    For error-value err, errno(err) returns the error-code for err and
    stores this in calc_errno;  error(err) returns err as if
    error(errno(err)) were called.

    Anticipating probable future use, names have been introduced for
    the four characters @, #, $, `.  This completes the coverage of
    printable characters on a standard keyboard.

    Added sha() builtin to perform the old Secure Hash Algorithm
    (SHS FIPS Pub 180).

    Added sha1() builtin to perform the new Secure Hash Standard-1
    (SHS-1 FIPS Pub 180-1).

    Added ${LD_DEBUG} Makefile variable to allow for additional
    libraries to be compiled into calc ... for debugging purposes.
    In most cases, LD_DEBUG= is sufficent.

    Added ${CALC_ENV} makefile variable to allow for particular
    environment variables to be supplied for make {check,chk,debug}.
    In most cases, CALC_ENV= CALCPATH=./lib is sufficent.

    Added ${CALC_LIBS} to list the libaraies created and used to
    build calc.  The CALC_LIBS= custom/libcustcalc.a libcalc.a
    is standard for everyone.

    Improved how 'make calc' and 'make all' rules work with respect
    to building .h files.

    Added 'make run' to only run calc interactively with the
    ${CALC_ENV} calc environment.  Added 'make cvd', 'make dbx'
    and 'make gdb' rules to run debug calc with the respective
    debugger with the ${CALC_ENV} calc environment.

    Added cvmalloc_error() function to lib_calc.c as a hook for
    users of the SGI Workshop malloc debugging library.

    Cut down on places where *.h files include system files.
    The *.c should do that instead where it is reasonable.

    To avoid symbol conflicts, *.h files produced and shipped
    with calc are inclosed that as similar to the following:

	#if !defined(__CALC_H__)
	#define __CALC_H__
	..
	#endif /* !__CALC_H__ */

    Added memsize(x) builtin to print the best aproximation of the
    size of 'x' including overhead.  The sizeof(x) builtin attempts
    to cover just the storage of the value and not the overhead.
    Because -1, 0 and 1 ZVALUES are static common values, sizeof(x)
    ignores their storage.  Also sizeof(x) ignores the denominator of
    integers, and the imaginary parts of pure real numbers.  Added
    regression tests for memsize(), sizeof() and size().


Following is the change from calc version 2.10.3t4.16 to 2.10.3t5.0:

    The calc source now comes with a custom sub-directory which
    contains the custom interface code.  The main Makefile now
    drives the building and installing of this code in a similar
    way that it drives the lib and help sub-directories.  (see below)

    Made minor edits to most help files beginning with a thru e.

    The errno(n) sets a C-like errno to the value n; errno() returns
    the current errno value.  The argument for strerror() and error()
    defaults to this errno.

    Added more error() and errno() regression tests.

    The convention of using the global variable lib_debug at the
    end of calc librar scripts has been replaced with config("lib_debug").
    The "lib_debug" is reserved by convention for calc library scripts.
    This config parameter takes the place of the lib_debug global variable.
    By convention, "lib_debug" has the following meanings:

	<-1	no debug messages are printed though some internal
		    debug actions and information may be collected

	-1	no debug messages are printed, no debug actions will be taken

	0	only usage message regarding each important object are
		    printed at the time of the read (default)

	>0	messages regarding each important object are
		    printed at the time of the read in addition
		    to other debug messages

    The "calc_debug" is reserved by convention for internal calc routines.
    The output of "calc_debug" will change from release to release.
    Generally this value is used by calc wizards and by the regress.cal
    routine (make check).  By convention, "calc_debug" has the following
    meanings:

	<-1	reserved for future use

	-1	no debug messages are printed, no debug actions will be taken

	0	very little, if any debugging is performed (and then mostly
		    in alpha test code).  The only output is as a result of
		    internal fatal errors (typically either math_error() or
		    exit() will be called). (default)

	>0	a greater degree of debugging is performed and more
		    verbose messages are printed (regress.cal uses 1).

    The "user_debug" is provided for use by users.  Calc ignores this value
    other than to set it to 0 by default (for both "oldstd" and "newstd").
    No calc code or shipped library will change this value other than
    during startup or during a config("all", xyz) call.

    The following is suggested as a convention for use of "user_debug".
    These are only suggestions: feel free to use it as you like:

	<-1	no debug messages are printed though some internal
		    debug actions and information may be collected

	-1	no debug messages are printed, no debug actions will be taken

	0	very little, if any debugging is performed.  The only output
		    are from fatal errors. (default)

	>0	a greater degree of debugging is performed and more
		    verbose messages are printed

    Added more code that is deading with the BLOCK type.

    Added blkalloc() builtin.

    Split NAMETYPE definition out into nametype.h.

    Added OCTET type for use in processing block[i].

    Added free, copy, cmp, quickhash and print functions for
    HASH, BLOCK and OCTET.

    Added notes to config.h about what needs to be looked at when
    new configuration items are added.

    The null() builtin now takes arguments.

    Given the following:

	obj point {x,y}
	obj point P, Q

    will will now create P and Q as obj point objects.

    Added xx_or, xx_and, xx_not and xx_fact objfuncs.

    Added the custom() builtin function.  The custom() builtin
    interface is designed to make it easier for local custom
    modification to be added to calc.  Custom functions are
    non-standard or non-portable code.  For these reasons, one must can
    only execute custom() code by way of an explicit action.

    By default, custom() returns an error.  A new calc command line
    option of '-C' is required (as well as ALLOW_CUSTOM= -DCUSTOM
    Makefile variable set) to enable it.

    Added -C as a calc command line option.  This permits the
    custom() interface to be used.

    Added ALLOW_CUSTOM Makefile variable to permanently disable
    or selective enable the custom builtin interface.

    The rm() builtin now takes multiple filenames.  If the first
    arg is "-f", then 'no-such-file' errors are ignored.

    Added errcount([count]) builtin to return or set the error
    counter.  Added errmax([limit]) to rturn or set the error
    count limiter.

    Added -n as a calc command line option.  This has the effect
    of calling config("all", "newstd") at startup time.

    Added -e as a calc command line option to ignore all environment
    varialbes at startup time.  The getenv() builtin function will
    still return values, however.

    Added -i as a calc command line option.  This has the effect
    ignoring when errcount() exceeds errmax().

    Changed the config("maxerr") name to config("maxscan").  The
    old name of "maxerr" is kept for backward compatibility.

    Using an unknown -flag on the calc command like will
    generate a short usage message.

    Doing a 'help calc' displays the same info as 'help usage'.

    The 'make check' rule now uses the -i calc command line flag
    so that regress.cal can continue beyond when errcount exceeds
    errmax.  In regress.cal, vrfy() reports when errcount exceeds
    errmax and resets errmax to match errcount.  This check
    and report is independent of the test success of failure.

    Fixed missing or out of order tests in regress.cal.

    Misc Makefile cleanup in lib/Makefile and help/Makefile.

    The default errmax() value on startup is now 20.

    The custom() interface is now complete.  See help/custom and
    custom/HOW_TO_ADD files, which show up as the custom and new_custom
    help files, for more information.

    The help command will search ${LIBDIR}/custhelp if it fails to find
    a file in ${LIBDIR}.  This allows the help command to also print
    help for a custom function.  However if a standard help file and a
    custom help file share the same name, help will only print the
    standard help file.  One can skip the standard help file and print
    the custom help file by:

	help custhelp/name

    or by:

	custom("help", "name")

    Added minor sanity checks the help command's filename.

    Added show custom to display custom function information.

    Added the contrib help page to give information on how
    and where to submit new calc code, modes or custom functions.

    Added comment information to value.h about what needs to be
    checked or modified when a new value type is added.

    Both size(x) and sizeof(x) return information on all value types.
    Moved size and sizeof information from func.c and into new file: size.c.

    Added custom("devnull") to serve as a do-nothing interface tester.

    Added custom("argv" [,arg ...]) to print information about args.

    Added custom("sysinfo", "item") to print an internal calc #define
    parameter.

    The make depend rule also processes the custom/Makefile.

    Added xx_max and xx_min for objfuncs.

    The max(), min() builtins work for lists.


Following is the change from calc version 2.10.3t3 to 2.10.3t4.15:

    The priority of unary + and - to that of binary + and - when they are
    applied to a first or only term.  Thus:

	-16^-2 == -1/256
	-7^2 == -49
	-3! == -6

    Running ranlib is no longer the default.  Systems that need RANLIB
    should edit the Makefile and comment back in:

	RANLIB=ranlib

    Dropped support of SGI r8k.

    Added support for the SGI r5k.

    Added support for SGI Mips compiler version 7.1 or later.

    Removed "random" as a config() option.

    Removed CCZPRIME Makefile variable.

    Added zsquaremod() back into zmod.c to be used by the Blum-Blum-Shub
    generator for the special case of needing x^2 mod y.

    Moved the Blum-Blum-Shub code and defines from zrand.c and zrand.h
    into zrandom.c and zrandom.h.  Now only the a55 generator resides
    in zrand.c and zrand.h.

    Added random, srandom and randombit help files.

    Added random(), srandom() and randombit() builtin functions.  The
    cryptographically strong random number generator is code complete!

    Removed cryrand.cal now that a Blum-Blum-Shub generator is builtin.

    Improved the speed of seedrandom.cal.  It now uses the 13th
    builtin Blum-Blum-Shub seed.

    The randmprime.cal script makes use of the Blum-Blum-Shub generator.

    Added randombitrun.cal and randomrun.cal calc library files.
    These are the Blum-Blum-Shub analogs to the randbitrun.cal
    and randrun.cal a55 tests.

    Improved hash.c interface to lower level hash functions.  The hash
    interface does not yet have a func.c interface ...  it is still
    under test.

    Added randombitrun.cal to test the Blum-Blum-Shub generator.

    Added calc.h, hash.h, shs.h and value.h to LIB_H_SRC because some
    of the libcalc.a files need them.

    In the original version, each call to newerror(str) created a new
    error-value.  Now a new value will be created only if str has not
    been used in a previous call to newerror().  In effect, the string
    serves to identify the error-value; for example:

	    return newerror("Non-integer argument");

    can be used in one or more functions, some of which may be
    repeatedly called, but after it has been called once, it will
    always return the same value as if one had initially used the
    assignment:

	    non_integer_argument_error = newerror("Non-integer argument")

    and then in each function used:

	    return non_integer_argument_error;

    The new definition of newerror() permits its freer use in cases like:

	    define foo(a) {

		    if (!isint(a))
			    return newerror("Non-integer argument");
		    ...
	    }

    One might say that "new" in "newerror" used to mean being different
    from any earlier error-value.  Now it means being not one of the
    "original" or "old" error-values defined internally by calc.

    As newerror() and newerror("") specify no non-null string, it has
    been arranged that they return the same as newerror("???").

    Added "show errors" command analogous to "show functions" for
    user-defined functions.  One difference is that whereas the
    functions are created by explicit definitions, a new described
    error is created only when a newerror(...) is executed.

    Fixed macro symbol substitution problem uncovered by HPUX cpp bug in
    HVAL and related zrand.h macros.

    Added +e to CCMISC for HP-UX users.

    Fixed the prompt bug.

    Eliminated the hash_init() initialization function.

    The 'struct block' has been moved from value.c to a new file: block.h.

    Added "blkmaxprint" config value, which limits the octets to print
    for a block.  A "blkmaxprint" of 0 means to print all octets of a
    block, regardless of size.  The default is to print only the first
    256 octets.

    The "blkverbose" determines if all lines, including duplicates
    should be printed.  If TRUE, then all lines are printed.  If false,
    duplicate lines are skipped and only a "*" is printed in a sytle
    similar to od.  This config value has not meaning if "blkfmt" is
    "str".  The default value for "blkverbose" is FALSE: duplicate
    lines are not printed.

    The "blkbase" determines the base in which octets of a block
    are printed.  Possible values are:

        "hexadecimal"           Octets printed in 2 digit hex
        "hex"

        "octal"                 Octets printed in 3 digit octal
        "oct"

        "character"             Octets printed as chars with non-printing
        "char"                      chars as \123 or \n, \t, \r

        "binary"                Octets printed as 0 or 1 chars
        "bin"

        "raw"                   Octets printed as is, i.e. raw binary
        "none"

    The default "blkbase" is "hex".

    The "blkfmt" determines for format of how block are printed:

        "line"          print in lines of up to 79 chars + newline
        "lines"

        "str"           print as one long string
        "string"
        "strings"

        "od"            print in od-like format, with leading offset,
        "odstyle"          followed by octets in the given base
        "od_style"

        "hd"            print in hex dump format, with leading offset,
        "hdstyle"          followed by octets in the given base, followed
        "hd_style"         by chars or '.' if no-printable or blank

    The default "blkfmt" is "hd".

    Fixed a bug in coth() when testing acoth using coth(acoth(x)) == x
    within the rounding error.

    Assignments to matrices and objects has been changed.  The assignments in:

	A = list(1,2,3,4);
	B = makelist(4) = {1,2,3,4};

    will result in A == B.  Then:

	A = {,,5}

    will result in A == list(1,2,5,4).

    Made minor edits to most help files beginning with a thru d.

    Fixed error in using cmdbuf("").


Following is the change from calc version 2.10.3t0 to 2.10.3t2:

    Bumped to version 2.10.3 due to the amount of changes.

    Renamed qabs() to qqabs() to avoid conflicts with stdlib.h.

    Fixed a casting problem in label.c.

    A lot of work was performed on the code generation by Ernest Bowen
    <ernie@neumann.une.edu.au>.  Declarations no longer need to precese code:

	define f(x) {
		local i = x^2;
		print "i = ":i;
		local j = i;
		...
	}

    The scope of a variable extends from the end of the declaration (including
    initialization code for the variable) at which it is first created
    to the limit given by the following rules:

	local variable: to the end of the function being defined

	global variable: to the end of the session with calc

	static within a function definition: to the the first of:

	    an end of a global, static or local declaration (including
	    initialization code) with the same identifier

	    the end of the definition

	static at top level within a file: to the first of:

	    the next static declaration of the identifier at top level
	    in the file,

	    the next global declaration of the identifier at top level
	    in the file or in any function definition in the file,

	    the next global declaration of the identifier at any level
	    in a file being read as a result of a "read" command,

	    the end of the file.

    The scope of a top-level global or static variable may be
    interrupted by the use of the identifier as a parameter or local or
    static variable within a function definition in the file being
    read; it is restored (without change of value) after the definition.

    For example, The two static variables a and b are created,
    with zero value, when the definition is read; a is initialized
    with the value x if and when f(x) is first called with a positive
    even x, b is similarly initialized if and when f(x) is first called
    positive odd x.  Each time f(x) is called with positive integer x,
    a or b is incremented.  Finally the values of the static variables
    are assigned to the global variables a and b, and the resulting
    values displayed.  Immediately after the last of several calls to
    f(x), a = 0 if none of the x's have been positive even, otherwise
    a = the first positive even x + the number of positive even x's,
    and b = 0 if none of the x's have been positive odd, otherwise
    b = the first positive odd x + the number of positive odd x's:

	define f(x) {
		if (isint(x) && x > 0) {
			if (iseven(x)) {
				static a = x;
				a++;
			} else {
				static b = x;
				b++;
			}
		}
		global a = a, b = b;
		print "a =",a,"b =",b;
	}

    Fixed some faults in the handling of syntax errors for the matrix
    and object creation operators mat and obj.  In previous versions of calc:

	mat;				<- Bad dimension 0 for matrix
	mat A;				<- Bad dimension 0 for matrix
	global mat A;			<- Bad dimension 0 for matrix
	mat A[2], mat B[3]		<- Semicolon expected
	global mat A[2], mat B[3]	<- Bad syntax in declaration statement

    Now:

	this statement			has the same effect as
	--------------			----------------------
	mat A[2], B[3]			(A = mat[2]), B[3]

	global mat A[2], B[3]		global A, B; A = mat[2]; B = mat[3];

    Initialization remains essentially as before except that for objects,
    spaces between identifiers indicate assignments as in simple variable
    declarations.  Thus, after:

	obj point {x,y};
	obj point P, Q R = {1,2}

    P has {0,0}, Q and R have {1,2}.  In the corresponding expression with
    matrices commas between identifiers before the initialization are ignored.
    For example:

	this statement			has the same effect as
	--------------			----------------------
	mat A, B C [2] = {1,2}		A = B = C = (mat[2] = {1,2})

    One can also do things like:

	L = list(mat[2] = {1,2}, obj point = {3,4}, mat[2] = {5,6})
	A = mat[2,2] = {1,2,3,4}^2
	B = mat[2,2] = {1,2,3,4} * mat[2,2] = {5,6,7,8}

    where the initialization = has stronger binding than the assignment = and
    the * sign.

    Matrices and objects can be mixed in declarations after any simple
    variables as in:

	global a, b, mat A, B[2] = {3,4}, C[2] = {4,5}, obj point P = {5,6}, Q

    Fixed some bugs related to global and static scoping.  See the the
    5200 regress test and lib/test5200.cal for details.

    Optimized opcode generator so that functions defined using '=' do not
    have two unreached opcodes.  I.e.,:

	define f(x) = x^2
	show opcodes f

    Also unreachable opcodes UNDEF and RETURN are now not included at
    the end of any user-defined function.

    Changed the "no offset" indicator in label.c from 0 to -1; this
    permits goto jumps to the zero opcode position.

    Changed the opcode generation for "if (...)" followed by
    "break", "continue", or "goto", so that only one jump opcode is
    required.

    A label can now be immediately by a rightbrace.  For example:

	define test_newop3(x) {if (x < 0) goto l132; ++x; l132: return x;}

    The LONG_BITS make variable, if set, will force the size of a long
    as well as forcing the USB8, SB8, USB16, SB16, USB32, SB32,
    HAVE_B64, USB64, SB64, U(x) and L(x) types.  If the longbits
    program is given an arg (of 32 or 64), then it will output
    based on a generic 32 or 64 bit machine where the long is
    the same size as the wordsize.

    Fixed how the SVAL and HVAL macros were formed for BASEB==16 machines.

    Dropped explicit Makefile support for MIPS r8k since these processors
    no longer need special compiler flags.

    SGI 6.2 and later uses -xansi.


Following is the change from calc version 2.10.2t33 to 2.10.2t34:

    Fixed a bug related to fact().

    Thanks to Ernest Bowen <ernie@neumann.une.edu.au>, for two or three
    arguments,

	    search(x, val, start);
	    rsearch(x, val, start);

    and for matrix, list or association x:

	    search(f, str, start);
	    rsearch(f, str, start);

    for a file stream f open for reading, behave as before except for a few
    differences:

	(1) there are no limits on the integer-valued start.

	(2) negative values of start are interpreted as offsets from the size of
	    x and f.  For example,

		    search(x, val, -100)

	    searches the last 100 elements of x for the first i for which
	    x[[i]] = val.

	(3) for a file f, when start + strlen(str) >= size(f) and
	    search(f, str, start) returns null, i.e. str is
	    not found, the file position after the search will be

		    size(f) - strlen(str) + 1

	    rather than size(f).

    For four arguments:

	    search(a, b, c, d)
	    rsearch(a, b, c, d),

    a has the role of x or f, and b the role of val or str as described
    above for the three-argument case, and for search(), c is
    essentially "start" as before, but for rsearch() is better for c
    and d to be the same as for search().  For a non-file case, if:

             0 <= c < d <= size(a),

    the index-interval over which the search is to take place is:

             c <= i < d.

    If the user has defined a function accept(v,b), this is used rather
    than the test v == b to decide for matrix, list, or association
    searches when a "match" of v = a[[i]] with b occurs. E.g.  after:

             define accept(v,b) = (v >= b);

    then calling:

             search(a, 5, 100, 200)

    will return, if it exists, the smallest index i for which
    100 <= i < 200 and a[[i]] >= 5.  To restore the effect of
    the original "match" function, one would then have to:

             define accept(v,b) == (v == b).

    Renamed the calc symbol BYTE_ORDER to CALC_BYTE_ORDER in order
    to avoid conflict.

    Added beer.cal and hello.cal lib progs in support of:   :-)

	http://www.ionet.net/~timtroyr/funhouse/beer.html
	http://www.latech.edu/~acm/HelloWorld.shtml


Following is the change from calc version 2.10.2t25 to 2.10.2t32:

    Eliminated use of VARARG and <varargs.h>.  Calc supports only
    <stdarg.h>.  The VARARGS Makefile variable has been eliminated.

    Source is converted to ANSI C.  In particular, functions
    will now have ANSI C style args.  Any comments from old K&R
    style args have been moved to function comment section.

    Removed prototype.h.  The PROTO() macro is no longer needed
    or supported.

    Added mfactor.cal to find the smallest factor of a Mersenne number.

    The built .h file: have_times.h, determines if the system has
    <time.h>, <times.h>, <sys/time.h> and <sys/times.h>.

    Because shs.c depends on HASHFUNC, which in turn depends on
    VALUE, shs.o has been moved out of libcalc.a.  For the same
    reasons, hash.h and shs.h are not being installed into
    the ${LIBDIR} for now.

    A number of the regression tests that need random numbers now
    use different seeds.

    Fixes for compiling under BSDI's BSD/OS 2.0.  Added a Makefile
    section for BSD/OS.

    Added a Makefile compile section for Dec Alpha without gcc ...
    provides a hack-a-round for Dec Alpha cc bug.

    Minor comment changes to lucas.cal.

    Added pix.cal, a slow painful but interesting way to compute pix(x).

    Confusion over the scope of static and global values has been reduced
    by a patch from Ernest Bowen <ernie@neumann.une.edu.au>.

	The change introduced by the following patch terminates the
	scope of a static variable at any static declaration with the
	same name at the same level, or at any global declaration with
	the same name at any level.  With the example above, the scope
	of the static "a" introduced in the third line ends when the
	"global a" is read in the last line.  Thus one may now use the
	same name in several "static" areas as in:

			> static a = 10;
			> define f(x) = a + x;
			> static a = 20;
			> define g(x) = a + x;
			> global a;

	The first "a" exists only for the definition of f(); the second
	"a" only for the definition of g().  At the end one has only
	the global "a".

	Ending the scope of a static variable in this way is consistent
	with the normal use of static variables as in:

			> static a = 10;
			> define f(x) {static a = 20; return a++ + x;}
			> define g(x) = a + x;
			> global a;

	The scope of the first "a" is temporarily interrupted by the
	"static a" in the second line; the second "a" remains active
	until its scope ends with the ending of the definition of f().
	Thus one ends with g(x) = 10 + x and on successive calls to
	f(), f(x) returns 20 + x, 21 + x, etc.  With successive "static
	a" declarations at the same level, the active one at any stage
	is the most recent; if the instructions are being read from a
	file, the scope of the last "static a" ends at the end-of-file.

	Here I have assumed that no "global a" is encountered.  As
	there can be only one global variable with name "a", it seems
	to me that its use must end the scope of any static "a".  Thus
	the changes I introduce are such that after:

			> global a = 10;
			> define f(x) = a + x;
			> static a = 20;
			> define g(x) = a + x;
			> define h(x) {global a = 30; return a + x;}
			> define i(x) = a + x;

	g(x) will always return 20 + x, and until h(x) has been called,
	f(x) and i(x) will return 10 + x; when h(x) is called, it
	returns 30 + x and any later call to f(x) or i(x) will return
	30 + x.  It is the reading of "global a" in the definition of
	h() that terminates the scope of the static a = 20, so that the
	"a" for the last line is the global variable defined in the
	first line.  The "a = 30" is executed only when h() is called.

	Users who find this confusing might be well advised to use
	different names for different variables at the same scope level.

	The other changes produced by the patch are more straightforward,
	but some tricky programming was needed to get the possibility of
	multiple assignments and what seems to be the appropriate order
	of executions and assignments.  For example, the order for the
	declaration:

		global a, b = expr1, c, d = expr2, e, f

	will be:

		evaluation of expr1;
		assignment to b;
		evaluation of expr2;
		assignment to d;

	Thus the effect is the same as for:

		a = 0; b = expr1; c = 0; d = expr2; e = 0; f = 0;

	The order is important when the same name is used for different
	variables in the same context.  E.g. one may have:

		define f(x) {
			global a = 10;
			static a = a;
			local a = a--;

			while (--a > 0)
				x++;
			return x;
		}

	Every time this is called, the global "a" is assigned the value
	10.  The first time it is called, the value 10 is passed on to
	the static "a" and then to the local "a".  In each later call
	the "static a = a" is ignored and the static "a" is one less than
	it was in the preceding call.  I'm not recommending this style of
	programming but it is good that calc will be able to handle it.

	I've also changed dumpop to do something recent versions do not do:
	distinguish between static and global variables with the same name.

	Other changes: commas may be replaced by spaces in a sequence of
	identifiers in a declaration. so one may now write:

		global a b c = 10, d e = 20

	The comma after the 10 is still required.  Multiple occurrences
	of an identifier in a local declaration are now acceptable as
	they are for global or static declarations:

		local a b c = 10, a = 20;

	does the same as:

		local a b c;
		a = b = c = 10;
		a = 20;

	The static case is different in that:

		static a b c = 10, a = 20;

	creates four static variables, the first "a" having a very short and
	useless life.

    Added new tests to verify the new assugnments above.

    Added the builtin test(x) which returns 1 or 0 according as x tests
    as true or false for conditions.

    Added have_posscl.c which attempts to determine if FILEPOS is
    a scalar and defines HAVE_FILEPOS_SCALAR in have_posscl.h
    accordingly.  The Makefile variable HAVE_POSSCL determines
    if have_posscl.c will test this condition or assume non-scalar.

    Added have_offscl.c which attempts to determine if off_t is
    a scalar and defines HAVE_OFF_T_SCALAR in have_posscl.h
    accordingly.  The Makefile variable HAVE_OFFSCL determines
    if have_offscl.c will test this condition or assume non-scalar.

    Reading to EOF leaves you positioned one character beyond
    the last character in the file, just like Un*x read behavior.

    Calc supports files and offsets up to 2^64 bytes, if the OS
    and file system permits.


Following is the change from calc version 2.10.2t4 to 2.10.2t24:

    Added makefile debugging rules:

	make chk	like a 'make check' (run the regression tests)
			except that only a few lines around interesting
			(and presumable error messages) are printed.
			No output if no errors are found.

	make env	print important makefile values

	make mkdebug	'make env' + version information and a
			make with verbose output and printing of
			constructed files

	make debug	'make mkdebug' with a 'make clobber'
			so that the entire make is verbose and
			a constructed files are printed

     Improved instuctions in 'BUGS' section on reporting problems.
     In particular we made it easy for people to send in a full
     diagnostic output by sending 'debug.out' which is made as follows:

	make debug > debug.out

     Added -v to calc command line to print the version and exit.

     Fixed declarations of memcpy(), strcpy() and memset() in the
     case of them HAVE_NEWSTR is false.

     Fixed some compile time warnings.

     Attempting to rewind a file this is not open generates an error.

     Noted conversion problems in file.c in tripple X comments.

     Some extremely braindead shells cannot correctly deal with if
     cluases that do not have a non-empty else statement.  Their
     exit bogosity results in make problems.  As a work-a-round,
     Makefile if clauses have 'else true;' clauses for if statements
     that previously did not have an else cluause.

     Fixed problems where the input stack depth reached the 10 levels.

     The show keyword is now a statement instead of a command:

	> define demo() {local f = open("foo", "w"); show files; fclose(f);}
	> demo()

     Added a new trace option for display of links to real and complex
     numbers.  This is activated by config("trace", 4).  The printing
     of a real number is immediately followed by "#" and the number of
     links to that number; complex numbers are printed in the same
     except for having "##" instead of "#".  <ernie@neumann.une.edu.au>

     The number of links for a number value is essentially the number of value
     locations at which it is either stored or deemed to be stored.  Here a
     number value is the result of a reading or evaluation; when the result
     is assigned to lvalues, "linking" rather than copying occurs.  Different
     sets of mutually linked values may contain the same number.  For example:

	a = b = 2 + 3; x, y = 2 + 3;

     a and b are linked, and x and y are linked, but a and x are not linked.

     Revised the credits help file and man page.  Added archive help
     file to indicate where recent versions of calc are available.

     The regression test suite output has been changed so that it will
     output the same information regardless of CPU performance.  In
     particular, cpu times of certain tests are not printed.  This allows
     one to compare the regression output of two different systems easier.

     A matrix or object declaration is now considered an expression
     and returns a matrix or object of the specified type.  Thus one may
     use assignments like:

	A = mat[2];		/* same as: mat A[2]; */
	P = obj point;		/* same as: obj point P; */

     The obj and mat keywords may be with "local", "global", "static" as in:

	local mat A[2];

     Several matrices or objects may be assigned or declared in the one
     statement, as in:

	mat A, B[2], C[3];	/* same as: mat A[2], B[2], C[3] */

     except that only one matrix creation occurs and is copied as in:

	A = B = mat[2];

     Initialization of matrices and objects now occur before assignments:

	mat A, B [2] = {1,2};	/* same as: A = B = (mat[2] = {1,2}); */

     Missing arguments are considered as "no change" rather than
     "assign null values".  As in recent versions of calc, the default
     value assigned to matrix elements is zero and the default for object
     elements is a null value).  Thus:

	mat A[2] = {1,2};
	A = { , 3};

     will change the value of A to {1,3}.

     If the relevant operation exists for matrices or has been defined for
     the type of object A is, the assignment = may be combined with +, -, *,
     etc. as in:

	A += {3, 4};		/* same as: A[0] += 3; A[1] += 4; */
	A += { };		/* same as: A += A; */

     In (non-local) declarations, the earlier value of a variable may be
     used in the initialization list:

	mat A[3]={1,2,3}; mat A[3]={A[2],A[1],A[0]}; /* same as: A={3,2,1} */

     Also:

	mat A[3] = {1,2,3};
	mat A[3] = {A, A, A};

     produces a 3-element matrix, each of whose elements is a 3-element matrix.

     The notation A[i][j] requires A[i] to be a matrix, whereas B[i,j]
     accesses an element in a 2-dimensional matrix.  Thus:

	B == A[i]	implies		A[i][j] = B[j]

     There is requirement in the use of A[i][j] that the matrices A[i]
     for i = 0, 1, ... all be of the same size.  Thus:

	mat A[3] = {(mat[2]), (mat[3]), (mat[2])};

     produces a matrix with a 7-element structure:

	A[0][0], A[0][1], A[1][0], A[1][1], A[1][2], A[2][0], A[2][1]

     One can initialize matrices and objects whose elements are matrices
     and/or objects:

	obj point {x,y}
	obj point P;
	obj point A = {P,P};

     or:

	obj point {x,y};
	obj point P;
	mat A[2] = {P,P};
	A = {{1,2}, {3,4}};

     The config("trace", 8) causes opcodes of newly defined functions
     are displayed.  Also show can now show the opcides for a function.
     For example:

	config("trace", 8);
	define f(x) = x^2;
	show opcodes f;
	define g(x,y) {static mat A[2]; A += {x,y}; return A;}
	show opcodes g
	g(2,3);
	show opcodes g;
	g(3,4);

     The two sequences displayed for f should show the different ways
     the parameter is displayed.  The third sequence for g should also
     show the effects of the static declaration of A.

     Fixed a number of compiler warning and type cast problems.

     Added a number of new error codes.

     Misc bug fixes for gcc2 based Sparc systems.

     Fixed a bug in the SVAL() macro on systems with 'long long'
     type and on systems with 16 bit HALFs.

     Reduced the Makefile CC set:

	 CCOPT are flags given to ${CC} for optimization
	 CCWARN are flags given to ${CC} for warning message control
	 CCMISC are misc flags given to ${CC}

	 CFLAGS are all flags given to ${CC}
		[[often includes CCOPT, CCWARN, CCMISC]]
	 ICFLAGS are given to ${CC} for intermediate progs

	 CCMAIN are flags for ${CC} when files with main() instead of CFLAGS
	 CCSHS are flags given to ${CC} for compiling shs.c instead of CFLAGS

	 LCFLAGS are CC-style flags for ${LINT}
	 LDFLAGS are flags given to ${CC} for linking .o files
	 ILDFLAGS are flags given to ${CC} for linking .o files
		  for intermediate progs

	 CC is how the the C compiler is invoked

    Added more tests to regress.cal.

    Port to HP-UX.

    Moved config_print() from config.c to value.c so prevent printvalue()
    and freevalue() from being unresolved symbols for libcalc.a users.

    Calc will generate "maximum depth reached" messages or errors when
    reading or eval() is attempted at maximum input depth.

    Now each invocation of make is done via ${MAKE} and includes:

	MAKE_FILE=${MAKE_FILE}
	TOPDIR=${TOPDIR}
	LIBDIR=${LIBDIR}
	HELPDIR=${HELPDIR}

    Setting MAKE_FILE= will cause make to not re-make if the Makefile
    is edited.

    Added libinit.c which contains the function libcalc_call_me_first().
    Users of libcalc.a MUST CALL libcalc_call_me_first BEFORE THEY USE
    ANY OTHER libcalc.a functions!

    Added support for the SGI IRIX6.2 (or later) Mongoose 7.0 (or later)
    C Compiler for the r4k, r8k and r10k.  Added LD_NO_SHARED for
    non-shared linker support.

    Re-ordered and expanded options for the DEBUG make variable.

    Make a few minor cosmetic comment changes/fixes in the main Makefile.

    Statements such as:

                mat A[2][3];

    now to the same as:

                mat M[3];
                mat A[2] = {M, M};

    To initialize such an A one can use a statement like

                A = {{1,2,3}, {4,5,6}};

    or combine initialization with creation by:

                mat A[2][3] = {{1,2,3}, {4,5,6}};

    One would then have, for example, A[1][0] = 4.  Also, the inner braces
    cannot be removed from the initialization for A:

                mat A[2][3] = {1,2};

    results in exactly the same as:

                mat A[2] = {1,2};

    Added rm("file") builtin to remove a file.

    The regress test sections that create files also use rm() to remove
    them before and afterwards.

    Added 4400-4500 set to test new mat and obj initializaion rules.

    Added 4600 to test version file operations.

    Added CCZPRIME Makefile variable to the set for the short term
    to work around a CC -O2 bug on some SGI machines.

    Added regression test of _ variables and function names.

    Added read of read and write, including read and write test for
    long strings.

    Fixed bug associated with read of a long string variable.

    Renumbered some of the early regress.cal test numbers to make room
    for more tests.  Fixed all out of sequence test numbers.  Fixed some
    malformatted regression reports.

    Renamed STSIZE_BITS to OFF_T_BITS.  Renamed SWAP_HALF_IN_STSIZE to
    SWAP_HALF_IN_OFF_T.


Following is the change from calc version 2.10.2t1 to 2.10.2t3:

    Fixed bug in the regression suite that made test3400 and test4100
    fail on correct computations.

    The randbit() builtin, when given to argument, returns 1 random bit.

    Fixed a bug in longlong.c which made is generate a syntax error
    on systems such as the PowerPC where the make variable LONGLONG
    was left empty.

    By default, the Makefile leaves LONGLONG_BITS empty to allow for
    testing of 64 bit data types.  A few hosts may have problems with
    this, but hopefully not.  Such hosts can revert back to LONGLONG_BITS=0.

    Improved SGI support.  Understands SGI IRIX6.2 performance issues
    for multiple architectures.

    Fixed a number of implicit conversion from unsigned long to long to avoid
    unexpected rounding, sign extension, or loss of accuracy side effects.

    Added SHSCC because shs.c contains a large expression that some
    systems need help in optimizing.

    Added "show files" to display information about all currently open files.

    Calc now prevents user-defined function having the same name as a
    builtin function.

    A number of new error codes (more than 100) have been added.

    Added ctime() builtin for date and time as string value.
    Added time() builtin for seconds since 00:00:00 1 Jan 1970 UTC.
    Added strerror() builtin for string describing error type.
    Added freopen() builtin to reopen a file.
    Added frewind() builtin to rewind a file.
    Added fputstr() builtin to write a null-terminated string to a file.
    Added fgetstr() builtin to read a null-terminated string from a file.
    Added fgetfield() builtin to read next field from file.
    Added strscan() builtin to scan a string.
    Added scan() builtin to scan of a file.
    Added fscan() builtin to scan of a file.
    Added fscanf() builtin to do a formatted scan of a file.
    Added scanf() builtin to do a formatted scan of stdin.
    Added strscanf() builtin to do a formatted scan of a string.
    Added ungetc() builtin to unget character read from a file.

    As before, files opened with fopen() will have an id different from
    earlier files.  But instead of returning the id to the FILEIO slot
    used to store information about it, calc simply uses consecutive
    numbers starting with 3.  A calc file retains its id, even when the
    file has been closed.

    The builtin files(i) now returns the file opened with id == i
    rather than the file with slot number i.  For any i <= lastid,
    files(i) has at some time been opened.  Whether open or closed, it
    may be "reopened" with the freopen() command.  This write to a file
    and then read it, use:

	f = fopen("junk", "w")
	freopen(f, "r")

	To use the same stream f for a new file, one may use:

	    freopen(f, mode, newfilename)

	which closes f (assuming it is open) and then opens newfilename on f.

	And as before:

	    f = fopen("curds", "r")
	    g = fopen("curds", "r")

	results in two file ids (f and g) that refer to the same file
	name but with different pointers.

    Calc now understands "w+", "a+" and "r+" file modes.

    If calc opens a file without a mode there is a "guess" that mode
    "r+" will work for any files with small descriptors found to be
    open.  In case it doesn't (as apparently happens if the file had
    not been opened for both reading and reading) the function now also
    tries "w" and "r", and if none work, gives up.  This avoids having
    "open" files with null fp.

    The buildin rewind() calls the C rewind() function, but one may
    now rewind several files at once by a call like rewind(f1, f2).
    With no argument, rewind() rewinds all open files with id >= 3.

    The functions fputstr(), fgetstr() have been defined to include the
    terminating '\0' when writing a string to a file.  This can be done
    at present with a sequence of instructions like:

	fputs(f, "Landon"); fputc(f, 0);
	fputs(f, "Curt"); fputc(f, 0);
	fputs(f, "Noll"); fputc(f, 0);

	One may now do:

	    fputstr(f, "Landon", "Curt", "Noll");

	and read them back by:

	    rewind(f);
	    x = fgetstr(f);	/* returns "Landon" */
	    y = fgetstr(f);	/* returns "Curt" */
	    z = fgetstr(f);	/* returns "Noll" */

    The buildin fgetfield() returns the next field of non-whitepsace
    characters.

    The builtins scan(), fscan(), strscan() read tokens (fields of
    non-whitepsace characters) and evaluates them.  Thus:

	global a,b,c;
	strscan("2+3  4^2\n c=a+b", a, b, 0);

	results in a = 5, b = 16, c = 21

    The functions scanf, fscanf, strscanf behave like the C functions
    scanf, fscanf, sscanf.   The conversion specifiers recognized are "%c",
    "%s", "%[...]" as in C, with the options of *, width-specification,
    and complementation (as in [^abc]), and "%n" for file-position, and
    "%f", "%r", "%e", "%i" for numbers or simple number-expressions - any
    width-specification is ignored; the expressions are not to include any
    white space or characters other than decimal digits, +, -, *, /, e, and i.
    E.g. expressions like 2e4i+7/8 are acceptable.

    The builtin size(x) now returns the size of x if x is an open file
    or -1 if x is a file but not open.  If s is a string, size(s) returns
    characters in s.

    Added buildin access("foo", "w") returns the null value if a file
    "foo" exists and is writeable.

    Some systems has a libc symbolc qadd() that conflicted with calc's
    qadd function.  To avoid this, qadd() has been renamed to qqadd().

    The calc error codes are produced from the the calcerr.tbl file.
    Instead of changing #defines in value.h, one can not edit calcerr.tbl.
    The Makefile builds calcerr.h from this file.

    Calc error codes are now as follows:

	<0 			invalid
	0 .. sys_nerr-1		system error ala C's errno values
	sys_nerr .. E__BASE-1	reserved for future system errors
	E__BASE .. E__HIGHEST	calc internal errors
	E__HIGHEST+1 .. E_USERDEF-1	invalid
	E_USERDEF ..		user defined errors

    Currently, E__BASE == 10000 and E_USERDEF == 20000.  Of course,
    sys_nerr is system defined however is likely to be < E__BASE.

    Renamed CONST_TYPE (as defined in have_const.h) to just CONST.
    This symbol will either be 'const' or an empty string depending
    on if your compiler understands const.

    CONST is beginning to be used with read-only tables and some
    function arguments.  This allows certain compilers to better
    optimize the code as well as alerts one to when some value
    is being changed inappropriately.  Use of CONST as in:

	int foo(CONST int curds, char *CONST whey)

    while legal C is not as useful because the caller is protected
    by the fact that args are passed by value.  However, the
    in the following:

	int bar(CONST char *fizbin, CONST HALF *data)

    is useful because it calls the compiler that the string pointed
    at by 'fizbin' and the HALF array pointer at by 'data' should be
    treated as read-only.


Following is the change from calc version 2.10.1t21 to 2.10.2t0:

    Bumped patch level 2.10.2t0 in honor of having help files for
    all builtin functions.  Beta release will happen at the end of
    the 2.10.2 cycle!!!

    Fewer items listed in BUGS due to a number of bug fixes.

    Less todo in the help/todo file because more has already been done.  :-)

    All builtin functions have help files!  While a number need cleanup
    and some of the LIMITS, LIBRARY and SEE ALSO sections need fixing
    (or are missing), most of it is there.  A Big round of thanks goes
    to <ernie@neumann.une.edu.au> for his efforts in initial write-ups
    for many of these files!

    The recognition of '\' as an escape character in the format argument
    of printf() has been dropped.  Thus:

	printf("\\n");

    will print the two-character string "\n" rather than the a
    one-character carriage return.  <ernie@neumann.une.edu.au>

    Missing args to printf-like functions will be treated as null values.

    The scope of of config("fullzero") has been extended to integers,
    so that for example, after config("mode","real"), config("display", 5),
    config("fullzero", 1), both:

	print 0, 1, 2;
	printf("%d %d %d\n", 0, 1, 2);

    print:

	.00000 1.00000, 2.00000

    The bug which caused calc to exit on:

	b = "print 27+"
	eval(b)

    has been fixed.  <ernie@neumann.une.edu.au>

    Fixed bugs in zio.c which caused eval(str(x)) == x to fail
    in non-real modes such as "oct".  <ernie@neumann.une.edu.au>

    The following:

	for (i = 1; i < 10; i++) print i^2,;

    now prints the same as:

	for (i = 1; i < 10; i++) print i^2,;

    The show globals will print '...' in the middle of large values.
    <ernie@neumann.une.edu.au>

    The param(n) builtin, then n > 0, returns the address rather than
    the value of the n-th argument to save time and memory usage.  This
    is useful when a matrix with big number entries is passed as an arg.
    <ernie@neumann.une.edu.au>

    The param(n) builtin, then n > 0, may be used as an lvalue:

	> define g() = (param(2) = param(1));
	> define h() = (param(1)++, param(2)--);
	> u = 5
	> v = 10
	> print g(u, &v), u, v;
	5 5 5
	> print h(&u, &v), u, v;
	5 6 4

    Missing args now evaluate to null as in:

	A = list(1,,3)
	B = list(,,)
	mat C[] = {,,}
	mat D[] = { }


Following is the change from calc version 2.10.1t20 to 2.10.1t20:

    Changes made in preparation for Blum Blum Shub random number generator.

    REDC bug fixes: <ernie@neumann.une.edu.au>

	Fixed yet another bug in zdiv which occasionally caused the "top digit"
	of a nonzero quotient to be zero.

	Fixed a bug in zredcmul() where a rarely required "topdigit" is
	sometimes lost rather than added to the appropriate carry.

    A new function zredcmodinv(ZVALUE z, ZVALUE *res) has been defined for
    evaluating rp->inv in zredcalloc().  <ernie@neumann.une.edu.au>

    New functions zmod5(ZVALUE *zp) and zmod6(ZVALUE z, ZVALUE *res) have
    been defined to give O(N^1.585)-runtime evaluation of z % m for
    large N-word m.  These require m and BASE^(2*N) // m to have been
    stored at named locations lastmod, lastmodinv.  zmod5() is essentially
    for internal use by zmod6() and zpowermod().  <ernie@neumann.une.edu.au>

    Changes to rcmul(x,y,m) so that the result is always in [0, m-1].
    <ernie@neumann.une.edu.au>

    Changes to some of the detail of zredcmul() so that it should run slightly
    faster.  Also changes to zredcsq() in the hope that it might achieve
    something like the improvement in speed of x^2 compared with x * x.
    <ernie@neumann.une.edu.au>

    A new "bignum" algorithm for evaluating pmod(x,k,m) when
    N >= config("pow2").  For the multiplications and squarings
    modulo m, or their equivalent, when N >= config("redc2"),
    calc has used evaluations correponding to rcout(x * y, m),
    for which the runtime is essentially that of three multiplications.
    <ernie@neumann.une.edu.au>

    Yet more additions to the regress.cal test suite.

    Fixed some ANSI-C compile nits in shs.c and quickhash.c.

    Plugs some potential memory leaks in definitions in func.c.
    Expressions such as qlink(vals[2]) in some circumstances are
    neither qfreed nor returned as function values.
    <ernie@neumann.une.edu.au>

    The nextcand() and prevcand() functions handle modval, modulus
    and skip by using ZVALUE rather than ZVALUE * and dropping
    the long modulus, etc.  <ernie@neumann.une.edu.au>

    Changed a couple of occurrences of itoq(1) or itoq(0) to &_qone_
    and &_qzero_.  <ernie@neumann.une.edu.au>

    In definition of f_primetest, changed ztolong(q2->num) to ztoi(q2->num)
    so that the sign of count in ptest(n, count, skip) is not lost; and
    ztolong(q3->num) to q3->num so that skip can be any integer.
    <ernie@neumann.une.edu.au>

    In zprime.c, in definition of small_factor(), adds "&& *tp != 1" to
    the exit condition in the for loop so that searching for a factor
    will continue beyond the table of primes, as required for e.g.
    factor(2^59 - 1).  <ernie@neumann.une.edu.au>

    Changed zprimetest() so that skip in ptest(n, count, skip)
    determines the way bases for the tests are selected.  Neg values of
    n are treated differently.   When considering factorization,
    primeness, etc. one is concerned with equivalence classes which for
    the rational integers are {0}, {-1, 1}, {-2, 2}, etc.  To refer to
    an equivalence class users may use any of its elements but when
    returning a value for a factor the computer normally gives the
    non-negative member.  The same sort of thing happens with integers
    modulo an integer, with fractions, etc., etc.  E.g. users may refer
    to 3/4 as 6/8 or 9/12, etc.  A simple summary of the way negative n
    is treated is "the sign is ignored". E.g. isprime(-97) and
    nextprime(-97) now return the same as isprime(97) and nextprime(97).
    <ernie@neumann.une.edu.au>


Following is the change from calc version 2.10.1t11 to 2.10.1t19:

    Added many more regression tests to lib/regress.cal.  Some
    due to <ernie@neumann.une.edu.au>.

    Added many help files, most due to <ernie@neumann.une.edu.au>.

    Fixed exp() and ln() so that when they return a complex value with a
    zero imaginary component, isreal() is true.  <ernie@neumann.une.edu.au>

    Fixed cast problem in byteswap.c.  <ernie@neumann.une.edu.au>

    Fixed memory leak problem where repeated assignments did not
    free the previous value.  <ernie@neumann.une.edu.au>

    Complex number ordering/comparison has been changed such that:

	a < b implies a + c < b + c
	a < b and c > 0 implies a * c < b * c
	a < b implies -a > -b

    To achieve a "natural" partial ordering of the complex numbers
    with the above properties, cmp(a,b) for real or complex numbers
    may be considered as follows:

	cmp(a,b) = sgn(re(a) - re(b)) + sgn(im(a) - im(b)) * 1i

    The cmp help file has been uptdated.

    Change HASH type to QCKHASH.  The HASH type is a name better suited
    for the upcoming one-way hash interface.

    Added the CONFIG type; a structure containing all of the configuration
    values under the control of config().  Added V_CONFIG data type.
    The call config("all") returns a V_CONFIG.  One may now save/restore
    the configuration state as follows:

	x = config("all")
	...
	config("all",x)

    Added two configuration aliases, "oldstd" (for old backward compatible
    standard configuration) and "newstd" (for new style configuration).
    One may set the historic configuration state by:

	config("all", "oldstd")

    One may use what some people consider to be a better but not backward
    compatible configuration state by:

	config("all", "newstd")

    Renamed config.h (configuration file built during the make) to conf.h.
    Added a new config.h to contain info on thw V_CONFIG type.

    Fixed some ANSI C compile warnings.

    The show config output is not indented by only one tab, unless
    config("tab",0) in which case it is not indented.

    The order of show config has been changed to reflect the config
    type values.

    Changed declaration of sys_errlst in func.c to be char *.

    Added quo(x,y,rnd) and mod(x,y,rnd) to give function interfaces
    to // and % with rounding mode arguments.  Extended these functions
    to work for list-values, complex numbers and matrices.
    <ernie@neumann.une.edu.au>

    For integer x, cfsim(x,8) returns 0.  <ernie@neumann.une.edu.au>

    Fixed config("leadzero").  <ernie@neumann.une.edu.au>

    Set config("cfsim",8) by default (in "oldstd").  Setup initial idea for
    config("all", "newstd") to be the default with the following changes:

	display		10
	epsilon		1e-10
	quo		0
	outround        24
	leadzero	1
	fullzero	1
	prompt		"; "		(allows full line cut/paste)
	more		";; "		(allows full line cut/paste)

    The "newstd" is a (hopefully) more perferred configuration than the
    historic default.

    The fposval.h file defines DEV_BITS and INODE_BITS giving the
    bit size of the st_dev and st_ino stat elements.  Also added
    SWAP_HALF_IN_DEV and SWAP_HALF_IN_STSIZE.

    Added sec(), csc(), cot(), sech(), csch(), coth(), asec(), acsc(),
    acot(), asech(), acsch() and acoth() builtins. <ernie@neumann.une.edu.au>

    The initmasks() call is no longer needed.  The bitmask[] array
    is a compiled into zmath.c directly.

    Added isconfig(), ishash(), isrand() and israndom() builtins to
    test is something is a configuration state, hash state, RAND
    state or RANDOM state.

    The lib/cryrand.cal library now no longer keeps the Blum prime
    factors used to formt he Blum modulus.  The default modulus has
    been expanded to 1062 bits product of two Blum primes.

    The function hash_init() is called to initialize the hash function
    interface.

    Misc calc man page fixes and new command line updates.

    Fixed bug related to srand(1).

    Cleaned up some warning messages.

    All calls to math_error() now have a /*NOTREACHED*/ comment after
    them.  This allows lint and compiler flow progs to note the jumpjmp
    nature of math_error().  Unfortunately some due to some systems
    not dealing with /*NOTREACHED*/ comments correctly, calls of the form:

	if (foo)
		math_error("bar");

    must be turned into:

	if (foo) {
		math_error("bar");
		/*NOTREACHED*/
	}

    The ploy() function can take a list of coefficients.  See
    the help/poly file.  Added poly.c.  <ernie@neumann.une.edu.au>

    Fixes and performance improvemtns to det().  <ernie@neumann.une.edu.au>

    Renamed atoq() and atoz() to str2q() and str2z() to avoid conflicts
    with libc function names.

    Fixed use of ${NROFF_ARG} when ${CATDIR} and ${NROFF} are set.

    Fixed SWAP_HALF_IN_B64 macro use for Big Endian machines without
    long long or with LONGLONG_BITS=0.

    Added error() and iserror() to generate a value of a given error type.
    See help/error for details.  <ernie@neumann.une.edu.au>

    Added singular forms of help files.  For example one can now get
    help for binding, bug, change, errorcode and type.

    The builtin mmin(x, md) has been changed to return the same as
    mod(x, md, 16).  The old mmin(x, md) required md to be a positive
    integer and x to be an integer.  Now md can be any real number; x
    can be real, complex, or a matrix or list with real elements, etc.
    <ernie@neumann.une.edu.au>

    The builtin avg(x_1, x_2, ...) has been changed to accept list-valued
    arguments:  a list x_i contributes its elements to the list of items to
    be averaged.  E.g. avg(list(1,2,list(3,4)),5) is treated as if it were
    avg(1,2,3,4,5).  If an error value is encountered in the items to be
    averaged, the first such value is returned.  If the number of items to be
    averaged is zero, the null value is returned.  <ernie@neumann.une.edu.au>

    The builtin hmean(x_1, x_2, ...) has been changed to admit types
    other than real for x_1, x_2, ...; list arguments are treated in
    the same way as in avg().  <ernie@neumann.une.edu.au>

    The builtin eval(str) has been changed so that when str has a
    syntax error, instead of call to math_error(), an error value is
    returned.  <ernie@neumann.une.edu.au>

    The old frem(x,y) builtin returned the wrong value when y was a power of
    2 greater than 2, e.g. f(8,4) is returned as 4 when its value should be 2.
    This has been fixed by a small change to the definition of zfacrem().
    Calc used to accept with no warning or error message, gcdrem(0,2) or
    generally gcdrem(0,y) for any y with abs(y) > 1, but then went into an
    infinite loop.  This has been fixed by never calling zfacrem() with zero x.
    Both frem(x,y) and gcdrem(x,y) now reject y = -1, 0 or 1 as errors.  For
    nonzero x, and y == -1 or 1, defining frem(x,y) and gcdrem(x,y) to equal
    abs(x) is almost as natural as defining x^0 to be 1.  Similarly, if x is
    not zero then gcdrem(x,0) == 1.
    <ernie@neumann.une.edu.au>

    Plugged some more memory leaks.

    Fixed bug related randbit(x) skip (where x < 0).

    Added seedrandom.cal to help users use the raw random() interface well.

    Made extensive additions and changes to the rand() and random() generator
    comments in zrand.c.

    Fixed a bug in fposval.c that prevented calc from compiling on systems
    with 16 bit device and/or inodes.  Fixed error messages in fposval.c.

    Fixed bug that would put calc into an infinite loop if it is ran
    with errors in startup files (calc/startup, .calcrc).
    Ha Lam <hl@kuhep5.phsx.ukans.edu>


Following is the change from calc version 2.10.0t13 to 2.10.1t10:

    Added SB8, USB8, SB16, USB16, SB32, USB32 typedefs, determined by
    longbits and declared in longbits.h, to deal with 8, 16 and 32 bit
    signed and unsigned values.

    The longbits.h will define HAVE_B64 with a 64 bit type (long or
    longlong) is available.   If one is, then SB64 abd US64 typedefs
    are declared.

    The U(x) and L(x) macros only used to define 33 to 64 bit signed
    and unsigned constants.  Without HAVE_B64, these macros cannot
    be used.

    Changed the way zmath.h declares types such as HALF and FULL.

    Changed the PRINT typedef.

    The only place where the long long type might be used is in longlong.c
    and if HAVE_LONGLONG, in longbits.h if it is needed.  The only place
    were a long long constant might be used is in longlong.c.  Any
    long long constants, if HAVE_LONGLONG, are hidden under the U(x) and
    L(x) macros on longbits.h.  And of course, if you don't have long long,
    then HAVE_LONGLONG will NOT be defined and long long's will not be used.

    The longlong.h file is no longer directly used by the main calc source.
    It only comes into play when compiling the longbits tool.

    Added config("prompt") to change the default interactive prompt ("> ")
    and config("more") to change the default continuation prompt (">> ").

    Makefile builds align32.h with determines if 32 bit values must always
    be aligned on 32 bit boundaries.

    The CALCBINDINGS file is searched for along the CALCPATH.  The Makefile
    defines the default CALCBINDINGS is "bindings" (or "altbind") which
    is now usualy found in ./lib or ${LIBDIR}.

    Per Ernest Bowen <ernie@neumann.une.edu.au>, an optional third argument
    was added  sqrt() so that in sqrt(x,y,z), y and z have essentially the
    same role as in appr(x,y,z) except that of course what is being
    approximated is the sqrt of x.  Another difference is that two more
    bits of z are used in sqrt: bit 5 gives the option of exact results
    when they exist (the value of y is then ignored) and bit 6 returns
    the nonprincipal root rather than the principal value.

    If commands are given on the command line, leading tabs are not
    printed in output.  Giving a command on the command line implies
    that config("tab",0) was given.

    Pipe processing is enabled by use of -p.  For example:

	echo "print 2^21701-1, 2^23209-1" | calc -p | fizzbin

    In pipe mode, calc does not prompt, does not print leading tabs
    and does not print the initial version header.

    Calc will now form FILE objects for any open file descriptor > 2
    and < MAXFILES.  Calc assumes they are available for reading
    and writing.  For example:

	$ echo "A line of text in the file on descriptor 5" > datafile
	$ calc 5<datafile
	C-style arbitrary precision calculator (version 2.10.1t3)
	[Type "exit" to exit, or "help" for help.]

	> files(5)
		FILE 5 "descriptor[5]" (unknown_mode, pos 0)
	> fgetline(files(5))
		"A line of text in the file on descriptor 5"

    The -m mode flag now controls calc's ability to open files
    and execute programs.  This mode flag is a single digit that
    is processed in a similar way as the octal chmod values:

	0   do not open any file, do not execute progs
	1   do not open any file
	2   do not open files for reading, do not execute progs
	3   do not open files for reading
	4   do not open files for writing, do not execute progs
	5   do not open files for writing
	6   do not execute any program
	7   allow everything (default mode)

    Thus if one wished to run calc from a privledged user, one might
    want to use -m 0 in an effort to make calc more secure.

    The -m flags for reading and writing apply on open.
    Files already open are not effected.  Thus if one wanted to use
    the -m 0 in an effort to make calc more secure, but still be
    able to read and write a specific file, one might do:

	calc -m 0 3<a.file 4>b.file

	NOTE: Files presented to calc in this way are opened in an unknown
	      mode.  Calc will try to read or write them if directed.

    The maximum command line size it MAXCMD (16384) bytes.  Calc objects to
    command lines that are longer.

    The -u flag cause calc to unbuffer stdin and stdout.

    Added more help files.  Improved other help files.

    Removed trailing blanks from files.

    Removed or rewrite the formally gross and disgusting hacks for
    dealing with various sizes and byte sex FILEPOS and off_t types.

    Defined ilog2(x), ilog10(x), ilog(x,y) so that sign of x is ignored,
    e.g. ilog2(x) = ilog2(abs(x)).

    The sixth bit of rnd in config("round", rnd) and config("bround", rnd)
    is used to specify rounding to the given number of significant
    digits or bits rather than places, e.g. round(.00238, 2, 32)
    returns .0023, round(.00238, 2, 56) returns .0024.

Following is the change from calc version 2.9.3t11 to 2.10.0t12:

    The default ${LIBDIR}/bindings CALCBINDINGS uses ^D for editing.
    The alternate CALCBINDINGS ${LIBDIR}/altbind uses ^D for EOF.

    The Makefile CC flag system has been changed.  The new CC flag system
    includes:

	CCMAIN are flags for ${CC} when compiling only files with main()
	CCOPT are flags given to ${CC} for optimization
	CCWARN are flags given to ${CC} for warning message control
	CCMISC are misc flags given to ${CC}

	CNOWARN are all flags given to ${CC} except ${CCWARN} flags
	CFLAGS are all flags given to ${CC}
	ICFLAGS are given to ${CC} for intermediate progs

	LCFLAGS are CC-style flags for ${LINT}
	LDFLAGS are flags given to ${CC} for linking .o files
	ILDFLAGS are given to ${CC} for linking .o's for intermediate progs

	CC is how the the C compiler is invoked

    The syntax error:

	print a[3][[4]]

    used to send calc into a loop printing 'missing expression'.  This
    has been fixed.

    Added config("maxerr") and config("maxerr",val) to control the
    maximum number of errors before a computation is aborted.

    Removed regress.cal test #952 and #953 in case calc's stdout or
    stderr is re-directed to a non-file by some test suite.

    Changed how <stdarg.h>, <varags.h> or simulate stdarg is determined.
    Changed how vsprintf() vs sprintf() is determined.  The args.h file
    is created by Makefile to test which combination works.  Setting
    VARARG and/or HAVE_VSPRINTF in the Makefile will alter these tests
    and direct a specific combination to be used.  Removed have_vs.c,
    std_arg.h and try_stdarg.c.  Added have_stdvs.c and have_varvs.c.

    Added 3rd optional arg to round(), bround(), appr() to specify the type of
    rounding to be used.

    Moved fnvhash.c to quickhash.c.

    Fixed a bug in appr rounding mode when >= 16.

    Added test2600.cal and test2700.cal. They are used by the regress.cal
    to provide a more extensive test suite for some builtin numeric
    functions.

Following is the change from calc version 2.9.3t9.2+ to 2.9.3t10:

    Added many help files for builtin functions and some symbols.
    More help files are needed, see help/todo.

    Removed the calc malloc code.  Calc now uses malloc and free to
    manage storage since these implementations are often written to
    work best for the local system.  Removed CALC_MALLOC code and
    Makefile symbol.  Removed alloc.c.

    Added getenv("name"), putenv("name=val") and putenv("name, "val")
    builts for environment variable support thanks to "Dr." "D.J." Picton
    <dave@aps2.ph.bham.ac.uk>.

    Added system("shell command") builtin to execute shell commands,
    thanks to "Dr." "D.J." Picton <dave@aps2.ph.bham.ac.uk>.

    Added isatty(fd) builtin to determine if fd is attached to a tty
    thanks to "Dr." "D.J." Picton <dave@aps2.ph.bham.ac.uk>.

    Added cmdbuf() builtin to return the command line executed by calc's
    command line args thanks to "Dr." "D.J." Picton <dave@aps2.ph.bham.ac.uk>.

    Added strpos(str1,str2) builtin to determine the first position where
    str2 is found in str1 thanks to "Dr." "D.J." Picton
    <dave@aps2.ph.bham.ac.uk>.

    Fixed bug that caused:

	global a,b,c 		(newline with no semicolon)
        read test.cal

    the read command to not be recognized.

    The show command looks at only the first 4 chars of the argument so
    that:

	show globals
	show global
	show glob

    do the same thing.

    Added show config to print the config values and parameters thanks
    to Ernest Bowen <ernie@neumann.une.edu.au>.

    Added show objtypes to print the defined objects thanks to Ernest Bowen
    <ernie@neumann.une.edu.au>.

    Added more builtin function help files.

    Fixed the 3rd arg usage of the root builtin.

    Expanded the regress.cal regression test suite.

    Fixed -- and ++ with respect to objects and asignment (see the 2300
    series in regress.cal).

    Added isident(m) to determine if m is an identity matrix.

    The append(), insert() and push() builtins can now append between
    1 to 100 values to a list.

    Added reverse() and join() builtins to reverse and join lists
    thanks to Ernest Bowen <ernie@neumann.une.edu.au>.

    Added sort() builtin to sort lists thanks to Ernest Bowen
    <ernie@neumann.une.edu.au>.

    Added head(), segment() and tail() builtins to return the head, middle or
    tail of lists thanks to Ernest Bowen <ernie@neumann.une.edu.au>.

    Added more and fixed some help files.

    The builtin help file is generated by the help makefile.  Thus it will
    reflect the actual calc builtin list instead of the last time someone
    tried to update it correctly.  :-)

    Fixed non-standard void pointer usage.

    Fixed base() bug with regards to the default base.

    Renamed MATH_PROTO() and HIST_PROTO() to PROTO().  Moved PROTO()
    into prototype.h.

    Fixed many function prototypes.  Calc does not declare functions
    as static in one place and extern in another.  Where reasonable
    function prototypes were added.  Several arg mismatch problems
    were fixed.

    Added support for SGI MIPSpro C compiler.

    Changes the order that args are declared to match the order
    of the function.  Some source tools got confused when:
    arg order did not match as in:

	void
	funct(foo,bar)
		int bar;	/* this caused a problem */
		char *foo;	/* even though it should not! */
	{
	}

Following is the change from calc version 2.9.3t8 to 2.9.3t9.2:

    Use of the macro zisleone(z) has been clarified.  The zisleone(z) macro
    tests if z <= 1.  The macro zisabsleone(z) tests of z is 1, 0 or -1.
    Added zislezero(z) macro.  Bugs are related to this confusion have
    been fixed.

    Added zge64b(z) macro to zmath.h.

    Added the macro zgtmaxufull(z) to determine if z will fit into a FULL.
    Added the macro zgtmaxlong(z) to determine if z will fit into a long.
    Added the macro zgtmaxulong(z) to determine if z will fit into a unsigned
    long.

    Added the macro ztoulong(z) to convert an absolute value of a ZVALUE to
    an unsigned long, or to convert the low order bits of a ZVALUE.
    Added the macro ztolong(z) to convert an absolute value of a ZVALUE to
    an long, or to convert the low order bits of a ZVALUE.

    Some non-ANSI C compilers define __STDC__ to be 0, whereas all ANSI
    C compiles define it as non-zero.  Code that depends on ANSI C now
    uses #if defined(__STDC__) && __STDC__ != 0.

    Fixed ptest(a,b) bug where (a mod 2^32) < b.  Previously ptest()
    incorrectly returned 1 in certain cases.

    The second ptest() argument, which is now optional, defaults to 1.
    This ptest(x) is the same as ptest(x,1).

    Added an optional 3rd argument to ptest().  The 3rd arg tells how many
    tests to skip.  Thus ptest(a,10) performs the same probabilistic
    tests as ptest(a,3) and ptest(a,7,3).

    The ptest() builtin by default will determine if a value is divisible
    by a trivial prime.  Thus, ptest(a,0) will only perform a quick trivial
    factor check.  If the test count is < 0, then this trivial factor check
    is omitted.  Thus ptest(a,10) performs the same amount of work as
    ptest(a,3) and ptest(a,-7,3) and the same amount of work as
    ptest(a,-3) and ptest(a,7,3).

    Added nextcand(a[,b[,c]]) and prevcand(a[,b[,c]]) to search for the
    next/previous value v > a (or v < a) that passes ptest(v[,b[,c]]).
    The nextcand() and prevcand() builtins take the same arguments
    as ptest().

    Added nextprime(x) and and prevprime(x) return the next and
    previous primes with respect to x respectively.  As of this
    release, x must be < 2^32.  With one argument, they will return
    an error if x is out of range.  With two arguments, they will
    not generate an error but instead will return y.

    Fixed some memory leaks, particularly those related with pmod().

    Fixed some of the array bounds reference problems in domult().

    Added a hack-a-round fix for the uninitialized memory reference
    problems in zsquare/dosquare.

    The LIBRARY file has been updated to include a note about calling
    zio_init() first.  Also some additional useful macros have been noted.

    The lfactor() function returns -1 when given a negative value.
    It will not search for factors beyond 2^32 or 203280221 primes.
    Performance of lfactor() has been improved.

    Added factor(x,y) to look for the smallest factor < min(sqrt(x),y).

    Added libcalcerr.a for a math_error() routine for the convince of
    progs that make use of libcalc.a.  This routine by default will
    print an message on stderr and exit.  It can also be made to
    longjump instead.  See the file LIBRARY under ERROR HANDING.

    Added isprime() to test if a value is prime.  As of this release,
    isprime() is limited to values < 2^32.  With one argument,
    isprime(x) will return an error if x is out of range.  With
    two arguments, isprime(x,y) will not generate an error but
    instead will return y.

    Added pix(x) to return the number of primes <= x.  As of this
    release, x must be < 2^32.  With one argument, pix(x) will
    return an error if x is out of range.  With two arguments,
    pix(x,y) will not generate an error but instead will return y.

    Fixed the way *.h files are formed.  Each file guards against
    multiple inclusion.

    Fixed numeric I/O on 64 bit systems.  Previously the print and
    constant conversion routines assumed a base of 2^16.

    Added support for 'long long' type.  If the Makefile is setup
    with 'LONGLONG_BITS=', then it will attempt to detect support
    for the 'long long' type.  If the Makefile is setup with
    'LONGLONG_BITS=64', then a 64 bit 'long long' is assumed.
    Currently, only 64 bit 'long long' type is supported.
    Use of 'long long' allows one to double the size of the
    internal base, making a number of computations much faster.
    If the Makefile is setup with 'LONGLONG_BITS=0', then the
    'long long' type will not be used, even if the compiler
    supports it.

    Fixed avg() so that it will correctly handle matrix arguments.

    Fixed btrunc() limit.

    The ord("string") function can now take a string of multiple
    characters.  However it still will only operate on the first
    character.

    Renamed stdarg.h to std_arg.h and endian.h endian_calc.h to
    avoid name conflicts with /usr/include on some systems that
    have make utilities that are too smart for their own good.

    Added additive 55 shuffle generator functions rand(), randbits()
    and its seed function srand().  Calling rand(a,b) produces a
    random value over the open half interval [a,b).  With one arg,
    rand(a) is equivalent to rand(0,a).  Calling rand() produces
    64 random bits and is equivalent to rand(0,2^64).

    Calling randbit(x>0) produces x random bits.  Calling randbit(skip<0)
    skips -skip bits and returns -skip.

    The srand() function will return the current state.  The call
    srand(0) returns the initial state.  Calling srand(x), where
    x > 0 will seed the generator to a different state.  Calling
    srand(mat55) (mat55 is a matrix of integers at least 55 elements long)
    will seed the internal table with the matrix elements mod 2^64.
    Finally calling srand(state) where state is a generator state
    also sets/seeds the generator.

    The cryrand.cal library has been modified to use the builtin
    rand() number generator.  The output of this generator is
    different from pervious versions of this generator because
    the rand() builtin does not match the additive 55 / shuffle
    generators from the old cryrand.cal file.

    Added Makfile support for building BSD/386 releases.

    The cmp() builtin can now compare complex values.

    Added the errno() builtin to return the meaning of errno numbers.

    Added fputc(), fputs(), fgets(), ftell(), fseek() builtins.

    Added fsize() builtin to determine the size of an open file.

    Supports systems where file positions and offsets are longer than 2^32
    byte, longer than long and/or are not a simple type.

    When a file file is printed, the file number is also printed:

	FILE 3 "/etc/motd" (reading, pos 127)

    Added matsum() to sum all numeric values in a matrix.

    The following code now works, thanks to a fix by ernie@neumann.une.edu.au
    (Ernest Bowen):

		mat A[3] = {1, 2, 3};
		A[0] = A;
		print A[0];

    Also thanks to ernie, calc can process compound expressions
    such as 1 ? 2 ? 3 : 4 : 5.

    Also^2 thanks to ernie, the = operator is more general:

		(a = 3) = 4		(same as a = 3; a = 4)
		(a += 3) *= 4		(same as a += 3; a *= 4)
		matfill(B = A, 4)	(same as B = A; matfill(B, 4);)

    Also^3 thanks to ernie, the ++ and -- operators are more general.

		a = 3
		++(b = a)		(a == 3, b == 4)
		++++a			(a == 5)
        	(++a)++ == 6		(a == 7)
		(++a) *= b		(a == 32, b == 4)

    Fixed a bug related to calling epsilon(variable) thanks to ernie.

    Removed trailing whitespace from source and help files.

    Some compilers do not support the const type.  The file have_const.h,
    which is built from have_const.c will determine if we can or should
    use const.  See the Makefile for details.

    Some systems do not have uid_t.  The file have_uid_t.h, which is
    built from have_uid_t.c will determine if we can or should depend
    on uid_t being typefed by the system include files.  See the Makefile
    for details.

    Some systems do not have memcpy(), memset() and strchr().  The
    file have_newstr.h, which is built from have_newstr.c will
    determine if we can or should depend libc providing these
    functions.  See the Makefile for details.

    The Makefile symbol DONT_HAVE_VSPRINTF is now called HAVE_VSPRINTF.
    The file have_vs.h, which is built from have_vs.c will determine if
    we can or should depend libc providing vsprintf().  See the Makefile
    for details.

    Removed UID_T and OLD_BSD symbols from the Makefile.

    A make all of the upper level Makefile will cause the all rule
    of the lib and help subdirs to be made as well.

    Fixed bug where reserved keyword used as symbol name caused a core dump.

Following is the change from calc version 2.9.3t7 to 2.9.3t7:

    WARNING: This patch is an beta test patch by chongo@toad.com
	     (Landon Curt Noll).

    The 'show' command by itself will issue an error message
    that will remind one of the possible show arguments.
    (thanks to Ha S. Lam <hl@kuhep4.phsx.ukans.edu>)

    Fixed an ANSI-C related problem with the use of stringindex()
    by the show command.  ANSI-C interprets "bar\0foo..." as if
    it were "bar\017oo...".

    Added a cd command to change the current directory.
    (thanks to Ha S. Lam <hl@kuhep4.phsx.ukans.edu>)

    Calc will not output the initial version string, startup
    message and command prompt if stdin is not a tty.  Thus
    the shell command:

	echo "fact(100)" | calc

    only prints the result.  (thanks to Ha S. Lam <hl@kuhep4.phsx.ukans.edu>)

    The zmath.h macro zisbig() macro was replaced with zlt16b(),
    zge24b(), zge31b(), zge32b() and zgtmaxfull() which are
    independent of word size.

    The 'too large' limit for factorial operations (e.g., fact, pfact,
    lcmfact, perm and comb) is now 2^24.  Previously it depended on the
    word size which in the case of 64 bit systems was way too large.

    The 'too large' limit for exponentiation, bit position (isset,
    digit, ), matrix operations (size, index, creation), scaling,
    shifting, rounding and computing a Fibonacci number is 2^31.
    For example, one cannot raise a number by a power >= 2^31.
    One cannot test for a bit position >= 2^31.  One cannot round
    a value to 2^31 decimal digit places.  One cannot compute
    the Fibonacci number F(2^31).

    Andy Fingerhut <jaf@dworkin.wustl.edu> (thanks!) supplied a fix to
    a subtle bug in the code generation routines.  The basic problem was
    that addop() is sometimes used to add a label to the opcode table
    of a function.  The addop() function did some optimization tricks,
    and if one of these labels happens to be an opcode that triggers
    optimization, incorrect opcodes were generated.

    Added utoz(), ztou() to zmath.c, and utoq(), qtou() to qmath.c
    in preparation for 2.9.3t9 mods.

Following is the change from calc version 2.9.2 to 2.9.3t7:

    WARNING: This patch is an beta test patch by chongo@toad.com
	     (Landon Curt Noll).

    Calc can now compile on OSF/1, SGI and IBM RS6000 systems.

    A number of systems that have both <varargs.h> and <stdarg.h> do
    not correctly implement both types.  On some System V, MIPS and DEC
    systems, vsprintf() and <stdarg.h> do not mix.  While calc will
    pass the regression test, use of undefined variables will cause
    problems.  The Makefile has been modified to look for this problem
    and work around it.

    Added randmprime.cal which find a prime of the form h*2^n-1 >= 2^x
    for some given x.  The initial search points for 'h' and 'n'
    are selected by a cryptographic pseudo-random generator.

    The library script nextprim.cal is now a link to nextprime.cal.
    The lib/Makefile will take care of this link and install.

    The show command now takes singular forms.  For example, the
    command 'show builtin' does the same as 'show builtins'.  This
    allows show to match the historic singular names used in
    the help system.

    Synced 'show builtin' output with 'help builtin' output.

    Fixed the ilog2() builtin.  Previously ilog2(2^-20) returned
    -21 instead of -20.

    The internal function qprecision() has been fixed.  The changes
    ensure that for any e for which 0 < e <= 1:

	1/4 < sup(abs(appr(x,e) - x))/e  <= 1/2.

    Here 'sup' denotes the supremum or least upper bound over values of x.
    Previousld calc did: 1/4 <= sup(abs(appr(x,e) - x))/e  < 1.

    Certain 64 bit processors such as the Alpha are now supported.

    Added -once to the READ command.  The command:

	read -once filename

    like the regular READ expect that it will ignore filename if
    is has been previously read.

    Improved the makefile.  One now can select the compiler type.  The
    make dependency lines are now simple foo.o: bar.h lines.  While
    this makes for a longer list, it is easier to maintain and will
    make future Makefile patches smaller.  Added special options for
    gcc version 1 & 2, and for cc on RS6000 systems.

    Calc compiles cleanly under the watchful eye of gcc version 2.4.5
    with the exception of warnings about 'aggregate has a partly
    bracketed initializer'.  (gcc v2 should allow you to disable
    this type of warning with using -Wall)

    Fixed a longjmp bug that clobbered a local variable in main().

    Fixed a number of cases where local variables or malloced storage was
    being used before being set.

    Fixed a number of fence post errors resulting in reads or writes
    just outside of malloced storage.

    A certain parallel processor optimizer would give up on
    code in cases where math_error() was called.  The obscure
    work-a-rounds involved initializing or making static, certain
    local variables.

    The cryrand.cal library has been improved.  Due to the way
    the initial quadratic residues are selected, the random numbers
    produced differ from previous versions.

    The printing of a leading '~' on rounded values is now a config
    option.  By default, tilde is still printed.  See help/config for
    details.

    The builtin function base() may be used to set the output mode or
    base.  Calling base(16) is a convenient shorthand for typing
    config("mode","hex").  See help/builtin.

    The printing of a leading tab is now a config option.  This does not
    alter the format of functions such as print or printf.  By default,
    a tab is printed.  See help/config for details.

    The value atan2(0,0) now returns 0 value in conformance with
    the 4.3BSD ANSI/IEEE 754-1985 math library.

    For all values of x, x^0 yields 1.  The major change here is
    that 0^0 yields 1 instead of an error.

    Fixed gcd() bug that caused gcd(2,3,1/2) to ignore the 1/2 arg.

    Fixed ltol() rounding so that exact results are returned, similar
    to the way sqrt() and hypot() round, when they exist.

    Fixed a bug involving ilog2().

    Fixed quomod(a,b,c,d) to give correct value for d when a is between
    0 and -b.

    Fixed hmean() to perform the necessary multiplication by the number of
    arguments.

    The file help/full is now being built.

    The man page is not installed by default.  One may install either
    the man page source or the cat (formatted man) page.  See the
    Makefile for details.

    Added a quit binding.  The file lib/bindings2 shows how this new
    binding may be used.

    One can now do a 'make check' to run the calc regression test
    within in the source tree.

    The regression test code is now more extensive.

    Updated the help/todo list.  A BUGS file was added.  Volunteers are
    welcome to send in patches!

Following is the change from calc version 2.9.1 to 2.9.1:

    Fixed floor() for values -1 < x < 0.

    Fixed ceil() for values -1 < x < 0.

    Fixed frac() for values < 0 so that int(x) + frac(x) == x.

    Fixed wild fetch bug in zdiv, zquo and zmod code.

    Fixed bug which caused regression test #719 to fail on some machines.

    Added more regression test code.

Following is the change from calc version 2.9.0 to 2.9.0:

    A major bug was fixed in subtracting two numbers when the first
    number was zero.  The problem caused wrong answers and core dumps.

Following is a list of visible changes to calc from version 1.27.0 to 2.8.0:

    Full prototypes have been provided for all C functions, and are used
    if calc is compiled with an ANSI compiler.

    Newly defined variables are now initialized to the value of zero instead
    of to the null value.  The elements of new objects are also initialized
    to the value of zero instead of null.

    The gcd, lcm, and ismult functions now work for fractional values.

    A major bug in the // division for fractions with a negative divisor
    was fixed.

    A major bug in the calculation of ln for small values was fixed.

    A major bug in the calculation of the ln and power functions for complex
    numbers was fixed.

    A major lack of precision for sin and tan for small values was fixed.

    A major lack of precision for complex square roots was fixed.

    The "static" keyword has been implemented for variables.  So permanent
    variables can be defined to have either file scope or function scope.

    Initialization of variables during their declaration are now allowed.
    This is most convenient for the initialization of static variables.

    The matrix definition statement can now be used within a declaration
    statement, to immediately define a variable as a matrix.

    Initializations of the elements of matrices are now allowed.  One-
    dimensional matrices may have implicit bounds when initialization is
    used.

    The obj definition statement can now be used within a declaration
    statement, to immediately define a variable as an object.

    Object definitions can be repeated as long as they are exactly the same
    as the previous definition.  This allows the rereading of files which
    happen to define objects.

    The integer, rational, and complex routines have been made into a
    'libcalc.a' library so that they can be used in other programs besides
    the calculator.  The "math.h" include file has been split into three
    include files: "zmath.h", "qmath.h", and "cmath.h".

Following is a list of visible changes to calc from version 1.26.4 to 1.26.4:

    Added an assoc function to return a new type of value called an
    association.  Such values are indexed by one or more arbitrary values.
    They are stored in a hash table for quick access.

    Added a hash() function which accepts one or more values and returns
    a quickly calculated small non-negative hash value for those values.

Following is a list of visible changes to calc from version 1.26.2 to 1.26.4:

    Misc fixes to Makefiles.

    Misc lint fixes.

    Misc portability fixes.

    Misc typo and working fixes to comments, help files and the man page.

Following is a list of visible changes to calc from version 1.24.7 to 1.26.1:

    There is a new emacs-like command line editing and edit history
    feature.  The old history mechanism has been removed.  The key
    bindings for the new editing commands are slightly configurable
    since they are read in from an initialization file.  This file is
    usually called /usr/lib/calc/bindings, but can be changed by the
    CALCBINDINGS environment variable.  All editing code is
    self-contained in the new files hist.c and hist.h, which can be
    easily extracted and used in other programs.

    Two new library files have been added: chrem.cal and cryrand.cal.
    The first of these solves the chinese remainder problem for a set
    of modulos and remainders.  The second of these implements several
    very good random number generators for large numbers.

    A small bug which allowed division by zero was fixed.

    A major bug in the mattrans function was fixed.

    A major bug in the acos function for negative arguments was fixed.

    A major bug in the strprintf function when objects were being printed
    was fixed.

    A small bug in the library file regress.cal was fixed.

*************
* contrib
*************

We welcome and encourage you to send us:

    * calc scripts
    * any builtin functions that you have modified or written
    * custom functions that you have modified or written
    * any other source code modifications

Prior to doing so, you should consider trying your changes on the most
recent alpha test code.  To obtain the most recent code, look under

	http://reality.sgi.com/chongo/calc/

You should also consider joining the calc testing group by sending a
request to:

	calc-tester-request@postofc.corp.sgi.com

    Your message body (not the subject) should consist of:

	subscribe calc-tester address
	end
	name your_full_name

    where "address" is your EMail address and "your_full_name"
    is your full name.

In order to consider integrating your code, we need:

    * help files (documentation)
    * CHANGES text (brief description of what it does)
    * regress.cal test (to test non-custom code)
    * your source code and/or source code changes (:-))

The best way to send us new code, if your changes are small, is
via a patch (diff -c from the latest alpha code to your code).
If your change is large, you should send entire files (either
as a diff -c /dev/null your-file patch, or as a uuencoded and
gziped (or compressed) tar file).

You should send submissions to:

	calc-tester@postofc.corp.sgi.com

Thanks for considering submitting code to calc.  Calc is a collective
work by a number of people.  It would not be what it is today without
your efforts and submissions!

Landon Curt Noll <chongo@toad.com> /\oo/\

*************
* credit
*************

Credits

    The majority of calc was written by David I. Bell.

    Calc archives and calc-tester mailing list maintained by Landon Curt Noll.

    Thanks for suggestions and encouragement from Peter Miller,
    Neil Justusson, and Landon Noll.

    Thanks to Stephen Rothwell for writing the original version of
    hist.c which is used to do the command line editing.

    Thanks to Ernest W. Bowen for supplying many improvements in
    accuracy and generality for some numeric functions.  Much of
    this was in terms of actual code which I gratefully accepted.
    Ernest also supplied the original text for many of the help files.

    Portions of this program are derived from an earlier set of
    public domain arbitrarily precision routines which was posted
    to the net around 1984.  By now, there is almost no recognizable
    code left from that original source.

    Most of this source and binary has one of the following copyrights:

	    Copyright (c) 19xx David I. Bell
	    Copyright (c) 19xx David I. Bell and Landon Curt Noll
	    Copyright (c) 19xx Landon Curt Noll
	    Copyright (c) 19xx Ernest Bowen and Landon Curt Noll

    Permission is granted to use, distribute, or modify this source,
    provided that this copyright notice remains intact.

    Send calc comments, suggestions, bug fixes, enhancements and
    interesting calc scripts that you would like you see included in
    future distributions to:

	    dbell@auug.org.au
	    chongo@toad.com

    Landon Noll maintains the official calc ftp archive at:

	ftp://ftp.uu.net/pub/calc

    Alpha test versions, complete with bugs, untested code and
    experimental features may be fetched (if you are brave) under:

	http://reality.sgi.com/chongo/calc/

    One may join the calc testing group by sending a request to:

	calc-tester-request@postofc.corp.sgi.com

    Your message body (not the subject) should consist of:

	subscribe calc-tester address
	end
	name your_full_name

    where "address" is your EMail address and "your_full_name"
    is your full name.

    Enjoy!

*************
* todo
*************

Needed enhancements

    Send calc comments, suggestions, bug fixes, enhancements and
    interesting calc scripts that you would like you see included in
    future distributions to:

	    dbell@auug.org.au
	    chongo@toad.com

    The following items are in the calc wish list.  Programs like this
    can be extended and improved forever.

    *  In general use faster algorithms for large numbers when they
       become known.  In particular, look at better algorithms for
       very large numbers -- multiply, square and mod in particular.

    *  Implement an autoload feature.  Associate a calc library filename
       with a function or global variable.  On the first reference of
       such item, perform an automatic load of that file.

    *  Add error handling statements, so that QUITs, errors from the
       'eval' function, division by zeroes, and so on can be caught.
       This should be done using syntax similar to:

		ONERROR statement DO statement;

       Something like signal isn't versatile enough.

    *  Add a debugging capability so that functions can be single stepped,
       breakpoints inserted, variables displayed, and so on.

    *  Figure out how to write all variables out to a file, including
       deeply nested arrays, lists, and objects.

       Add the ability to read and write a value in some binary form.
       Clearly this is easy for non-neg integers.  The question of
       everything else is worth pondering.

    *  Eliminate the need for the define keyword by doing smarter parsing.

    *  Allow results of a command (or all commands) to be re-directed to a
       file or piped into a command.

    *  Add some kind of #include and #define facility.  Perhaps use
       the C pre-processor itself?

    *  Support a more general input and output base mode other than
       just dec, hex or octal.

    *  Implement a form of symbolic algebra.  Work on this has already
       begun.  This will use backquotes to define expressions, and new
       functions will be able to act on expressions.  For example:

	    x = `hello * strlen(mom)`;
	    x = sub(x, `hello`, `hello + 1`);
	    x = sub(x, `hello`, 10, `mom`, "curds");
	    eval(x);

       prints 55.

    *  Place the results of previous commands into a parallel history list.
       Add a binding that returns the saved result of the command so
       that one does not need to re-execute a previous command simply
       to obtain its value.

       If you have a command that takes a very long time to execute,
       it would be nice if you could get at its result without having
       to spend the time to reexecute it.

    *  Add a binding to delete a value from the history list.

       One may need to remove a large value from the history list if
       it is very large.  Deleting the value would replace the history
       entry with a null value.

    *  Add a binding to delete a command from the history list.

       Since you can delete values, you might as well be able to
       delete commands.

    *  All one to alter the size of the history list thru config().

       In some cases, 256 values is too small, in others it is too large.

    *  Add a builtin that returns a value from the history list.
       As an example:

	    histval(-10)

       returns the 10th value on the history value list, if such
       a value is in the history list (null otherwise).  And:

	    histval(23)

       return the value of the 23rd command given to calc, if
       such a value is in the history list (null otherwise).

       It would be very helpful to use the history values in
       subsequent equations.

    *  Add a builtin that returns command as a string from the
       history list.  As an example:

	    history(-10)

       returns a string containing the 10th command on the
       history list, if a such a value is in the history list
       (empty string otherwise).  And:

	    history(23)

       return the string containing the 23rd command given to calc, if
       such a value is in the history list (empty string otherwise).

       One could use the eval() function to re-evaluate the command.

    *  Allow one to optionally restore the command number to calc
       prompts.  When going back in the history list, indicate the
       command number that is being examined.

       The command number was a useful item.  When one is scanning the
       history list, knowing where you are is hard without it.  It can
       get confusing when the history list wraps or when you use
       search bindings.  Command numbers would be useful in
       conjunction with positive args for the history() and histval()
       functions as suggested above.

    *  Add a builtin that returns the current command number.
       For example:

	    cmdnum()

       returns the current command number.

       This would allow one to tag a value in the history list.  One
       could save the result of cmdnum() in a variable and later use
       it as an arg to the histval() or history() functions.

    *  Add a factoring builtin functions.  Provide functions that perform
       multiple polynomial quadratic sieves, elliptic curve, difference
       of two squares, N-1 factoring as so on.  Provide a easy general
       factoring builtin (say factor(foo)) that would attempt to apply
       whatever process was needed based on the value.

       Factoring builtins would return a matrix of factors.

       It would be handy to configure, via config(), the maximum time
       that one should try to factor a number.  By default the time
       should be infinite.  If one set the time limit to a finite
       value and the time limit was exceeded, the factoring builtin
       would return whatever if had found thus far, even if no new
       factors had been found.

       Another factoring configuration interface, via config(), that
       is needed would be to direct the factoring builtins to return
       as soon as a factor was found.

    *  Allow one to config calc break up long output lines.

       The command:  calc '2^100000'  will produce one very long
       line.  Many times this is reasonable.  Long output lines
       are a problem for some utilities.  It would be nice if one
       could configure, via config(), calc to fold long lines.

       By default, calc should continue to produce long lines.

       One option to config should be to specify the length to
       fold output.  Another option should be to append a trailing
       \ on folded lines (as some symbolic packages use).

    *  Allow one to use the READ and WRITE commands inside a function.

    *  Remove or increase limits on factor(), lfactor(), isprime(),
       nextprime(), and prevprime().  Currently these functions cannot
       search for factors > 2^32.

    *  Add read -once -try "filename" which would do nothing
       if "filename" was not a readable file.

    *  Complete the use of CONST where appropirate:

	CONST is beginning to be used with read-only tables and some
	function arguments.  This allows certain compilers to better
	optimize the code as well as alerts one to when some value
	is being changed inappropriately.  Use of CONST as in:

	    int foo(CONST int curds, char *CONST whey)

	while legal C is not as useful because the caller is protected
	by the fact that args are passed by value.  However, the
	in the following:

	    int bar(CONST char *fizbin, CONST HALF *data)

	is useful because it calls the compiler that the string pointed
	at by 'fizbin' and the HALF array pointer at by 'data' should be
	treated as read-only.

    * Blocks should have the following features:

        + read/write to/from files (ala fread/fwrite)

	+ misc memory functions (ala memcpy, memcmp, memset,
	  memchr, etc.)

	+ scatter and gather functions (to send every n-th octet
	  to another block and to copy from n blocks, the 1st
	  then 2nd then 3rd ... octets)

    * Printing of blocks should be under the control of the
      config() interface.  This should allow one to select
      from any of the following formats:

	+ as one long string

	+ as a series of lines (< 80 chars wide)

	+ in od command style (offset: value value value ...)

	+ in hex dump style (offset: val val val val ...  3hf.Uas.c)

    * In addition one should be able to control the following
      aspects of printing blocks via the config() interface:

	+ base (hex, octal, char, base 2)

	+ amount of data (the first n octets or the entire block)

	+ skipping printing of duplicate print lines (ala od)

	+ have the ability to print the block as raw data

    * It is overkill to have nearly everything wind up in libcalc.a.

      One should make available a the fundimental math operations
      on ZVALUE, NUMBER and perhaps COMPLEX (without all of the
      other stuff) in a separate library.
