The \ALBERTA toolbox provides two header files 
\code{alberta\_util.h}\idx{include files!alberta_util.h@{\code{alberta\_util.h}}}
and \code{alberta.h}\idx{include files!alberta.h@{\code{alberta.h}}}, which
contain the definitions of all data structures, macros, and subroutine
prototypes.  The file \code{alberta\_util.h} is included in the header
file \code{alberta.h}.

\section{Basic types, utilities, and parameter handling}%
\label{S:types.util}

The file \code{alberta\_util.h} contains some type definitions and
macro definitions for memory \hbox{(de-)} allocation and messages,
which we describe briefly in this section. The following system header
files are included in \code{alberta\_util.h}
\bv\begin{verbatim}
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
\end{verbatim}\ev

\subsection{Basic types}%
\label{basic_types}

\ALBERTA uses the following elementary symbolic constants and macro 
definitions:
\cdx{true@{\code{true}}}
\cdx{false@{\code{false}}}
\cdx{nil@{\code{nil}}}
\mdx{MAX()@{\code{MAX()}}}
\mdx{MIN()@{\code{MIN()}}}
\mdx{ABS()@{\code{ABS()}}}
\mdx{SQR()@{\code{SQR()}}}
\bv\begin{verbatim}
#define true          1
#define false         0
#define nil           NULL
#define MAX(a, b)     ((a) > (b) ? (a) : (b))
#define MIN(a, b)     ((a) < (b) ? (a) : (b))
#define ABS(a)        ((a) >= 0 ? (a) : -(a))
#define SQR(a)        ((a)*(a))
\end{verbatim}\ev
%
In order to store information in a compact way,
we define two bit fields \code{U\_CHAR} and \code{S\_CHAR}:
%
\ddx{U_CHAR@{\code{U\_CHAR}}}%
\ddx{S_CHAR@{\code{S\_CHAR}}}%
\bv\begin{verbatim}
typedef unsigned char       U_CHAR;
typedef signed char         S_CHAR;
\end{verbatim}\ev
%
The mesh traversal routines need flags which are stored in the
data type \code{FLAGS}:
%
\ddx{FLAGS@{\code{FLAGS}}}
\bv\begin{verbatim}
typedef unsigned long       FLAGS;
\end{verbatim}\ev
%
By the data type \code{REAL} the user can specify to store floating
point values in the type \code{float} or \code{double}. All pointers
to variables or vectors of floating point values have to be defined
as \code{REAL}!
%
\ddx{REAL@{\code{REAL}}}
\bv\begin{verbatim}
typedef double              REAL;
\end{verbatim}\ev
%
The use of \code{float} is also possible, but it is not guaranteed to
work and may lead to problems when using other libraries (like libraries for 
linear solver or graphics, e.g.).

\subsection{Message macros}%
\label{S:messages}%
\idx{messages}

There are several macros to write messages and error messages.
Especially for error messages the exact location of the error is
of interest. Thus, error messages are preceded by the name of
the source file and the line number where this error was detected.
Such information is produced by the \code{C}-preprocessor.
Additionally, the name of the function is printed. Since there
is no symbolic constant defined by the \code{C}-preprocessor
holding the function name, in each function a string \code{funcName} 
containing the name of the function has to be defined. This is usually
done by the macro \code{FUNCNAME}
\mdx{FUNCNAME()@{\code{FUNCNAME()}}}
\bv\begin{verbatim}
#define FUNCNAME(nn)  const char *funcName = nn
\end{verbatim}\ev
as the first declaration:
\begin{example}[\code{FUNCNAME}]
\bv\begin{verbatim}
static void refine_element(EL *el)
{
   FUNCNAME("refine_element");

   ...
}
\end{verbatim}\ev
\end{example}

All message macros use this local variable \code{funcName} and it has 
to be defined in each function using message macros.

Usual output to \code{stdout} is done by the macro \code{MSG()} which has
the same arguments as \code{printf()}: 
\mdx{MSG()@{\code{MSG()}}}
\bv\begin{verbatim}
MSG(const char *format, ...);
\end{verbatim}\ev
The format string should be ended with the newline character \code{`\bs{}n'}.
\code{MSG()} usually precedes the message by the function's
name. If the previous message was produced by the same function, the 
function's name is omitted and the space of the name is filled with blanks.

If the format string of \code{MSG()} does not end with the newline
character, and one wants to print more information to the same line,
this can be done by \code{print\_msg()} which again has the
same arguments as \code{printf()}:
\fdx{print_msg()@{\code{print\_msg()}}}
\bv\begin{verbatim}
print_msg(const char *format, ...);
\end{verbatim}\ev

\begin{example}[\code{MSG()}, \code{print\_msg()}]
\bv\begin{verbatim}
static void refine_element(EL *el)
{
   FUNCNAME("refine_element");

   ...

   MSG("refining element %d\n", INDEX(el));
   MSG("neighbours of element: ");
   for (i = 0; i < N_VERTICES-1; i++)
      print_msg("%d, ", INDEX(NEIGH(el)[i]));
   print_msg("%d\n", INDEX(NEIGH(el)[N_VERTICES-1]));
}
\end{verbatim}\ev
produces for instance output 
\bv\begin{verbatim}
refine_element:    refining element 10
                   neighbours of element: 0, 14, 42
\end{verbatim}\ev
\end{example}

A simpler way to print vectors of integer or real numbers is provided
by the macros \code{PRINT\_INT\_VEC} and \code{PRINT\_REAL\_VEC}.
\mdx{PRINT_INT_VEC()@{\code{PRINT\_INT\_VEC()}}}%
\mdx{PRINT_REAL_VEC()@{\code{PRINT\_REAL\_VEC()}}}
\bv\begin{verbatim}
PRINT_INT_VEC(const char *s, const int *vec, int no);
PRINT_REAL_VEC(const char *s, const REAL *vec, int no);
\end{verbatim}\ev
Based on the \code{MSG()} and \code{print\_msg()} mechanisms, a
comma-separated list of the \code{no} vector elements is produced. 
\begin{example}[\code{PRINT\_REAL\_VEC()}]
\bv\begin{verbatim}
{
   FUNCNAME("test_routine");
   REAL_D point;
   ...

   PRINT_REAL_VEC("point coordinates", point, DIM_OF_WORLD);
}
\end{verbatim}\ev
generates for the second unit vector in 3D the output 
\bv\begin{verbatim}
test_routine:      point coordinates = (0.00000, 1.00000, 0.00000)
\end{verbatim}\ev
\end{example}


Often it is useful to suppress messages or to give only information
up to a suitable level. There are two ways for defining such a level
of information. The first one is a local level, which is determined 
by some variable in a function; the other one is a global restriction
for information. For this global restriction a global variable
%
\idx{msg_info@{\code{msg\_info}}}
\bv\begin{verbatim}
int      msg_info = 10;
\end{verbatim}\ev
%
is defined with an default value of \code{10}.
Using one of the macros
%
\mdx{INFO()@{\code{INFO()}}}
\mdx{PRINT_INFO()@{\code{PRINT\_INFO()}}}
\bv\begin{verbatim}
#define INFO(info,noinfo, ...)                          \
  do {                                                  \
    if (msg_info&&(MIN(msg_info,(info))>=(noinfo))) {   \
      print_funcname(funcName); print_msg(__VA_ARGS__); \
    }                                                   \
  } while (0)

#define PRINT_INFO(info,noinfo, ...)                    \
  do {                                                  \
    if (msg_info&&(MIN(msg_info,(info))>=(noinfo))) {   \
      print_msg(__VA_ARGS__);                           \
    }                                                   \
  } while (0)
\end{verbatim}\ev
%
only messages are produced by \code{INFO()} or
\code{PRINT\_INFO()} if \code{msg\_info} is non zero and
the value \code{MIN(msg\_info, info)} is greater or equal \code{noinfo},
where \code{noinfo} denotes some local level of information.
Thus after setting \code{msg\_info = 0}, no further messages are
produced. Changing the value of this variable via a parameter file 
is described below in \secref{S:par_util}.

\begin{example}[\code{INFO()}, \code{PRINT\_INFO()}]
\bv\begin{verbatim}
static void refine_element(EL *el)
{
   FUNCNAME("refine_element");

   ...

   INFO(info,4,"refining element %d\n", INDEX(el));
   INFO(info,6,"neighbours of element: ");
   for (i = 0; i < N_VERTICES-1; i++)
      PRINT_INFO(info,6,"%d, ", INDEX(NEIGH(el)[i]));
    PRINT_INFO(info,6,"%d\n", INDEX(NEIGH(el)[N_VERTICES-1]));
}
\end{verbatim}\ev
will print the element index, if the value of the global variable
$\code{info} \geq \code{4}$ and additionally the indices
of neighbours if $\code{info} \geq \code{6}$.
\end{example}

For error messages macros \code{ERROR} and \code{ERROR\_EXIT} are
defined. \code{ERROR} has the same functionality as the \code{MSG}
macro but the output is piped to \code{stderr}. \code{ERROR\_EXIT}
exits the program with return value 1 after using the \code{ERROR}:
\mdx{ERROR()@{\code{ERROR()}}}
\mdx{ERROR_EXIT()@{\code{ERROR\_EXIT()}}}
\bv\begin{verbatim}
ERROR(const char *format, ...);
ERROR_EXIT(const char *format, ...);
\end{verbatim}\ev
%
Furthermore, two macros for testing boolean values are available:
%
\mdx{TEST()@{\code{TEST()}}}
\mdx{TEST_EXIT()@{\code{TEST\_EXIT()}}}
\bv\begin{verbatim}
#define TEST(test, ...)                                               \
  do {                                                                \
    if (!(test)) {                                                    \
      print_error_funcname(funcName, __FILE__, __LINE__);             \
      print_error_msg(__VA_ARGS__);                                   \
    }                                                                 \
  } while (0)
#define TEST_EXIT(test, ...)                                          \
  do {                                                                \
    if (!(test)) {                                                    \
      print_error_funcname(funcName, __FILE__, __LINE__);             \
      print_error_msg_exit(__VA_ARGS__);                              \
    }                                                                 \
  } while (0)
\end{verbatim}\ev
If \code{test} is not true both macros will print the specified error message.
\code{TEST} will continue the program afterwards, meanwhile \code{TEST\_EXIT}
will exit the program with return value 1.

Error messages can not be suppressed and the information variable
\code{msg\_info} does not influence these error functions.

\begin{example}[\code{TEST()}, \code{TEST\_EXIT()}]
\bv\begin{verbatim}
static void refine_element(EL *el)
{
   FUNCNAME("refine_element");

   TEST_EXIT(el, "no element for refinement\n");
   ...
}
\end{verbatim}\ev
\end{example}

Finally, there exists a macro \code{WARNING} for writing
warnings to the same stream as for messages. Each warning
is preceeded by the word \texttt{WARNING}. Warnings can not
be suppressed by the information variable \code{msg\_info}.
\mdx{WARNING()@{\code{WARNING()}}}
\bv\begin{verbatim}
WARNING(const char *format, ...);
\end{verbatim}\ev

Sometimes it may be very useful to write messages to file, or write
parts of messages to file. By the functions
\fdx{change_msg_out()@{\code{change\_msg\_out()}}}
\fdx{open_msg_file()@{\code{open\_msg\_file()}}}
\bv\begin{verbatim}
void change_msg_out(FILE *fp);
void open_msg_file(const char *filename, const char *type);
\end{verbatim}\ev
the user can select a new stream or file for message output.
Using the first routine, the user directly specifies the new stream
\code{fp}. If this stream is non nil, all messages are flushed
to this stream, otherwise \ALBERTA will use the old stream furthermore.
The function \code{open\_msg\_file()} acts like
\code{change\_msg\_out(fopen(filename, type))}.

Similar functions are available for error messages and they act
in the same manner on the output stream for error messages:
\fdx{change_error_out()@{\code{change\_error\_out()}}}
\fdx{open_error_file()@{\code{open\_error\_file()}}}
\bv\begin{verbatim}
void change_error_out(FILE *fp);
void open_error_file(const char *filename, const char *type);
\end{verbatim}\ev

For setting breakpoints in the program two macros
\mdx{WAIT@\code{WAIT}} 
\mdx{WAIT_REALLY@\code{WAIT\_REALLY}}
\bv\begin{verbatim}
WAIT
WAIT_REALLY
\end{verbatim}\ev
are defined.
\begin{descr}
\kitem{WAIT} this macro uses a global variable \code{msg\_wait} 
 and if the value of this variable is not zero the statement
 \code{WAIT;} will produce the message
\bv\begin{verbatim}
                    wait for <enter> ...
\end{verbatim}\ev
 and will continue after pressing the \code{enter} or \code{return}
 key. If the value of \code{msg\_wait} is zero, no message is produced
 and the program continues. The value of \code{msg\_wait} can be
 modified by the parameter tools (see \secref{S:par_util}).
\kitem{WAIT\_REALLY} the statement \code{WAIT\_REALLY} will always 
  produce the above message and will wait for pressing the
  \code{enter} or \code{return} key.
\end{descr}

If not disabled by the installer, \ALBERTA libraries are also available in 
versions suited for debugging of code. In the debugging version the macro 
\code{ALBERTA\_DEBUG} set to \code{1}. The
functionality of some \ALBERTA routines and macros is changed in the
debugging versions. Specifically, more safety tests are carried out
that are normally unnecessary in optimized production versions of
code. We provide the following additional message macros which are
only active in the debug versions of \ALBERTA:
\mdx{DEBUG_TEST@\code{DEBUG\_TEST}} 
\mdx{DEBUG_TEST_EXIT@\code{DEBUG\_TEST\_EXIT}}
\bv\begin{verbatim}
DEBUG_TEST
DEBUG_TEST_EXIT
\end{verbatim}\ev
These macros have the same behaviour as the corresponding macros
without the \code{DEBUG}-prefix if \code{ALBERTA\_DEBUG} is set, and
are ignored otherwise.

\subsection{Memory allocation and deallocation}%
\label{memory}%
\idx{memory (de--) allocation|(}

\ALBERTA keeps track of the amount of memory which is allocated and
de--allocated by the routines described below. Information about
the currently used amount of allocated memory can be obtained by calling
the function
\fdx{print_mem_use()@{\code{print\_mem\_use()}}}
\idx{memory (de--) allocation!print_mem_use()@{\code{print\_mem\_use()}}}
\bv\begin{verbatim}
void print_mem_use();
\end{verbatim}\ev

\subsubsection{General Allocation}
\label{S:general_memory_allocation}

Various functions and macros for memory allocation and deallocation
are implemented. The basic ones are
%
\fdx{alberta_alloc()@{\code{alberta\_alloc()}}}
\fdx{alberta_realloc()@{\code{alberta\_realloc()}}}
\fdx{alberta_calloc()@{\code{alberta\_calloc()}}}
\fdx{alberta_free()@{\code{alberta\_free()}}}
\idx{memory (de--) allocation!alberta_alloc()@{\code{alberta\_alloc()}}}
\idx{memory (de--) allocation!alberta_realloc()@{\code{alberta\_realloc()}}}
\idx{memory (de--) allocation!alberta_calloc()@{\code{alberta\_calloc()}}}
\idx{memory (de--) allocation!alberta_free()@{\code{alberta\_free()}}}
\bv\begin{verbatim}
void *alberta_alloc(size_t, const char *, const char *,int);
void *alberta_realloc(void *, size_t, size_t, const char *, const char *, int);
void *alberta_calloc(size_t, size_t, const char *, const char *,int);
void alberta_free(void *, size_t);
\end{verbatim}\ev
In the following \code{name} is a pointer to the string holding the
function name of the calling function (defined by the \code{FUNCNAME}
macro, e.g.), \code{file} a pointer to the string holding the name of
the source file (generated by the \code{\_\_FILE\_\_} \code{CPP}
macro) and \code{line} is the line number of the call (generated by
the \code{\_\_LINE\_\_} \code{CPP} macro). All functions will exit the
running program with an error message, if the size to be allocated is
0 or the memory allocation by the system functions fails.
\begin{descr}
\kitem{alberta\_alloc(size, name, file, line)} returns a pointer to a
 block of memory of at least the number of bytes specified by \code{size}.
\kitem{alberta\_realloc(ptr, o\_size, n\_size, name, file, line)}
  changes the size of the block of memory pointed to by the pointer 
  \code{ptr} to the number of bytes specified by \code{n\_size}, and 
  returns a pointer to the block.  The contents of the block
  remain unchanged up to the lesser of the \code{o\_size} and 
  \code{n\_size}; if necessary, a new block is allocated, and data 
  is copied to it; if the \code{ptr} is a \nil pointer, 
  the \code{alberta\_realloc()} function allocates a new block
  of the requested size.
\kitem{alberta\_calloc(n\_el, el\_size, name, file, line)} returns a
  pointer to a vector with the \code{n\_el} number of elements, where
  each element is of the size \code{el\_size}; the space is
  initialized to zeros.
\kitem{alberta\_free(ptr, size)} frees the block of memory pointed to by 
 the argument \code{ptr} for further allocation; \code{ptr} must have been
 previously allocated by either \code{alberta\_alloc()}, 
 \code{alberta\_realloc()}, or \code{alberta\_calloc()}.
\end{descr}
%
A more comfortable way to use these functions, is the use of the
following macros:
\mdx{MEM_ALLOC()@{\code{MEM\_ALLOC()}}}%
\mdx{MEM_CALLOC()@{\code{MEM\_CALLOC()}}}%
\mdx{MEM_REALLOC()@{\code{MEM\_REALLOC()}}}%
\mdx{MEM_FREE()@{\code{MEM\_FREE()}}}%
\idx{memory (de--) allocation!MEM_ALLOC()@{\code{MEM\_ALLOC()}}}%
\idx{memory (de--) allocation!MEM_CALLOC()@{\code{MEM\_CALLOC()}}}%
\idx{memory (de--) allocation!MEM_REALLOC()@{\code{MEM\_REALLOC()}}}%
\idx{memory (de--) allocation!MEM_FREE()@{\code{MEM\_FREE()}}}%
\bv\begin{verbatim}
TYPE* MEM_ALLOC(size_t, TYPE);
TYPE* MEM_REALLOC(TYPE *, size_t, size_t, TYPE);
TYPE* MEM_CALLOC(size_t, TYPE);
TYPE* MEM_FREE(TYPE *, size_t, TYPE);
\end{verbatim}\ev
They supply the above described functions with the function name,
file name and line number automatically. For an allocation
by these macros, the number of elements and the data type have
to be specified; the actual size in bytes is computed automatically.
Additionally, casting to the correct type is performed.
\begin{descr}
\kitem{MEM\_ALLOC(n, TYPE)}
 returns a pointer to a vector of type \code{TYPE} with the \code{n}
 number of elements.
\kitem{MEM\_REALLOC(ptr, n\_old, n\_new, TYPE)}
   reallocates the vector of type \code{TYPE} at pointer \code{ptr}
   with \code{n\_old} elements for \code{n\_new} elements; values of
   the vector are not changed for all elements up to the minimum of
   \code{n\_old} and \code{n\_new}; returns a pointer to the
   new vector.
\kitem{MEM\_CALLOC(n, TYPE)}
 returns a pointer to a vector of type \code{TYPE} with the \code{n}
 number of elements; the elements are initialized to zeros.
\kitem{MEM\_FREE(ptr, n, TYPE)}
   frees a vector of type \code{TYPE} with \code{n} number of elements
   at \code{ptr}, allocated previously by either \code{MEM\_ALLOC()}, 
   \code{MEM\_REALLOC()}, or \code{MEM\_CALLOC()}.
\end{descr}

\begin{example}[\code{MEM\_ALLOC()}, \code{MEM\_FREE()}]
\bv\begin{verbatim}
   REAL  *u = MEM_ALLOC(10, REAL);
   ...
   MEM_FREE(u, 10, REAL);
\end{verbatim}\ev
allocates a vector of 10 \code{REAL}s and frees this vector again.
\end{example}

\subsubsection{Allocation of matrices}
\label{S:matrix_allocation}

For some applications matrices are needed too. Matrices can be
allocated and freed by the functions
\fdx{alberta_matrix()@\code{alberta\_matrix()}}
\fdx{free_alberta_matrix()@{\code{free\_alberta\_matrix()}}}
\idx{memory (de--) allocation!alberta_matrix()@\code{alberta\_matrix()}}
\idx{memory (de--) allocation!free_alberta_matrix()@{\code{free\_alberta\_matrix()}}}
\bv\begin{verbatim}
void **alberta_matrix(size_t, size_t, size_t, const char *, const char *, int);
void free_alberta_matrix(void **, size_t, size_t, size_t);
\end{verbatim}\ev

\begin{descr}
\kitem{alberta\_matrix(nr, nc, el\_size, name, file, line)}
  returns a pointer \code{**ptr} to a matrix with \code{nr} number of
  rows and \code{nc} number of columns,  where each element is of 
  size \code{el\_size}; \code{name} is a string holding the
  name of the calling function, \code{file} a string holding the
  name of the source file and \code{line} the line number of the
  call.
\kitem{free\_alberta\_matrix(ptr, nr, nc, el\_size)}
  frees the matrix pointed to by \code{ptr}, previously allocated
  by \code{alberta\_matrix()}.
\end{descr}
%
Again, the following macros simplify the use of the above functions:
%
\mdx{MAT_ALLOC()@{\code{MAT\_ALLOC()}}}%
\mdx{MAT_FREE()@{\code{MAT\_FREE()}}}%
\idx{memory (de--) allocation!MAT_ALLOC()@{\code{MAT\_ALLOC()}}}%
\idx{memory (de--) allocation!MAT_FREE()@{\code{MAT\_FREE()}}}%
\bv\begin{verbatim}
TYPE** MAT_ALLOC(size_t, size_t, TYPE);
void   MAT_FREE(TYPE **, size_t, size_t, TYPE);
\end{verbatim}\ev
They supply the above described functions with the function name,
file name and line number automatically. These macros need
the type of the matrix elements instead of the size. Casting
to the correct type is performed.
\begin{descr}
\kitem{MAT\_ALLOC(nr, nc, type)}
    returns a pointer \code{**ptr} to a matrix with elements \code{ptr[i][j]}
    of type \code{TYPE} and indices in the range \code{0 $\le$ i $ <$ nr}
    and \code{0 $\le$ j $ < $ nc}.
\kitem{MAT\_FREE(ptr, nr, nc, type)}
    frees a matrix allocated by \code{MAT\_ALLOC()}.
\end{descr}

\subsubsection{Allocation and management of workspace}
\label{S:workspace_allocation}

Many subroutines need additional workspace for storing vectors, etc.
(linear solvers like conjugate gradient methods, e.g.). Many applications
need such kinds of workspaces for several functions. In order to
make handling of such workspaces easy, a data structure \code{WORKSPACE}
is available. In this data structure a pointer to the workspace
and the actual size of the workspace is stored.
\ddx{WORKSPACE@{\code{WORKSPACE}}}
\bv\begin{verbatim}
typedef struct workspace    WORKSPACE;

struct workspace
{
  size_t  size;
  void    *work;
};
\end{verbatim}\ev
The members yield following information:
\begin{descr}
\kitem{size} actual size of the workspace in bytes.
\kitem{work} pointer to the workspace.
\end{descr}
%
The following functions access and enlarge workspaces:
\fdx{get_workspace()@{\code{get\_workspace()}}}
\idx{memory (de--) allocation!get_workspace()@{\code{get\_workspace()}}}
\fdx{realloc_workspace()@{\code{realloc\_workspace()}}}
\idx{memory (de--) allocation!realloc_workspace()@{\code{realloc\_workspace()}}}
\bv\begin{verbatim}
WORKSPACE *get_workspace(size_t, const char *, const char *, int);
WORKSPACE *realloc_workspace(WORKSPACE *,size_t,const char *,const char *,int);
\end{verbatim}\ev
Description:
\begin{descr}
\kitem{get\_workspace(size, name, file, line)}
  return value is a pointer to a \code{WORKSPACE} structure holding a
  vector of length \code{size} bytes;
  \code{name} is a string holding the name of
  the calling function, \code{file} a string holding the name of the
  source file and \code{line} the line number of the call.
\kitem{realloc\_workspace(work\_space, size, name, file, line)}
  return value is a pointer to a \code{WORKSPACE} structure holding a
  vector of at least length \code{size} bytes; the member \code{size}
  holds the true length of the vector \code{work}; if
  \code{work\_space} is a \nil pointer, a new \code{WORKSPACE}
  structure is allocated; \code{name} is a string holding the name of
  the calling function, \code{file} a string holding the name of the
  source file and \code{line} the line number of the call.
\end{descr}
The macros
\mdx{GET_WORKSPACE()@{\code{GET\_WORKSPACE()}}}
\idx{memory (de--) allocation!GET_WORKSPACE()@{\code{GET\_WORKSPACE()}}}
\mdx{REALLOC_WORKSPACE()@{\code{REALLOC\_WORKSPACE()}}}
\idx{memory (de--) allocation!REALLOC_WORKSPACE()@{\code{REALLOC\_WORKSPACE()}}}
\bv\begin{verbatim}
WORKSPACE* GET_WORKSPACE(size_t)
WORKSPACE* REALLOC_WORKSPACE(WORKSPACE*, size_t)
\end{verbatim}\ev
simplify the use of \code{get\_workspace()}
 and \code{realloc\_workspace()} by supplying the
function with \code{name}, \code{file}, and \code{line}.
\begin{descr}
\kitem{GET\_WORKSPACE(ws, size)} 
  returns a pointer to \code{WORKSPACE} structure holding a vector
  of length \code{size} bytes.
\kitem{REALLOC\_WORKSPACE(ws, size)} 
  returns a pointer to \code{WORKSPACE} structure holding a vector
  of at least length \code{size} bytes; the member \code{size} holds
  the true length of the vector \code{work}; if \code{ws} is a \nil
  pointer, a new \code{WORKSPACE} structure is allocated.
\end{descr}
The functions
\fdx{clear_workspace()@{\code{clear\_workspace()}}}
\fdx{free_workspace()@{\code{free\_workspace()}}}
\idx{memory (de--) allocation!clear_workspace()@{\code{clear\_workspace()}}}
\idx{memory (de--) allocation!free_workspace()@{\code{free\_workspace()}}}
\bv\begin{verbatim}
void clear_workspace(WORKSPACE *);
void free_workspace(WORKSPACE *);
\end{verbatim}\ev
are used for \code{WORKSPACE} deallocation. Description:
\begin{descr}
\kitem{clear\_workspace(ws)} frees the vector \code{ws->work} and
sets \code{ws->work} to \nil and \code{ws->size} to \code{0};
the structure \code{ws} is not freed.
\kitem{free\_workspace(ws)} frees the vector \code{ws->work} and
then the structure \code{ws}.
\end{descr}
For convenience, the corresponding macros are defined as well.
\mdx{CLEAR_WORKSPACE()@{\code{CLEAR\_WORKSPACE()}}}
\idx{memory (de--) allocation!CLEAR_WORKSPACE()@{\code{CLEAR\_WORKSPACE()}}}
\mdx{FREE_WORKSPACE()@{\code{FREE\_WORKSPACE()}}}
\idx{memory (de--) allocation!FREE_WORKSPACE()@{\code{FREE\_WORKSPACE()}}}
\bv\begin{verbatim}
void CLEAR_WORKSPACE(WORKSPACE *)
void FREE_WORKSPACE(WORKSPACE *)
\end{verbatim}\ev

\subsubsection{Allocation of ``scratch'' memory with easy cleanup}
\label{S:scratch_memory}

Sometimes it is convenient to allocate a lot of objects dynamically;
afterwards one always has the dilemma that one has to keep track of
each object individually, in order to avoid memory leaks. The
following support macros allow the allocation of many small objects of
different size from a single pool, with the option to free up the
memory for the entire pool at once. Individual object, however, may
not be freed individually.

\begin{lstlisting}
typedef struct obstack SCRATCH_MEM[1];
typedef struct obstack *SCRATCH_MEM_PTR; /* A reference to an existing pool */
\end{lstlisting}

As can be seen, currently these ``scratch'' memory regions are based on the GNU obstack framework, but an application should not rely on this fact.

\noindent
Initialization of such a scratch memory area:
\begin{lstlisting}
SCRATCHM_MEM handle;

SCRATCH_MEM_INIT(handle);
\end{lstlisting}

\noindent
Allocation from a scratch-memory pool:
\begin{lstlisting}
ptr = SCRATCH_MEM_ALLOC(handle, n_elem, type);
ptr = SCRATCH_MEM_CALLOC(handle, n_elem, type);
\end{lstlisting}

\noindent
Cleaning up:
\begin{lstlisting}
SCRATCH_MEM_ZAP(handle);
\end{lstlisting}
Afterwards, \code{handle} has to be reinitialized before it can be
used again, calling \code{SCRATCH\_MEM\_INIT(handle)}.

\noindent
Copying of scratch-memory handles:
\begin{lstlisting}
SCRATCH_MEM to;
SCRATCH_MEM from;

SCRATCH_MEM_INIT(from);

SCRATCH_MEM_CPY(to, from);
\end{lstlisting}
Note that this is a shallow copy: only the administrative data
structures are copied, not the underlying data. Calling
\code{SCRATCH\_MEM\_ZAP()} with interchangeably either \code{to} or
\code{from} as argument will destroy the underlying data.

%For the handling of general linked lists, 
%data structures and memory allocation functions are defined.
%\ddx{VOID_LIST_ELEMENT@{\code{VOID\_LIST\_ELEMENT}}}
%\bv\begin{verbatim}
%typedef struct void_list_element VOID_LIST_ELEMENT;

%struct void_list_element
%{
%  void               *data;
%  VOID_LIST_ELEMENT  *next;
%};

%\end{verbatim}\ev
%The members yield following information:
%\begin{descr}
%\kitem{data} pointer to data section of list element.
%\kitem{next} pointer to next list element.
%\end{descr}
%%
%Such list elements can be accessed by the function
%\fdx{get_void_list_element()@{\code{get\_void\_list\_element()}}}
%\idx{memory (de--) allocation!get_void_list_element()@{\code{get\_void\_list\_element()}}}
%\bv\begin{verbatim}
%VOID_LIST_ELEMENT *get_void_list_element(void);
%\end{verbatim}\ev
%and subsequently be deallocated by a call to the function
%\fdx{free_void_list_element()@{\code{free\_void\_list\_element()}}}
%\idx{memory (de--) allocation!%
%free_void_list_element()@{\code{free\_void\_list\_element()}}}
%\bv\begin{verbatim}
%void free_void_list_element(VOID_LIST_ELEMENT *);
%\end{verbatim}\ev
%Description:
%\begin{descr}
%\kitem{get\_void\_list\_element()} returns a pointer to a new list
%element with \code{list->data = list->next = nil}.
%\kitem{free\_void\_list\_element(list)} frees the list element
%\code{list}. After return, the pointers \code{list->data} and
%\code{list->next} will be changed (the list element will be linked into a
%list of currently unused elements).
%\end{descr}

\subsection{Parameters and parameter files}%
\label{S:param}%
\idx{parameter handling|(}

Many procedures need parameters, for example the maximal number
of iterations for an iterative solver, the tolerance for the
error in the adaptive procedure, etc. It is often very helpful
to change the values of these parameters without recompiling the
program by initializing them from a parameter file.

In order to avoid a fixed list of parameters, we use the following
concept: Every parameter consists of two strings: a key string by
which the parameter is identified, and a second string containing the
parameter values. These values are stored as \code{ASCII}-characters
and can be converted to \code{int}, \code{REAL}, etc. according to a
format specified by the user (see below). Using this concept,
parameters can be accessed at any point of the program.

Usually parameters are initialized from parameter files. Each line of
the file describes either a single parameter: the key definition
terminated by a \code{':'} character followed by the parameter values,
or specifies another parameter file to be included at that point (this
can also be done recursively).  The syntax of these files is described
below and an example is given at the end of this section.%
\idx{memory (de--) allocation|)}

\subsubsection{Parameter files}%
\label{par_files}

The definition of a parameter has the following syntax:
\idx{parameter file}
\bv\begin{verbatim}
key: parameter values % optional comment
\end{verbatim}\ev
Lines are only read up to the first occurrence of the comment sign
\code{'\%'}. All characters behind this sign in the same line are
ignored. The comment sign may be a character of the specified filename
in an include statement (see below). In this case, \code{'\%'} is
treated as a usual character.

The definition of a new parameter consists out of a key string and a
string containing the parameter values. The definition of the key for
a new parameter has to be placed in one line before the first comment
sign. For the parameter values a continuation line can be used (see
below). The key string is a sequence of arbitrary characters except
\code{':'} and the comment character. It is terminated by \code{':'},
which does not belong to the key string. A key may contain
blanks. Optional white space characters as blanks, tabs, etc.  in
front of a key and in between \code{':'} and the first character of
the parameter value are discarded.

Each parameter definition must have at least one parameter value, but
it can have more than one. If there are no parameter values specified,
i.e. the rest of the line (and all continuation lines) contain(s) only
white-space characters (and the continuation character(s)). Such a parameter
definition is ignored and the line(s) is (are) skipped.

One parameter value is a sequence of non white-space characters. 
We will call such a sequence of non white-space characters a word.
Two parameter values are separated by at least one white-space character.
A string as a parameter value must not contain white-space characters. Strings
enclosed in single or double quotes are not supported at the moment. These
quotes are treated as usual characters.

Parameter values are stored as a sequence of words in one string. The
words are separated by exactly one blank, although parameter values in
the parameter file may be separated by more than one white-space
character.

The key definition must be placed in one line. Parameter values can
also be specified in so called continuation lines. A line is
a continuation line if the last two characters in the preceding line
are a \code{'$\backslash$'} followed directly by the newline
character. The \code{'$\backslash$'} and the newline character are removed
and the line is continued at the beginning of the next line. No additional
blank is inserted.

Lines containing only white-space characters (if they are not
continuation lines!) are skipped.

Besides a parameter definition we can include another parameter file 
with name \code{filename}:
\bv\begin{verbatim}
#include "filename"
\end{verbatim}\ev
  The effect of an include statement is the similar to an include
  statement in a \code{C}-program. Using the function
  \code{init\_parameters()} (see below) for reading the parameter
  file, the named file is read by a recursive call of the function
  \code{init\_parameters()}. Thus, the included parameter file may
  also contain an include statement. The rest of line behind the
  closing \code{"} is skipped.  Initialization then is continued from
  the next line on. An include statement must not have a continuation
  line.

\begin{comment}
Using the function \code{init\_parameters\_cpp()}, the file is
included using the \code{C}-preprocessor (see below).
\end{comment}

If a parameter file can not be opened for reading, an error message
is produced and the reading of the file is skipped.

Errors occur and are reported if a key definition is not terminated in the
same line by \code{':'}, no parameter values are specified, filename
for include files are not specified correctly in between \code{" "}.
The corresponding lines are ignored. No parameter is defined,
or no file is included.

A parameter can be defined more than once but only the latest definition
is valid. All previous definitions are ignored.

\subsubsection{Reading of parameter files}

Initializing parameters from such files is done by
\fdx{init_parameters()@{\code{init\_parameters()}}}
\idx{parameter handling!init_parameters()@{\code{init\_parameters()}}}

\bv\begin{verbatim}
void init_parameters(int, const char *);
\end{verbatim}\ev
%void init_parameters_cpp(int print, const char *filename, const char *cpp_flags);
Description:
\begin{descr}
\kitem{init\_parameters(info, filename)} initializes parameters
from a file; \code{filename} is a string holding the name of the file
and if values of the argument \code{info} and the global variable
\code{msg\_info} are not zero, a list of all defined parameters is
printed to the message stream; if \code{init\_parameters()} can not open
the input file, or \code{filename} is a pointer to \nil, 
no parameters are defined.

One call of this function should be the first executable statement in
the main program. Several calls of \code{init\_parameters()} are
possible. If a key is defined more than once, parameter values from
the latest definition are valid. Parameter values from previous
definition(s) are ignored.
\begin{comment}
\kitem{init\_parameters\_cpp(print, filename, cpp\_flags)} the
behavior of this function is the same as of \code{init\_parameters()}
but the file is first processed by the \code{C}--preprocessor
with argument \code{cpp\_flags}, replacing macros by their definitions
in the parameter file and including files specified by \code{\#include"..."}. 
\bv\begin{verbatim}
init_parameters_cpp(0, "alberta.dat", "-DNEIGH_IN_EL=0");
\end{verbatim}\ev
The \code{C}--preprocessor will first replace each occurrence of 
\code{NEIGH\_IN\_EL} in \code{"alberta.dat"} by \code{0}.
Also preprocessor conditionals depending on such macro definitions
are allowed in the parameter file. Default macro definitions to
the preprocessor are 
\bv\begin{verbatim}
-DDIM=d -DDIM_OF_WORLD=dow
\end{verbatim}\ev
where \code{d} and \code{dow} are replaced by the actually used
values, i.e \code{d} equals \code{2} for 2d and \code{3} for 3d
simulations.  After this preprocessing the the parameters are
initialized.

This function is only available, if the \ALBERTA library was compiled
with the \code{CPP} macro holding the command for the \code{C}--preprocessor.
\end{comment}
\end{descr}

\subsubsection{Adding of parameters or changing of parameter values}

Several calls of \code{init\_parameters()}
%or \code{init\_parameters\_cpp()}
are possible. This may add new parameters or change the value of an
existing parameter since only the values from the latest definition
are valid.  Examples for giving parameter values from the command line
and integrating them into the set of parameters are shown in Sections
\ref{S:nonlin_main} and \ref{S:heat_main}.

Parameters can also be defined or modified by the function or the
macro
\fdx{add_parameter()@\code{add\_parameter()}}
\idx{parameter handling!add_parameter()@{\code{add\_parameter()}}}
\mdx{ADD_PARAMETER()@\code{ADD\_PARAMETER()}}
\idx{parameter handling!ADD_PARAMETER()@{\code{ADD\_PARAMETER()}}}
\bv\begin{verbatim}
void add_parameter(int, const char *, const char *);
ADD_PARAMETER(int, const char *, const char *);
\end{verbatim}\ev
Description:
\begin{descr}
\kitem{add\_parameter(info, key, value)} initializes a parameter
identified by \code{key} with values \code{value}; if the parameter
already exists, the old values are replaced by the new one; if
\code{info} is not zero information about the initialization is printed;
This message can be suppressed by a global level of parameter information
(see the parameter \code{parameter information} in \secref{S:par_util}).
\kitem{ADD\_PARAMETER(info, key, value)} acts like 
\code{add\_parameter(info, key, value)} but the function is additionally
supplied with the name of the calling function, source file and line,
which results in more detailed messages during parameter definition.
\end{descr}

\subsubsection{Display and saving of parameters and parameter values}

All a list of all parameters together with the actual parameter values
can be printed to \code{stdout} using the function
\bv\begin{verbatim}
void print_parameters(void);
\end{verbatim}\ev

For long time simulations it is important to write all parameters
and their values to file; using this file the simulation
can be re--done with exactly the same parameter values although
the original parameter file was changed. Thus, after the
initialization of parameters in a long time simulation, they
should be written to a file by the following function:
\fdx{save_parameters()@\code{save\_parameters()}}
\idx{parameter handling!save_parameters()@{\code{save\_parameters()}}}
\bv\begin{verbatim}
void save_parameters(const char *, int);
\end{verbatim}\ev
Description:
\begin{descr}
\kitem{save\_parameters(file, info)} writes all successfully initialized
       parameters to \code{file} according to the above described
       parameter file format; if the value of \code{info} is different
       from zero, the location of the initialization is supplied for
       each parameter as a comment; no original comment is written,
       since these are not stored.
\end{descr}

\subsubsection{Getting parameter values}%
\label{S:get_par}

After initializing parameters by \code{init\_parameters()} 
%or \code{init\_parameters\_cpp()}
we can access the values of a parameter by a call of
\fdx{get_parameter()@{\code{get\_parameter()}}}
\idx{parameter handling!get_parameter()@{\code{get\_parameter()}}}
\mdx{GET_PARAMETER()@{\code{GET\_PARAMETER()}}}
\idx{parameter handling!GET_PARAMETER()@{\code{GET\_PARAMETER()}}}
\bv\begin{verbatim}
int get_parameter(int, const char *, const char *, ...);
int GET_PARAMETER(int, const char *, const char *, ...)
\end{verbatim}\ev
Description:
\begin{descr}
\kitem{get\_parameter(info, key, format, ...)}
  looks for a parameter which matches the identifying key string
  \code{key} and converts the values of the corresponding string
  containing the parameter values according to the control string
  \code{format}. Pointers to variable(s) of suitable types are placed in
  the unnamed argument list (compare the syntax of \code{scanf()}). The
  first argument \code{info} defines the level of information during
  the initialization of parameters with a range of
  \code{0} to \code{4}: no to full information. The return value
  is the number of successfully matched and assigned input items.

  If there is no parameter key matching \code{key}, \code{get\_parameter()}
  returns without an initialization. The return value is zero. 
  It will also return without an initialization and return value zero
  if no parameter has been defined by \code{init\_parameters()}.

  In the case that a parameter matching the key is found, \code{
    get\_parameter()} acts like a simplified version of \code{sscanf()}.
  The input string is the string containing the parameter values. The
  function reads characters from this string, interprets them according
  to a format, and stores the results in its arguments. It expects, as
  arguments, a control string, \code{format} (described below) and a set
  of pointer arguments indicating where the converted input should be
  stored. If there are insufficient arguments for the format, the
  behavior is undefined. If the format is exhausted while arguments
  remain, the excess arguments are simply ignored. The return value is
  the number of converted arguments.

  The control string must only contain the following characters used as
  conversion specification: \code{\%s}, \code{\%c}, \code{\%d},
  \code{\%e}, \code{\%f}, \code{\%g}, \code{\%U}, \code{\%S}, or
  \code{\%*}.  All other characters are ignored. In contrast to
  \code{scanf()}, a numerical value for a field width is not
  allowed. For each element of the control string the next word of the
  parameter string is converted as follows:
  \begin{descr}
  \kitem{\%s}
    a character string is expected; the corresponding argument should
    be a character pointer pointing to an array of characters large
    enough to accept the string and a terminating {\tt
      `$\backslash$0'}, which will be added automatically; the string is
    one single word of the parameter string; as mentioned above strings
    enclosed in single or double quotes are not supported at the
    moment.
  \kitem{\%c}
    matches a single character; the corresponding argument should be a
    pointer to a \code{char} variable; if the corresponding word of
    the parameter string consists of more than one character, the rest
    of the word is ignored; no space character is possible as argument.
  \kitem{\%d}
    matches a decimal integer, whose format is the same as expected
    for the subject sequence of the \code{atoi()} function; the
    corresponding argument should be a pointer to an \code{int}
    variable.
  \kitem{\%i}
    matches a decimal integer, whose format is the same as expected
    for the subject sequence of the \code{strtol(arg, NULL, 0)} function; the
    corresponding argument should be a pointer to an \code{int}
    variable.
  \kitem{\%e,\%f,\%g}
    matches an optionally signed floating point number, whose format is
    the same as expected for the subject string of the \code{atof()}
    function; the corresponding argument should be a pointer to a
    \code{REAL} variable.
  \kitem{\%U}
    matches an unsigned decimal integer in the range [0,255], whose
    format is the same as expected for the subject sequence of the {\tt
      atoi()} function; the corresponding argument should be a pointer to
    an \code{U\_CHAR} variable.
  \kitem{\%S}
    matches an optionally signed decimal integer in the range
    [-128,127], whose format is the same as expected for the subject
    sequence of the \code{atoi()} function; the corresponding argument
    should be a pointer to an \code{S\_CHAR} variable.
    %% 
  \kitem{\%B} matches a boolean value; the corresponding argument
    should be a pointer to a \code{bool} variable. The boolean value
    may be specified as any of the following strings: \code{true},
    \code{t}, \code{yes}, \code{y}, \code{1}, \code{false}, \code{f},
    \code{no}, \code{n}, \code{0}, \code{nil}, with the obvious
    meaning concerning the translation into the value for the
    \code{bool} data type of \code{C}.
    %% 
  \kitem{\%*}
    next word of parameter string should be skipped; there must not be
    a corresponding argument.
  \end{descr}
  \code{get\_parameter()} will always finish its work, successfully or not.
  It may fail if a misspelled key is handed over or there are not so
  many parameter values as format specifiers (the remaining variables
  are not initialized!). If \code{info} is zero, \code{get\_parameter()}
  works silently; no error message is produced. Otherwise the key and
  the initialized values and error messages are printed.  The second way
  to influence messages produced by \code{get\_parameter()} is
  a parameter \code{parameter information} specified in a parameter
  file, see \secref{S:par_util}.
\kitem{GET\_PARAMETER(info, key, format, ...)} is a macro and acts in the
  same way as the function \code{get\_parameter(info, key, format, ...)}
  but the function is additionally supplied with the name of the
  calling function, source file and line, which results in more
  detailed messages during parameter definition.
\end{descr}

In order to prevent the program from working with uninitialized 
variables, all parameters should be initialized beforehand! By the
return value the number of converted arguments can be checked.

\begin{example}[\code{init\_parameters()}, \code{GET\_PARAMETER()}]
Consider the following parameter file \code{init.dat}:

\bv\begin{verbatim}
adapt info:  3             % level of information of the adaptive method
adapt tolerance:  0.001    % tolerance for the error
\end{verbatim}\ev
Then
\bv\begin{verbatim}
init_parameters(0, "init.dat");
...
tolerance = 0.1;
GET_PARAMETER(0, "adapt tolerance", "%e", &tolerance);
\end{verbatim}\ev
initializes the \code{REAL} variable \code{tolerance} with the value 
\code{0.001}.
\end{example}

\subsection{Parameters used by the utilities}%
\label{S:par_util}

The utility tools use the following parameters initialized with default
values given in \code{()}:
\begin{descr}
\kitem{level of information (10)} the global level of information;
can restrict the local level of information (compare \secref{S:messages}).
\kitem{parameter information (1)} enforces more/less information than
specified by the argument \code{info} of
the routine \code{get\_parameter(info, ...)}:
\begin{descr}
\kitem{0} no message at all is produced, although the value \code{info} may be
          non zero;
\kitem{1} gives only messages if the value of \code{info} is non zero;
\kitem{2} all error messages are printed, although the value of \code{info} 
          may be zero;
\kitem{4} all messages are printed, although the value of \code{info} 
          may be zero.
\end{descr}
\kitem{WAIT (1)}\idx{WAIT} sets the value of the global variable \code{msg\_wait}
and changes by that the behaviour of the macro \code{WAIT} 
(see \secref{S:messages}).
\end{descr}%
\idx{parameter handling|)}

\subsection{Generating filenames for meshes and finite element data}%
\label{S:generate_filename}

During simulation of time-dependent problems one often wants to
store meshes and finite element data for the sequence of time steps.
A routine is provided to automatically generate file names 
composed from a given data path, a base-name for the file and
a number which is iteration counter of the actual time step
in time-dependent problems. Such a function simplifies the
handling of a sequence of data for reading and writing. It also
ensures that files are listed alphabetically in the given path 
(up to 1 million files with the same base-name).
\fdx{generate_filename()@{\code{generate\_filename()}}}
\idx{GRAPE!generate_filename()@{\code{generate\_filename()}}}
\bv\begin{verbatim}
const char *generate_filename(const char *, const char *, int);
\end{verbatim}\ev
Description:
\begin{descr}
  \kitem{generate\_filename(path, file, index)} composes a filename
  from the given \code{path}, the base-name \code{file} of the file and
  the (iteration counter) \code{index}.  When no path is
  given, the current directory \code{"./"} is used, if the first 
  character of \code{path} is \verb|'~'|, \code{path} is 
  assumed to be located in the home directory and the name of 
  the path is expanded accordingly, using the environment variable
  \code{HOME}. A pointer to a string 
  containing the full filename is the return value; this string
  is overwritten on the next call to \code{generate\_filename()}.

  \verb|generate_filename("./output", "mesh",1)|
  returns \code{"./output/mesh000001"}, for instance. An
  example how to use \code{generate\_filename()} in a time dependent
  problem is given in \secref{S:heat_timestep}.
\end{descr}


%%% Local Variables: 
%%% mode: latex
%%% TeX-master: "alberta-man"
%%% End: 
