/***** do not edit -- this file was generated mechanically *****/



/****************************************  from ../h/rt.h:  */

#ifndef RT_H    /* only include once */
#define RT_H 1

/*
 * Include files.
 */



/****************************************  from ../h/../h/define.h:  */


/****************************************   end ../h/../h/define.h   */


/****************************************  from ../h/../h/config.h:  */

/*
 * Icon configuration.
 */

/*
 * System-specific definitions are in define.h
 * update June 2017::
 *    System-specific definitions are being handled
 *    by the configure script. Some remaining definitions are
 *    moved here so they are all in one place for all systems.
 *    Many of these options will be automated as well.
 */

/*
 *  A number of symbols are defined here.  Some are specific to individual
 *  to operating systems.  Examples are:
 *
 *      MSDOS           MS-DOS for PCs
 *      UNIX            any UNIX system; also set for BeOS
 *      VMS             VMS for the VAX
 *
 *  These are defined to be 1 or 0 depending on which operating system
 *  the installation is being done under.  They are all defined and only
 *  one is defined to be 1.  (They are used in the form #if VAX || MSDOS.)
 *
 *  There also are definitions of symbols for specific computers and
 *  versions of operating systems.  These include:
 *
 *      SUN             code specific to the Sun Workstation
 *      MICROSOFT       code specific to the Microsoft C compiler for MS-DOS
 *
 *  Other definitions may occur for different configurations. These include:
 *
 *      DeBug           debugging code
 *      MultiProgram    support for multiple programs under the interpreter
 *
 *  Other definitions perform configurations that are common to several
 *  systems. An example is:
 *
 *      Double          align reals at double-word boundaries
 *
 */

#ifndef UNICON_CONFIG_H
#define UNICON_CONFIG_H

/*
 * If define.h does not specify NoAuto, supplement config info with
 * autoconf-generated symbols.
 */
#ifndef NoAuto


/****************************************  from ../h/../h/auto.h:  */

/* src/h/auto.h.  Generated from auto.in by configure.  */
/* src/h/auto.in.  Generated from configure.ac by autoheader.  */

#ifndef __AUTO_CONFIG_H
#define __AUTO_CONFIG_H

/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */

/* ARM platform */
/* #undef ARM */

/* Define to 1 if using 'alloca.c'. */
/* #undef C_ALLOCA */

/* Developer Mode */
/* #undef DEVELOPMODE */

/* Debug Heap */
/* #undef DebugHeap */

/* FreeBSD OS */
/* #undef FreeBSD */

/* Define to 1 if you have 'alloca', as a function or macro. */
#define HAVE_ALLOCA 1

/* Define to 1 if <alloca.h> works. */
/* #undef HAVE_ALLOCA_H */

/* Define if you have the external `altzone' variable. */
/* #undef HAVE_ALTZONE */

/* Define to 1 if you have the <AL/alut.h> header file. */
#define HAVE_AL_ALUT_H 1

/* Define to 1 if you have the <AL/al.h> header file. */
#define HAVE_AL_AL_H 1

/* Define to 1 if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H 1

/* Define to 1 if you have the `asctime_r' function. */
#define HAVE_ASCTIME_R 1

/* Define to 1 if you have the `bcopy' function. */
#define HAVE_BCOPY 1

/* Define to 1 if you have the `bzero' function. */
#define HAVE_BZERO 1

/* Define to 1 if you have the `clock_gettime' function. */
#define HAVE_CLOCK_GETTIME 1

/* crypt */
#define HAVE_CRYPT 1

/* Define to 1 if you have the `ctime_r' function. */
#define HAVE_CTIME_R 1

/* Define if you have the external `daylight' variable. */
#define HAVE_DAYLIGHT 1

/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you
   don't. */
#define HAVE_DECL_STRERROR_R 1

/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
   */
/* #undef HAVE_DECL_TZNAME */

/* Define to 1 if you have the <errno.h> header file. */
#define HAVE_ERRNO_H 1

/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1

/* Define to 1 if you have the `flock' function. */
#define HAVE_FLOCK 1

/* Define to 1 if you have the `fork' function. */
#define HAVE_FORK 1

/* Define to 1 if you have the <freetype/fttypes.h> header file. */
#define HAVE_FREETYPE_FTTYPES_H 1

/* Define to 1 if you have the `fsync' function. */
#define HAVE_FSYNC 1

/* Define to 1 if you have the <FTGL/FTGLExtrdFont.h> header file. */
#define HAVE_FTGL_FTGLEXTRDFONT_H 1

/* Define to 1 if you have the `ftruncate' function. */
#define HAVE_FTRUNCATE 1

/* getaddinfo */
#define HAVE_GETADDRINFO 1

/* Define to 1 if you have the `getenv_r' function. */
/* #undef HAVE_GETENV_R */

/* Define to 1 if you have the `getopt' function. */
#define HAVE_GETOPT 1

/* Define to 1 if you have the `getrlimit' function. */
#define HAVE_GETRLIMIT 1

/* Define to 1 if you have the `getrusage' function. */
#define HAVE_GETRUSAGE 1

/* Define to 1 if you have the <GL/glu.h> header file. */
#define HAVE_GL_GLU_H 1

/* Define to 1 if you have the <GL/gl.h> header file. */
#define HAVE_GL_GL_H 1

/* Define to 1 if you have the `gmtime_r' function. */
#define HAVE_GMTIME_R 1

/* Define to 1 if you have the `inet_aton' function. */
#define HAVE_INET_ATON 1

/* Define to 1 if you have the `inet_pton' function. */
#define HAVE_INET_PTON 1

/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1

/* Define to 1 if you have the <jerror.h> header file. */
#define HAVE_JERROR_H 1

/* Define to 1 if you have the <jpeglib.h> header file. */
#define HAVE_JPEGLIB_H 1

/* Define to 1 if you have lib alut */
#define HAVE_LIBALUT 1

/* Define to 1 if you have lib crypto */
#define HAVE_LIBCRYPTO 1

/* Define to 1 if you have the `dbm' library (-ldbm). */
/* #undef HAVE_LIBDBM */

/* define to 1 if you have dlopen */
#define HAVE_LIBDL 1

/* Define to 1 if you have lib freetype */
#define HAVE_LIBFREETYPE 1

/* Define to 1 if you have lib ftgl */
#define HAVE_LIBFTGL 1

/* Define to 1 if you have the `GL' library (-lGL). */
#define HAVE_LIBGL 1

/* Define to 1 if you have the `GLU' library (-lGLU). */
#define HAVE_LIBGLU 1

/* Define to 1 if you have lib iodbc */
#define HAVE_LIBIODBC 1

/* Define to 1 if you have lib jpeg */
#define HAVE_LIBJPEG 1

/* Define to 1 if you have the `jrtp' library (-ljrtp). */
/* #undef HAVE_LIBJRTP */

/* Define to 1 if you have the `jthread' library (-ljthread). */
/* #undef HAVE_LIBJTHREAD */

/* Define to 1 if you have the `jvoip' library (-ljvoip). */
/* #undef HAVE_LIBJVOIP */

/* Define to 1 if you have the `m' library (-lm). */
#define HAVE_LIBM 1

/* Define to 1 if you have the `ndbm' library (-lndbm). */
/* #undef HAVE_LIBNDBM */

/* Define to 1 if you have the `nsl' library (-lnsl). */
/* #undef HAVE_LIBNSL */

/* Define to 1 if you have lib odbc */
/* #undef HAVE_LIBODBC */

/* Define to 1 if you have lib ogg */
#define HAVE_LIBOGG 1

/* Define to 1 if you have lib openal */
#define HAVE_LIBOPENAL 1

/* Define to 1 if you have lib png */
#define HAVE_LIBPNG 1

/* Define to 1 if you have lib pthread */
#define HAVE_LIBPTHREAD 1

/* Define to 1 if you have lib SDL */
#define HAVE_LIBSDL 1

/* Define to 1 if you have lib smpeg */
/* #undef HAVE_LIBSMPEG */

/* Define to 1 if you have the `socket' library (-lsocket). */
/* #undef HAVE_LIBSOCKET */

/* Define to 1 if you have the `sqlite3' library (-lsqlite3). */
#define HAVE_LIBSQLITE3 1

/* Define to 1 if you have lib ssl */
#define HAVE_LIBSSL 1

/* Define to 1 if you have the `voip' library (-lvoip). */
/* #undef HAVE_LIBVOIP */

/* Define to 1 if you have lib vorbis */
#define HAVE_LIBVORBIS 1

/* Define to 1 if you have lib vorbisfile */
#define HAVE_LIBVORBISFILE 1

/* Define to 1 if you have lib X11 */
#define HAVE_LIBX11 1

/* Define to 1 if you have lib Xft */
#define HAVE_LIBXFT 1

/* Define to 1 if you have lib z */
/* #undef HAVE_LIBZ */

/* Define to 1 if you have the `localtime_r' function. */
#define HAVE_LOCALTIME_R 1

/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1

/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1

/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1

/* Define to 1 if you have the <minix/config.h> header file. */
/* #undef HAVE_MINIX_CONFIG_H */

/* Define to 1 if you have the <netdb.h> header file. */
#define HAVE_NETDB_H 1

/* Define to 1 if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H 1

/* Define to 1 if you have the <net/errno.h> header file. */
/* #undef HAVE_NET_ERRNO_H */

/* Define to 1 if you have the <ogg/ogg.h> header file. */
#define HAVE_OGG_OGG_H 1

/* Define to 1 if you have the <openssl/bio.h> header file. */
#define HAVE_OPENSSL_BIO_H 1

/* Define to 1 if you have the <openssl/ssl.h> header file. */
#define HAVE_OPENSSL_SSL_H 1

/* Define to 1 if you have the <png.h> header file. */
#define HAVE_PNG_H 1

/* Define to 1 if you have the `profil' function. */
#define HAVE_PROFIL 1

/* Define to 1 if you have the <pthread.h> header file. */
#define HAVE_PTHREAD_H 1

/* Define to 1 if you have the `rename' function. */
#define HAVE_RENAME 1

/* Define to 1 if you have the <SDL/SDL_audio.h> header file. */
#define HAVE_SDL_SDL_AUDIO_H 1

/* Define to 1 if you have the `setrlimit' function. */
#define HAVE_SETRLIMIT 1

/* Define to 1 if you have the <smpeg.h> header file. */
/* #undef HAVE_SMPEG_H */

/* Define to 1 if you have the `snprintf' function. */
#define HAVE_SNPRINTF 1

/* Define to 1 if you have the `socket' function. */
#define HAVE_SOCKET 1

/* Define to 1 if you have the <sqlext.h> header file. */
#define HAVE_SQLEXT_H 1

/* Define to 1 if you have the <sqlite3.h> header file. */
#define HAVE_SQLITE3_H 1

/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1

/* Define to 1 if you have the <stdio.h> header file. */
#define HAVE_STDIO_H 1

/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1

/* Define to 1 if you have the `strerror' function. */
#define HAVE_STRERROR 1

/* Define if you have `strerror_r'. */
#define HAVE_STRERROR_R 1

/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1

/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1

/* Define to 1 if `tm_zone' is a member of `struct tm'. */
#define HAVE_STRUCT_TM_TM_ZONE 1

/* Define to 1 if you have the `sysconf' function. */
#define HAVE_SYSCONF 1

/* Define to 1 if you have the <sys/errno.h> header file. */
#define HAVE_SYS_ERRNO_H 1

/* Define to 1 if you have the <sys/file.h> header file. */
#define HAVE_SYS_FILE_H 1

/* Define to 1 if you have the <sys/resource.h> header file. */
#define HAVE_SYS_RESOURCE_H 1

/* Define to 1 if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H 1

/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1

/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1

/* Define if you have the external `timezone' variable. */
#define HAVE_TIMEZONE 1

/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use
   `HAVE_STRUCT_TM_TM_ZONE' instead. */
#define HAVE_TM_ZONE 1

/* Define to 1 if you don't have `tm_zone' but do have the external array
   `tzname'. */
/* #undef HAVE_TZNAME */

/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1

/* Define to 1 if you have the `vfork' function. */
#define HAVE_VFORK 1

/* Define to 1 if you have the <vfork.h> header file. */
/* #undef HAVE_VFORK_H */

/* Define to 1 if you have the <vorbis/codec.h> header file. */
#define HAVE_VORBIS_CODEC_H 1

/* Define to 1 if you have the <vorbis/vorbisfile.h> header file. */
#define HAVE_VORBIS_VORBISFILE_H 1

/* Define to 1 if you have the `vsprintf' function. */
#define HAVE_VSPRINTF 1

/* Define to 1 if you have the <wchar.h> header file. */
#define HAVE_WCHAR_H 1

/* Define to 1 if `fork' works. */
#define HAVE_WORKING_FORK 1

/* Define to 1 if `vfork' works. */
#define HAVE_WORKING_VFORK 1

/* Define to 1 if you have the <X11/Xatom.h> header file. */
#define HAVE_X11_XATOM_H 1

/* Define to 1 if you have the <X11/Xft/Xft.h> header file. */
#define HAVE_X11_XFT_XFT_H 1

/* Define to 1 if you have the <X11/Xlib.h> header file. */
#define HAVE_X11_XLIB_H 1

/* Define to 1 if you have the <X11/Xos.h> header file. */
#define HAVE_X11_XOS_H 1

/* Define to 1 if you have the <X11/Xutil.h> header file. */
#define HAVE_X11_XUTIL_H 1

/* Define to 1 if you have the <zlib.h> header file. */
/* #undef HAVE_ZLIB_H */

/* Extra cpp flags for iconc when compiling user C (ft2build.h). */
#define ICONC_FREETYPE_CPPFLAGS "-I/usr/X11R6/include/freetype2"

/* Mac OS */
/* #undef MacOS */

/* No Audio */
/* #undef NoAudio */

/* No Concurrency */
/* #undef NoConcurrent */

/* No ConcurrentCOMPILER */
#define NoConcurrentCOMPILER 1

/* No Database */
/* #undef NoDatabase */

/* No Graphics */
/* #undef NoGraphics */

/* No Graphics3D */
/* #undef NoGraphics3D */

/* No LoadFunc */
/* #undef NoLoadFunc */

/* No MultiProgram */
/* #undef NoMultiProgram */

/* No Native Coswitch */
#define NoNativeCoswitch 1

/* No PatternType */
/* #undef NoPattern */

/* No VOIP */
/* #undef NoVoip */

/* Enable Operator Overloading */
/* #undef OVLD */

/* OpenBSD OS */
#define OpenBSD 1

/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "jeffery@unicon.org"

/* Define to the full name of this package. */
#define PACKAGE_NAME "Unicon"

/* Define to the full name and version of this package. */
#define PACKAGE_STRING "Unicon 13.3"

/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "unicon"

/* Define to the home page for this package. */
#define PACKAGE_URL "http://www.unicon.org"

/* Define to the version of this package. */
#define PACKAGE_VERSION "13.3"

/* PowerPC platform */
/* #undef PPC */

/* PowerPC 64 platform */
/* #undef PPC64 */

/* RISC-V platform */
/* #undef RISCV */

/* The size of `int', as computed by sizeof. */
#define SIZEOF_INT 4

/* The size of `int *', as computed by sizeof. */
#define SIZEOF_INT_P 8

/* The size of `long int', as computed by sizeof. */
#define SIZEOF_LONG_INT 8

/* The size of `long long int', as computed by sizeof. */
#define SIZEOF_LONG_LONG_INT 8

/* Solaris OS */
/* #undef SOLARIS */

/* If using the C implementation of alloca, define if you know the
   direction of stack growth for your system; otherwise it will be
   automatically deduced at runtime.
	STACK_DIRECTION > 0 => grows toward higher addresses
	STACK_DIRECTION < 0 => grows toward lower addresses
	STACK_DIRECTION = 0 => direction of growth unknown */
/* #undef STACK_DIRECTION */

/* Define to 1 if all of the C90 standard headers exist (not just the ones
   required in a freestanding environment). This macro is provided for
   backward compatibility; new code need not use it. */
#define STDC_HEADERS 1

/* Define to 1 if strerror_r returns char *. */
/* #undef STRERROR_R_CHAR_P */

/* Sun platform */
/* #undef SUN */

/* Define to 1 if your <sys/time.h> declares `struct tm'. */
/* #undef TM_IN_SYS_TIME */

/* Unix platform */
#define UNIX 1

/* Enable extensions on AIX 3, Interix.  */
#ifndef _ALL_SOURCE
# define _ALL_SOURCE 1
#endif
/* Enable general extensions on macOS.  */
#ifndef _DARWIN_C_SOURCE
# define _DARWIN_C_SOURCE 1
#endif
/* Enable general extensions on Solaris.  */
#ifndef __EXTENSIONS__
# define __EXTENSIONS__ 1
#endif
/* Enable GNU extensions on systems that have them.  */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
/* Enable X/Open compliant socket functions that do not require linking
   with -lxnet on HP-UX 11.11.  */
#ifndef _HPUX_ALT_XOPEN_SOCKET_API
# define _HPUX_ALT_XOPEN_SOCKET_API 1
#endif
/* Identify the host operating system as Minix.
   This macro does not affect the system headers' behavior.
   A future release of Autoconf may stop defining this macro.  */
#ifndef _MINIX
/* # undef _MINIX */
#endif
/* Enable general extensions on NetBSD.
   Enable NetBSD compatibility extensions on Minix.  */
#ifndef _NETBSD_SOURCE
# define _NETBSD_SOURCE 1
#endif
/* Enable OpenBSD compatibility extensions on NetBSD.
   Oddly enough, this does nothing on OpenBSD.  */
#ifndef _OPENBSD_SOURCE
# define _OPENBSD_SOURCE 1
#endif
/* Define to 1 if needed for POSIX-compatible behavior.  */
#ifndef _POSIX_SOURCE
/* # undef _POSIX_SOURCE */
#endif
/* Define to 2 if needed for POSIX-compatible behavior.  */
#ifndef _POSIX_1_SOURCE
/* # undef _POSIX_1_SOURCE */
#endif
/* Enable POSIX-compatible threading on Solaris.  */
#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-5:2014.  */
#ifndef __STDC_WANT_IEC_60559_ATTRIBS_EXT__
# define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-1:2014.  */
#ifndef __STDC_WANT_IEC_60559_BFP_EXT__
# define __STDC_WANT_IEC_60559_BFP_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-2:2015.  */
#ifndef __STDC_WANT_IEC_60559_DFP_EXT__
# define __STDC_WANT_IEC_60559_DFP_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-4:2015.  */
#ifndef __STDC_WANT_IEC_60559_FUNCS_EXT__
# define __STDC_WANT_IEC_60559_FUNCS_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-3:2015.  */
#ifndef __STDC_WANT_IEC_60559_TYPES_EXT__
# define __STDC_WANT_IEC_60559_TYPES_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TR 24731-2:2010.  */
#ifndef __STDC_WANT_LIB_EXT2__
# define __STDC_WANT_LIB_EXT2__ 1
#endif
/* Enable extensions specified by ISO/IEC 24747:2009.  */
#ifndef __STDC_WANT_MATH_SPEC_FUNCS__
# define __STDC_WANT_MATH_SPEC_FUNCS__ 1
#endif
/* Enable extensions on HP NonStop.  */
#ifndef _TANDEM_SOURCE
# define _TANDEM_SOURCE 1
#endif
/* Enable X/Open extensions.  Define to 500 only if necessary
   to make mbstate_t available.  */
#ifndef _XOPEN_SOURCE
/* # undef _XOPEN_SOURCE */
#endif


/* Avoid naming conflicts with Icon */
/* #undef UniconX */

/* Verify Heap */
/* #undef VerifyHeap */

/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
   significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
#  define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
#  define WORDS_BIGENDIAN 1
# endif
#endif

/* Windows platform */
/* #undef Windows */

/* X86 platform */
/* #undef X86 */

/* MUSL C Library */
/* #undef __MUSL__ */

/* bindir */
#define config_bindir "/usr/local/bin"

/* docdir */
#define config_docdir "/usr/local/share/doc/unicon"

/* exec_prefix */
#define config_exec_prefix "/usr/local"

/* libdir */
#define config_libdir "/usr/local/lib"

/* mandir */
#define config_man "/usr/local/man"

/* prefix */
#define config_prefix "/usr/local"

/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */

/* Define to `long int' if <sys/types.h> does not define. */
/* #undef off_t */

/* Define as a signed integer type capable of holding a process identifier. */
/* #undef pid_t */

/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */

/* Define to `signed' if <sys/types.h> does not define. */
/* #undef ssize_t */

/* Define as `fork' if `vfork' does not work. */
/* #undef vfork */

#endif          /* __AUTO_CONFIG_H  */

/****************************************   end ../h/../h/auto.h   */
#endif                                  /* NoAuto */

/*
 *  Avoid name conflicts with Icon by using unicon-specific names
 */
#ifdef UniconX
#define UNICONX "uniconx"
#define UNICONWX "wuniconx"
#define UNICONT "unicont"
#define UNICONWT "wunicont"
#define UNICONC "uniconc"
#else                                   /* UNICONX */
#define UNICONX "iconx"
#define UNICONWX "wiconx"
#define UNICONT "icont"
#define UNICONWT "wicont"
#define UNICONC "iconc"
#endif                                  /* UNICONX */

#if Windows
#define UNICONX_EXE UNICONX".exe"
#define UNICONWX_EXE UNICONWX".exe"
#define UNICONT_EXE UNICONT".exe"
#define UNICONWT_EXE UNICONWT".exe"
#define UNICONC_EXE UNICONC".exe"
#else                                   /* NT */
#define UNICONX_EXE UNICONX
#define UNICONWX_EXE UNICONWX
#define UNICONT_EXE UNICONT
#define UNICONWT_EXE UNICONWT
#define UNICONC_EXE UNICONC
#endif                                  /* NT */

/* make SQL_LENORIND definition global for now*/
#define SQL_LENORIND SQLLEN

#if MacOS
//#define COpts "-I/usr/X11R6/include"

#define NamedSemaphores
#define INTMAIN
#define PROFIL_CHAR_P
#endif                                  /* MacOS */

#if SUN
#define INTMAIN

#define SysOpt   1
#define NoRanlib
//#define COpts " -m64 -I/usr/X11R6/include -L/usr/X11R6/lib/64 "

#define Messaging  1
#define PosixFns   1
#define NoVFork
#endif                                  /* SUN */

#if OpenBSD
#define GenericBSD
#define BSD_4_4_LITE    1	/* This is new, for 4.4Lite specific stuff */

#define NEED_UTIME
#define Messaging 1

#define SysOpt

#define MaxStatSize 40960

#define LinkLibs " -lm"

#define HAVE_GETHOSTNAME 1
#define HAVE_GETPWUID 1
#define HAVE_GETUID 1
#endif					/* OpenBSD */

#if FreeBSD
#define GenericBSD
#define BSD_4_4_LITE    1       /* This is new, for 4.4Lite specific stuff */

#define NEED_UTIME
#define Messaging 1

#define SysOpt
#define ExecImages

#define MaxStatSize 40960

#define LinkLibs " -lm"

#define HAVE_GETHOSTNAME 1
#define HAVE_GETPWUID 1
#define HAVE_GETUID 1
#define PROFIL_CHAR_P
#endif                                  /* FreeBSD */


#if Windows

/*
 * 0x501 => WindowsXP or later
 * 0x601 => Win7 or later
 */

#if !defined(WINVER) || (WINVER < 0x0601)
#undef WINVER
#define WINVER 0x0601
#endif

#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0601)
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#endif

#define HostStr "Win32 Intel GCC"
#define IconAlloc
#define Precision 16
#define IcodeSuffix ".exe"
#define IcodeASuffix ".EXE"
#define SystemFnc
#define SysTime <sys/time.h>
#define Standard
/*
 * Header is used in winnt.h; careful how we define it here
 */
#define Header header
#define NT 1
#define NTGCC 1
#define CComp "gcc"
#define ShellHeader

#define index strchr
#define rindex strrchr
#define strdup _strdup
#define unlink _unlink
#define MSDOS 1
#define StandardC
#define ZERODIVIDE
#define QSortFncCast int (*)(const void *,const void *)

/* #define Eve */
#define PosixFns
#define KeyboardFncs
#define NoCrypt
#define Dbm
#define Messaging 1

#if defined(Messaging) && defined(OLD_NTGCC)
#define ssize_t signed
#endif                                  /* Messaging && OLD_NTGCC */

#define LoadFunc
#define FieldTableCompression 1

/* StackCheck seems to cause a crash when exiting through
 * pressing the [x] close window button, turn it off for now
 */
#define NoStackCheck

#endif                                  /* Windows */


/*
 * If COMPILER is not defined, code for the interpreter is compiled.
 */

#ifndef COMPILER
   #define COMPILER 0
#endif

/*
 * The following definitions insure that all the symbols for operating
 * systems that are not relevant are defined to be 0 -- so that they
 * can be used in logical expressions in #if directives.
 */

#ifndef PORT
   #define PORT 0
#endif                                  /* PORT */

#ifndef MSDOS
   #define MSDOS 0
#endif                                  /* MSDOS */

#ifndef MVS
   #define MVS 0
#endif                                  /* MVS */

#ifndef UNIX
   #define UNIX 0
#endif                                  /* UNIX */

#ifndef VM
   #define VM 0
#endif                                  /* VM */

#ifndef VMS
   #define VMS 0
#endif                                  /* VMS */

/*
 * The following definitions serve to cast common conditionals in
 *  a positive way, while allowing defaults for the cases that
 *  occur most frequently.  That is, if co-expressions are not supported,
 *  NoCoExpr is defined in define.h, but if they are supported, no
 *  definition is needed in define.h; nonetheless subsequent conditionals
 *  can be cast as #ifdef CoExpr.
 */

#ifndef NoPosixFns
   #undef PosixFns
   #define PosixFns
#endif                                  /* NoPosixFns */

#ifdef PosixFns
#define ReadDirectory
#endif                                  /* PosixFns */

/*
 *  Execution monitoring is not supported under the compiler,
 *  nor if co-expressions are not available.
 */

#undef NativeCoswitch
#ifdef NoCoExpr
   #undef NoNativeCoswitch
   #define NoNativeCoswitch
   #undef MultiProgram
   #undef NoMultiProgram
   #define NoMultiProgram
#else                                   /* NoCoExpr */
   #undef CoExpr
   #define CoExpr
   #ifndef NoNativeCoswitch
      #define NativeCoswitch
   #endif                               /* NoNativeCoswitch */
#endif                                  /* NoCoExpr */

#if COMPILER
   #undef MultiProgram
   #undef NoMultiProgram
   #define NoMultiProgram
#endif                                  /* COMPILER */

#ifdef NoMultiProgram
   #undef MultiProgram
   #undef EventMon
   #undef Eve
   #undef NoEventMon
   #define NoEventMon
#else
   #undef MultiProgram
   #define MultiProgram
#endif                                  /* NoMultiProgram */

#ifndef NoEventMon
  #undef  EventMon
  #define EventMon
#endif

//#ifdef MultiProgram
   #if defined(HAVE_LIBPTHREAD) && !defined(NoConcurrent)
      #undef Concurrent
      #define Concurrent 1
   #endif                       /* HAVE_LIBPTHREAD && !NoConcurrent */
//#endif                                        /* MultiProgram */

#if defined(Concurrent) && COMPILER
   #ifdef NoConcurrentCOMPILER
   #define ConcurrentCOMPILER 0
   #undef Concurrent
   #else
   #define ConcurrentCOMPILER 1
   #endif
#else
   #define ConcurrentCOMPILER 0
#endif

#ifdef Concurrent
   #define PthreadCoswitch 1
   #define TSLIST
   /*
    * The default at present does not use __thread.
    * To use __thread, uncomment the following line
    * "#define HAVE_KEYWORD__THREAD"
    */
#endif                          /* Concurrent */

#ifndef NoINTMAIN
   #undef INTMAIN
   #define INTMAIN
#endif                                  /* NoINTMAIN */

#ifndef NoMessaging
   #undef Messaging
   #define Messaging
#endif                                  /* Messaging */

#ifndef NoStrInvoke
   #undef StrInvoke
   #define StrInvoke
#endif                                  /* NoStrInvoke */

#ifndef NoLargeInts
   #undef LargeInts
   #define LargeInts
#endif                                  /* NoLargeInts */

#ifdef EventMon
   #undef MultiProgram
   #define MultiProgram
#ifndef NoMonitoredTrappedVar
   #undef MonitoredTrappedVar
   #define MonitoredTrappedVar
#endif                                  /* MonitoredTrappedVar */
#endif                                  /* EventMon */


/*
 * Names for standard environment variables.
 * The standard names are used unless they are overridden.
 */

#ifndef NOERRBUF
   #define NOERRBUF "NOERRBUF"
#endif

#ifndef TRACE
   #define TRACE "TRACE"
#endif

#ifndef COEXPSIZE
   #define COEXPSIZE "COEXPSIZE"
#endif

#ifndef STRSIZE
   #define STRSIZE "STRSIZE"
#endif

#ifndef HEAPSIZE
   #define HEAPSIZE "HEAPSIZE"
#endif

#ifndef BLOCKSIZE
   #define BLOCKSIZE "BLOCKSIZE"
#endif

#ifndef BLKSIZE
   #define BLKSIZE "BLKSIZE"
#endif

#ifndef MSTKSIZE
   #define MSTKSIZE "MSTKSIZE"
#endif

#ifndef QLSIZE
   #define QLSIZE "QLSIZE"
#endif

#ifndef ICONCORE
   #define ICONCORE "ICONCORE"
#endif

#ifndef IPATH
   #define IPATH "IPATH"
#endif

#if defined(HAVE_LIBJVOIP) && defined(HAVE_LIBJRTP) && defined(HAVE_LIBJTHREAD) && defined(HAVE_LIBVOIP)
#define HAVE_VOICE
#endif

#if (defined(HAVE_LIBOPENAL) && defined(HAVE_LIBALUT))
   #if (defined(HAVE_LIBVORBIS) && defined(HAVE_LIBOGG))
   #define Audio
   #endif
   #if defined(HAVE_LIBSDL) && defined(HAVE_LIBSMPEG)
   #define Audio
   #endif
#endif

#if  (defined(HAVE_LIBOGG) && defined(WIN32))
/* defined audio because have ogg and win32 */
#define Audio
#endif

#if !defined(NoGraphics)
   #if HAVE_LIBX11
   #define Graphics 1
   #endif

#if defined(MSWindows) || defined(WICONT)
   #undef Graphics
   #define Graphics 1
   #define FAttrib 1
   #ifndef NTConsole
      #define ConsoleWindow 1
   #endif                               /* NTConsole */
   #endif                                       /* MSWindows */
#endif

#ifdef Graphics
   #ifndef NoXpmFormat
      #if UNIX
         #undef HAVE_LIBXPM
         #define HAVE_LIBXPM
      #endif                            /* UNIX */
   #endif                               /* NoXpmFormat */

   #ifndef MSWindows
         #undef XWindows
         #define XWindows 1
   #endif                               /* MSWindows */

   #undef LineCodes
   #define LineCodes

   #undef Polling
   #define Polling

   #ifndef NoIconify
      #define Iconify
   #endif                               /* NoIconify */

   #ifndef ICONC_XLIB
      #define ICONC_XLIB "-L/usr/X11R6/lib -lX11"
   #endif                               /* ICONC_XLIB */

   #if defined(ConsoleWindow) || (NT && !defined(Rttx) && !defined(NTConsole))
      /*
       * Knock out fprintf and putc; these are here so that consoles
       * may be used in icont and rtt, not just iconx.
       */
      #undef fprintf
      #define fprintf Consolefprintf
      #undef putc
      #define putc Consoleputc
      #undef fflush
      #define fflush Consolefflush
      #undef printf
      #define printf Consoleprintf
   #endif


#endif                                  /* Graphics */

#ifndef NoExternalFunctions
   #undef ExternalFunctions
   #define ExternalFunctions
#endif                                  /* NoExternalFunctions */

/*
 * EBCDIC == 0 corresponds to ASCII.
 * EBCDIC == 1 corresponds to EBCDIC collating sequence.
 * EBCDIC == 2 provides the ASCII collating sequence for EBCDIC systems.
 */
#ifndef EBCDIC
   #define EBCDIC 0
#endif                                  /* EBCDIC */

/*
 * Other defaults.
 */

#ifdef DeBug
   #undef DeBugTrans
   #undef DeBugLinker
   #undef DeBugIconx
   #define DeBugTrans
   #define DeBugLinker
   #define DeBugIconx
#endif                                  /* DeBug */

#ifndef AllocType
   #define AllocType uword
#endif                                  /* AllocType */

#ifndef MaxHdr
   #define MaxHdr 4096
#endif                                  /* MaxHdr */

#ifndef MaxPath
   #ifdef PATH_MAX
      #define MaxPath PATH_MAX
   #else
      #define MaxPath 1024
   #endif
#endif                                  /* MaxPath */

#ifndef StackAlign
   #define StackAlign (SIZEOF_INT_P * 2)
#endif                                  /* StackAlign */

#ifndef WordBits
   #if Windows
      #define WordBits (SIZEOF_INT_P * 8)
   #else
      #define WordBits (SIZEOF_LONG_INT * 8)
   #endif                               /* Windows */
#endif                                  /* WordBits */

#ifndef IntBits
   #define IntBits (SIZEOF_INT * 8)
#endif                                  /* IntBits */

#if (WordBits == 64)
   #define LINTFRMT "l"

   #if Windows
      #define MSWIN64
      #define LongLongWord
   #endif                               /* Windows */
   #ifndef OLD_NTGCC
      #define Double
   #endif                               /* OLD_NTGCC */
#else
   #define LINTFRMT ""
    #ifdef ARM
      #define Double
   #endif                               /* ARM */
#endif

#ifndef SourceSuffix
   #define SourceSuffix ".icn"
#endif                                  /* SourceSuffix */

/*
 * Representations of directories. LocalDir is the "current working directory".
 *  SourceDir is where the source file is.
 */

#define LocalDir ""
#define SourceDir (char *)NULL

#ifndef TargetDir
   #define TargetDir LocalDir
#endif                                  /* TargetDir */

/*
 * Features enabled by default under certain systems
 */

#ifndef Pipes
   #if UNIX || VMS
      #define Pipes
   #endif                               /* UNIX || VMS */
#endif                                  /* Pipes */

#ifndef KeyboardFncs
   #if UNIX
      #ifndef NoKeyboardFncs
         #define KeyboardFncs
      #endif                            /* NoKeyboardFncs */
   #endif                               /* UNIX */
#endif                                  /* KeyboardFncs */

#ifndef ReadDirectory
   #if UNIX
      #define ReadDirectory
   #endif                               /* UNIX*/
#endif                                  /* ReadDirectory */

#ifndef Dbm
   #if UNIX
   #ifndef NoDbm
      #define Dbm 1
   #endif                               /* NoDbm */
   #endif                               /* UNIX */
#endif                                  /* Dbm */

/*
 * Default sizing and such.
 */

#define WordSize sizeof(word)

#ifndef ByteBits
   #define ByteBits 8
#endif                                  /* ByteBits */

/*
 *  The following definitions assume ANSI C.
 */
#define Cat(x,y) x##y
#define Lit(x) #x
#define Bell '\a'

/*
 *  something to handle a cast problem for signal().
 */
#ifndef SigFncCast
   #define SigFncCast (void (*)(int))
#endif                                  /* SigFncCast */

#ifndef QSortFncCast
   #define QSortFncCast int (*)(const void *,const void *)
#endif                                  /* QSortFncCast */

/*
 * Customize output if not pre-defined.
 */

#if EBCDIC
   #define BackSlash "\xe0"
#else                                   /* EBCDIC */
   #define BackSlash "\\"
#endif                                  /* EBCDIC */

#ifndef WriteBinary
   #define WriteBinary "wb"
#endif                                  /* WriteBinary */

#ifndef ReadBinary
   #define ReadBinary "rb"
#endif                                  /* ReadBinary */

#ifndef ReadWriteBinary
   #define ReadWriteBinary "wb+"
#endif                                  /* ReadWriteBinary */

#ifndef ReadEndBinary
   #define ReadEndBinary "r+b"
#endif                                  /* ReadEndBinary */

#ifndef WriteText
   #define WriteText "w"
#endif                                  /* WriteText */

#ifndef ReadText
   #define ReadText "r"
#endif                                  /* ReadText */

/*
 * The following code is operating-system dependent [@config.01].
 *  Any configuration stuff that has to be done at this point.
 */

#if PORT
   /* Probably nothing is needed. */
Deliberate Syntax Error
#endif                                  /* PORT */

#if VMS
   #define ExecSuffix ".exe"
   #define ObjSuffix ".obj"
   #define LibSuffix ".olb"
#endif                                  /* VMS */

#if MSDOS

   /*
    *  Define compiler-specific symbols to be zero if not already
    *  defined.
    */

   #ifndef MICROSOFT
      #define MICROSOFT 0
   #endif                               /* MICROSOFT */

   #ifndef CSET2
      #define CSET2 0
   #endif                               /* CSet/2 */

   #ifndef CSET2V2
      #define CSET2V2 0
   #endif                               /* CSet/2 version 2 */

   #ifndef TURBO
      #define TURBO 0
   #endif                               /* TURBO */

   #ifndef NT
      #define NT 0
   #endif                               /* NT */

#endif                                  /* MSDOS */

#ifndef NoWildCards
   #if NT || MICROSOFT
      #define WildCards 1
   #else                                /* NT || ... */
      #define WildCards 0
   #endif                               /* NT || ... */
#else                                   /* NoWildCards */
   #define WildCards 0
#endif                                  /* NoWildCards */

/*
 * End of operating-system specific code.
 */

#ifndef DiffPtrs
   #define DiffPtrs(p1,p2) (word)((p1)-(p2))
#endif                                  /* DiffPtrs */

#ifndef AllocReg
   #define AllocReg(n) malloc((msize)n)
#endif                                  /* AllocReg */

#define MaxFileName MaxPath

#ifndef RttSuffix
   #define RttSuffix ".r"
#endif                                  /* RttSuffix */

#ifndef DBSuffix
   #define DBSuffix ".db"
#endif                                  /* DBSuffix */

#ifndef PPInit
   #define PPInit ""
#endif                                  /* PPInit */

#ifndef PPDirectives
   #define PPDirectives {"passthru", PpKeep}, {"host", PpKeep}, {"rawc", PpKeep},
#endif                                  /* PPDirectives */

#ifndef NoPseudoPty
   #define PseudoPty
#endif                                  /* PseudoPty */

#ifndef NoArrays
   #ifdef Arrays
   #undef Arrays
   #endif
   #define Arrays 1
#endif                                  /* Arrays */

#if !defined(NoDescriptorDouble) && (WordBits==64)
   #define DescriptorDouble 1
#endif                                  /* DescriptorDouble */


#ifndef NoPattern
   #define PatternType 1
#endif                                  /* PatternType */

#ifndef ExecSuffix
   #define ExecSuffix ""
#endif                                  /* ExecSuffix */

#ifndef CSuffix
   #define CSuffix ".c"
#endif                                  /* CSuffix */

#ifndef HSuffix
   #define HSuffix ".h"
#endif                                  /* HSuffix */

#ifndef ObjSuffix
   #define ObjSuffix ".o"
#endif                                  /* ObjSuffix */

#ifndef LibSuffix
   #define LibSuffix ".a"
#endif                                  /* LibSuffix */

#ifndef CComp
   #define CComp "cc"
#endif                                  /* CComp */

#ifndef COpts
   #define COpts ""
#endif                                  /* COpts */

/*
 * Note, size of the hash table is a power of 2:
 */
#define IHSize 128
#define IHasher(x)      (((unsigned int)(uword)(x))&(IHSize-1))

#if COMPILER

   /*
    * Code for the compiler.
    */
   #undef MultiProgram          /* no way -- interpreter only */
   #undef EventMon              /* presently not supported in the compiler */
   #undef MonitoredTrappedVar   /* no way */
   #undef ExecImages            /* interpreter only */
   #undef HAVE_IODBC            /* ODBC interpreter only until dynamic */
   #undef ISQL                  /* records get added to the compiler */
   #undef OVLD                  /* operator overloading -- not supported */

#else                                   /* COMPILER */

   /*
    * Code for the interpreter.
    */
   #ifndef IcodeSuffix
      #define IcodeSuffix ""
   #endif                               /* IcodeSuffix */

   #ifndef IcodeASuffix
      #define IcodeASuffix ""
   #endif                               /* IcodeASuffix */

   #ifndef U1Suffix
      #define U1Suffix ".u1"
   #endif                               /* U1Suffix */

   #ifndef U2Suffix
      #define U2Suffix ".u2"
   #endif                               /* U2Suffix */

   #ifndef USuffix
      #define USuffix ".u"
   #endif                               /* USuffix */

#endif                                  /* COMPILER */

#if UNIX
   #undef Header
   #define Header
   #undef ShellHeader
   #define ShellHeader
#endif                                  /* UNIX */

/*
 * I don't care what autoconf says, some platforms (Solaris) have trouble
 * with vfork.
 */
#ifdef NoVFork
#undef HAVE_WORKING_VFORK
#endif

#if MSDOS && !NT
   #undef DirectExecution
   #define DirectExecution
#endif                                  /* MSDOS && !NT */

#ifdef Header
   #undef DirectExecution
   #define DirectExecution
#endif                                  /* Header */

#ifdef PthreadCoswitch
#define CoClean 1
#endif                                  /* PthreadCoswitch */

#if COMPILER
#undef StackCheck
#define NoStackCheck
#endif                                  /* COMPILER */

#ifndef Concurrent
#ifndef NoStackCheck
#define StackCheck 1
#endif                                  /* NoStackCheck */
#endif                                  /* Concurrent */

#ifdef NoLIBZ
#undef HAVE_LIBZ
#define HAVE_LIBZ 0
#endif                                  /* NoLIBZ */

#ifdef NoJPEG
#undef HAVE_LIBJPEG
#define HAVE_LIBJPEG 0
#endif                                  /* NoJPEG */

#ifdef NoPNG
#undef HAVE_LIBPNG
#define HAVE_LIBPNG 0
#endif                                  /* NoPNG */

#ifdef NoGL
#undef HAVE_LIBGL
#define HAVE_LIBGL 0
#endif                                  /* NoGL */

#ifdef NoODBC
#undef HAVE_LIBIODBC
#define HAVE_LIBIODBC 0
#define HAVE_LIBODBC 0
#endif                                  /* NoODBC */

#ifdef NoProfil
#undef HAVE_PROFIL
#define HAVE_PROFIL 0
#endif                                  /* NoProfil */

#ifndef HAVE_LIBZ
#define HAVE_LIBZ 0
#endif                                  /* HAVE_LIBZ */

#if !HAVE_LIBZ && !defined(NTGCC)
#ifdef HAVE_LIBPNG
#undef HAVE_LIBPNG
#endif                                  /* HAVE_LIBPNG */
#define HAVE_LIBPNG 0
#endif                                  /* !HAVE_LIBZ */

#ifndef HAVE_LIBJPEG
#define HAVE_LIBJPEG 0
#endif                                  /* HAVE_LIBJPEG */

#ifndef HAVE_LIBGL
#define HAVE_LIBGL 0
#endif                                  /* HAVE_LIBGL */

#ifndef HAVE_LIBIODBC
#define HAVE_LIBIODBC 0
#endif                                  /* HAVE_LIBIODBC */
#ifndef HAVE_LIBODBC
#define HAVE_LIBODBC 0
#endif                                  /* HAVE_LIBODBC */

#ifndef HAVE_FTGL
#define HAVE_FTGL 0
#endif                                  /* HAVE_FTGL */

#if HAVE_LIBGL
#define Graphics3D 1
#else                                   /* HAVE_LIBGL */
#if HAVE_FTGL
#undef HAVE_FTGL
#define HAVE_FTGL 0
#endif                                  /* HAVE_FTGL */
#endif                                  /* HAVE_LIBGL */

#ifndef Arrays
  #undef Graphics3D
  #undef PatternType
#endif

#ifndef Graphics
#undef Graphics3D
#endif                                  /* Graphics */

#if HAVE_LIBIODBC || HAVE_LIBODBC
#define ISQL 1
#endif                                  /* HAVE_LIBIODBC */
#ifdef ISQL
#ifndef SQL_LENORIND

#ifdef MSWIN64
    #define SQL_LENORIND SQLLEN
#else                                   /* MSWIN64 */
    #define SQL_LENORIND SQLINTEGER
#endif                                  /* MSWIN64 */

#endif                                  /* SQL_LENORIND */
#endif                                  /* ISQL */

#ifndef NoLoadFunc
#if HAVE_LIBDL
#define LoadFunc
#endif                                  /* HAVE_LIBDL */
#endif


/*
 *  Vsizeof is for use with variable-sized (i.e., indefinite)
 *   structures containing an array of descriptors declared of size 1
 *   to avoid compiler warnings associated with 0-sized arrays.
 */

#define Vsizeof(s)      (sizeof(s) - sizeof(struct descrip))

/*
 * Other sizeof macros:
 *
 *  Wsizeof(x)  -- Size of x in words.
 *  Vwsizeof(x) -- Size of x in words, minus the size of a descriptor.  Used
 *   when structures have a potentially null list of descriptors
 *   at their end.
 */

#define Wsizeof(x)      ((sizeof(x) + sizeof(word) - 1) / sizeof(word))
#define Vwsizeof(x)     ((sizeof(x) - sizeof(struct descrip) +\
                           sizeof(word) - 1) / sizeof(word))

#endif                                  /* UNICON_CONFIG_H */

/*
 * Ensure configurations that are no longer supported cannot be built by accident.
 * The date gives a clue to the last commit where the configuration was supported.
 */

#if defined(CRAY) || defined (CRAY_STACK)
#error The CRAY configuration option is no longer supported (since 7 Mar 2024)
#endif                                  /* CRAY */

#if defined(MACINTOSH)
#error The MACINTOSH configuration option is no longer supported (since 7 Mar 2024)
#endif                                  /* MACINTOSH */

#if defined(MacGraph)
#error The MacGraph configuration option is no longer supported (since 8 Mar 2024)
#endif                                  /* MacGraph */

/****************************************   end ../h/../h/config.h   */


/****************************************  from ../h/../h/sys.h:  */

/*
 * sys.h -- system include files.
 */

#ifdef ConsoleWindow
#undef putc
#undef printf
#undef fprintf
#undef fflush
#endif                                  /* ConsoleWindow */

/*
 * Universal (Standard ANSI C) includes.
 */
#include <ctype.h>
#include <errno.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

   /* not sure whether this one should always be in effect. Maybe it should.
    * moved from config.h so that it does not knock out exit's prototype.
    */
   #ifdef ConsoleWindow
      #undef exit
      #define exit c_exit
   #endif                               /* Console Window */

/*
 * Operating-system-dependent includes.
 */
#if PORT
   Deliberate Syntax Error
#endif                                  /* PORT */

#ifdef ISQL
  #undef Type
  #undef Precision
#endif                                  /* ISQL */

#if MSDOS
   #undef Type
   #include <sys/types.h>
   #include <sys/stat.h>
   #include <fcntl.h>
#ifdef NTGCC
   #include <sys/time.h>
   /* Mingw GCC 4.8.1 idiotically #define's stat. We need that name intact. */
#ifdef stat
   #undef stat
#endif                                  /* stat */
   #include <dirent.h>
   #ifndef OLD_NTGCC
   /* The new GCC needs locking.h but the old one doesn't*/
   #include <sys/locking.h>
   #endif                               /* OLD_NTGCC */
#endif                                  /* NTGCC */
#ifdef MSVC
   #include <direct.h>
#endif                                  /* MSVC */
   #ifdef MSWindows
      #define int_PASCAL int PASCAL
      #define LRESULT_CALLBACK LRESULT CALLBACK
      #define BOOL_CALLBACK BOOL CALLBACK
      #ifdef PosixFns

      /*
       * Avoid a conflict between rpcndr.h and jmorecfg.h (jpeg) about "boolean"
       * uncomment the "boolean" lines below if you have this issue.
       */
      /* #define boolean bolean */
      #include <winsock2.h>
      /* #undef boolean */
      #include<ws2tcpip.h>
      #else                                     /* PosixFns */
      #include <windows.h>
      #endif                                    /* PosixFns */
      #include <mmsystem.h>
      #include <process.h>
   #else                                        /* MSWindows */
      #if NT
      #ifndef PATH_MAX
      #define PATH_MAX 512
      #endif                                    /* PATH_MAX */
      #ifdef PosixFns
      /*
       * Avoid a conflict between rpcndr.h and jmorecfg.h (jpeg) about "boolean"
       * uncomment the "boolean" lines below if you have this issue.
       */
      /* #define boolean bolean */
      #include <winsock2.h>
      /* #undef boolean */
      #include<ws2tcpip.h>
      #else
         #if defined(ISQL) || defined(Audio)
           #include <windows.h>
           #include <mmsystem.h>
         #endif                                 /* ISQL */
      #endif                                    /* PosixFns */
      #endif                                    /* NT */
   #endif                               /* MSWindows */
   #include <setjmp.h>
   #define Type(d) (int)((d).dword & TypeMask)
   #undef lst1
   #undef lst2

   /*MinGW32 needs these defined*/
   #ifndef EWOULDBLOCK

      #define EWOULDBLOCK             WSAEWOULDBLOCK
      #define EINPROGRESS             WSAEINPROGRESS
      #define EALREADY                WSAEALREADY
      #define ENOTSOCK                WSAENOTSOCK
      #define EDESTADDRREQ            WSAEDESTADDRREQ
      #define EMSGSIZE                WSAEMSGSIZE
      #define EPROTOTYPE              WSAEPROTOTYPE
      #define ENOPROTOOPT             WSAENOPROTOOPT
      #define EPROTONOSUPPORT         WSAEPROTONOSUPPORT
      #define ESOCKTNOSUPPORT         WSAESOCKTNOSUPPORT
      #define EOPNOTSUPP              WSAEOPNOTSUPP
      #define EPFNOSUPPORT            WSAEPFNOSUPPORT
      #define EAFNOSUPPORT            WSAEAFNOSUPPORT
      #define EADDRINUSE              WSAEADDRINUSE
      #define EADDRNOTAVAIL           WSAEADDRNOTAVAIL
      #define ENETDOWN                WSAENETDOWN
      #define ENETUNREACH             WSAENETUNREACH
      #define ENETRESET               WSAENETRESET
      #define ECONNABORTED            WSAECONNABORTED
      #define ECONNRESET              WSAECONNRESET
      #define ENOBUFS                 WSAENOBUFS
      #define EISCONN                 WSAEISCONN
      #define ENOTCONN                WSAENOTCONN
      #define ESHUTDOWN               WSAESHUTDOWN
      #define ETOOMANYREFS            WSAETOOMANYREFS
      #define ETIMEDOUT               WSAETIMEDOUT
      #define ECONNREFUSED            WSAECONNREFUSED
      #define ELOOP                   WSAELOOP
      #define EHOSTDOWN               WSAEHOSTDOWN
      #define EHOSTUNREACH            WSAEHOSTUNREACH
      #define EPROCLIM                WSAEPROCLIM
      #define EUSERS                  WSAEUSERS
      #define EDQUOT                  WSAEDQUOT
      #define ESTALE                  WSAESTALE
      #define EREMOTE                 WSAEREMOTE
#endif                                          /* EWOULDBLOCK */

#endif                                  /* MSDOS */

#if UNIX
   #include <dirent.h>
   #include <limits.h>
   #include <unistd.h>
   #include <sys/stat.h>
   #include <sys/time.h>
   #include <sys/times.h>
   #include <sys/types.h>
#ifdef MacOS
   #include <sys/sysctl.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
   #include <sys/resource.h>
#endif                                  /* HAVE_SYS_RESOURCE_H */
#ifdef HAVE_SYS_FILE_H
   #include <sys/file.h>
#endif                                  /* HAVE_FILE_H */
   #include <termios.h>
   #include <poll.h>
   #ifdef SysSelectH
      #include <sys/select.h>
   #endif
#if defined(PseudoPty) || defined(Audio)
   #include <fcntl.h>
#endif                                  /* PseudoPty || Audio */
#ifdef Audio
   #include <sys/ioctl.h>
#ifdef OpenBSD
   #include <sndio.h>
#else
   #include <linux/soundcard.h>
#endif
   #include <pthread.h>
#endif                                  /* Audio */
#endif                                  /* UNIX */

#ifdef HAVE_LIBPTHREAD
#if !UNIX || !defined(Audio)
#include <pthread.h>
#endif                                  /* PthreadCoswitch & ! Audio */
#include <semaphore.h>
#endif                                  /* HAVE_LIBPTHREAD */

#if VMS
   #include <types.h>
   #include <dvidef>
   #include <iodef>
   #include <stsdef.h>
#endif                                  /* VMS */

#include <stdarg.h>
/*
 * Window-system-dependent includes.
 */
#ifdef ConsoleWindow
   #undef printf
   #undef fprintf
   #undef fflush
   #define printf Consoleprintf
   #define fprintf Consolefprintf
   #define fflush Consolefflush
#endif                                  /* ConsoleWindow */

#ifdef XWindows
   /*
    * Undef VMS under UNIX, and UNIX under VMS,
    * to avoid confusing the tests within the X header files.
    */
   #if VMS
      #undef UNIX


/****************************************  from ../h/../h/decw$include:Xlib.h:  */

/* [file not found] */

/****************************************   end ../h/../h/decw$include:Xlib.h   */


/****************************************  from ../h/../h/decw$include:Xutil.h:  */

/* [file not found] */

/****************************************   end ../h/../h/decw$include:Xutil.h   */


/****************************************  from ../h/../h/decw$include:Xos.h:  */

/* [file not found] */

/****************************************   end ../h/../h/decw$include:Xos.h   */


/****************************************  from ../h/../h/decw$include:Xatom.h:  */

/* [file not found] */

/****************************************   end ../h/../h/decw$include:Xatom.h   */

      #ifdef HAVE_LIBXPM


/****************************************  from ../h/../h/../xpm/xpm.h:  */

/*
 * Copyright (C) 1989-95 GROUPE BULL
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * GROUPE BULL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of GROUPE BULL shall not be
 * used in advertising or otherwise to promote the sale, use or other dealings
 * in this Software without prior written authorization from GROUPE BULL.
 */

/*****************************************************************************\
* xpm.h:                                                                      *
*                                                                             *
*  XPM library                                                                *
*  Include file                                                               *
*                                                                             *
*  Developed by Arnaud Le Hors                                                *
\*****************************************************************************/

/*
 * The code related to FOR_MSW has been added by
 * HeDu (hedu@cul-ipn.uni-kiel.de) 4/94
 */

#ifndef XPM_H
#define XPM_H

/*
 * first some identification numbers:
 * the version and revision numbers are determined with the following rule:
 * SO Major number = LIB minor version number.
 * SO Minor number = LIB sub-minor version number.
 * e.g: Xpm version 3.2f
 *      we forget the 3 which is the format number, 2 gives 2, and f gives 6.
 *      thus we have XpmVersion = 2 and XpmRevision = 6
 *      which gives  SOXPMLIBREV = 2.6
 *
 * Then the XpmIncludeVersion number is built from these numbers.
 */
#define XpmFormat 3
#define XpmVersion 4
#define XpmRevision 11
#define XpmIncludeVersion ((XpmFormat * 100 + XpmVersion) * 100 + XpmRevision)

#ifdef FOR_MSW
# define SYSV                   /* uses memcpy string.h etc. */
# include <malloc.h>


/****************************************  from ../h/../h/../xpm/simx.h:  */

/* [file not found] */

/****************************************   end ../h/../h/../xpm/simx.h   */
#define NEED_STRCASECMP         /* at least for MSVC++ */
#else /* FOR_MSW */
#  include <X11/Xlib.h>
#  include <X11/Xutil.h>
#endif /* FOR_MSW */

/* let's define Pixel if it is not done yet */
#if ! defined(_XtIntrinsic_h) && ! defined(PIXEL_T)
typedef unsigned long Pixel;    /* Index into colormap */
# define PIXEL_T
#endif


/* Return ErrorStatus codes:
 * null     if full success
 * positive if partial success
 * negative if failure
 */

#define XpmColorError    1
#define XpmSuccess       0
#define XpmOpenFailed   -1
#define XpmFileInvalid  -2
#define XpmNoMemory     -3
#define XpmColorFailed  -4

typedef struct {
    char *name;                 /* Symbolic color name */
    char *value;                /* Color value */
    Pixel pixel;                /* Color pixel */
}      XpmColorSymbol;

typedef struct {
    char *name;                 /* name of the extension */
    unsigned int nlines;        /* number of lines in this extension */
    char **lines;               /* pointer to the extension array of strings */
}      XpmExtension;

typedef struct {
    char *string;               /* characters string */
    char *symbolic;             /* symbolic name */
    char *m_color;              /* monochrom default */
    char *g4_color;             /* 4 level grayscale default */
    char *g_color;              /* other level grayscale default */
    char *c_color;              /* color default */
}      XpmColor;

typedef struct {
    unsigned int width;         /* image width */
    unsigned int height;        /* image height */
    unsigned int cpp;           /* number of characters per pixel */
    unsigned int ncolors;       /* number of colors */
    XpmColor *colorTable;       /* list of related colors */
    unsigned int *data;         /* image data */
}      XpmImage;

typedef struct {
    unsigned long valuemask;    /* Specifies which attributes are defined */
    char *hints_cmt;            /* Comment of the hints section */
    char *colors_cmt;           /* Comment of the colors section */
    char *pixels_cmt;           /* Comment of the pixels section */
    unsigned int x_hotspot;     /* Returns the x hotspot's coordinate */
    unsigned int y_hotspot;     /* Returns the y hotspot's coordinate */
    unsigned int nextensions;   /* number of extensions */
    XpmExtension *extensions;   /* pointer to array of extensions */
}      XpmInfo;

typedef int (*XpmAllocColorFunc)(
    Display*                    /* display */,
    Colormap                    /* colormap */,
    char*                       /* colorname */,
    XColor*                     /* xcolor */,
    void*                       /* closure */
);

typedef int (*XpmFreeColorsFunc)(
    Display*                    /* display */,
    Colormap                    /* colormap */,
    Pixel*                      /* pixels */,
    int                         /* npixels */,
    void*                       /* closure */
);

typedef struct {
    unsigned long valuemask;            /* Specifies which attributes are
                                           defined */

    Visual *visual;                     /* Specifies the visual to use */
    Colormap colormap;                  /* Specifies the colormap to use */
    unsigned int depth;                 /* Specifies the depth */
    unsigned int width;                 /* Returns the width of the created
                                           pixmap */
    unsigned int height;                /* Returns the height of the created
                                           pixmap */
    unsigned int x_hotspot;             /* Returns the x hotspot's
                                           coordinate */
    unsigned int y_hotspot;             /* Returns the y hotspot's
                                           coordinate */
    unsigned int cpp;                   /* Specifies the number of char per
                                           pixel */
    Pixel *pixels;                      /* List of used color pixels */
    unsigned int npixels;               /* Number of used pixels */
    XpmColorSymbol *colorsymbols;       /* List of color symbols to override */
    unsigned int numsymbols;            /* Number of symbols */
    char *rgb_fname;                    /* RGB text file name */
    unsigned int nextensions;           /* Number of extensions */
    XpmExtension *extensions;           /* List of extensions */

    unsigned int ncolors;               /* Number of colors */
    XpmColor *colorTable;               /* List of colors */
/* 3.2 backward compatibility code */
    char *hints_cmt;                    /* Comment of the hints section */
    char *colors_cmt;                   /* Comment of the colors section */
    char *pixels_cmt;                   /* Comment of the pixels section */
/* end 3.2 bc */
    unsigned int mask_pixel;            /* Color table index of transparent
                                           color */

    /* Color Allocation Directives */
    Bool exactColors;                   /* Only use exact colors for visual */
    unsigned int closeness;             /* Allowable RGB deviation */
    unsigned int red_closeness;         /* Allowable red deviation */
    unsigned int green_closeness;       /* Allowable green deviation */
    unsigned int blue_closeness;        /* Allowable blue deviation */
    int color_key;                      /* Use colors from this color set */

    Pixel *alloc_pixels;                /* Returns the list of alloc'ed color
                                           pixels */
    int nalloc_pixels;                  /* Returns the number of alloc'ed
                                           color pixels */

    Bool alloc_close_colors;            /* Specify whether close colors should
                                           be allocated using XAllocColor
                                           or not */
    int bitmap_format;                  /* Specify the format of 1bit depth
                                           images: ZPixmap or XYBitmap */

    /* Color functions */
    XpmAllocColorFunc alloc_color;      /* Application color allocator */
    XpmFreeColorsFunc free_colors;      /* Application color de-allocator */
    void *color_closure;                /* Application private data to pass to
                                           alloc_color and free_colors */

}      XpmAttributes;

/* XpmAttributes value masks bits */
#define XpmVisual          (1L<<0)
#define XpmColormap        (1L<<1)
#define XpmDepth           (1L<<2)
#define XpmSize            (1L<<3)      /* width & height */
#define XpmHotspot         (1L<<4)      /* x_hotspot & y_hotspot */
#define XpmCharsPerPixel   (1L<<5)
#define XpmColorSymbols    (1L<<6)
#define XpmRgbFilename     (1L<<7)
/* 3.2 backward compatibility code */
#define XpmInfos           (1L<<8)
#define XpmReturnInfos     XpmInfos
/* end 3.2 bc */
#define XpmReturnPixels    (1L<<9)
#define XpmExtensions      (1L<<10)
#define XpmReturnExtensions XpmExtensions

#define XpmExactColors     (1L<<11)
#define XpmCloseness       (1L<<12)
#define XpmRGBCloseness    (1L<<13)
#define XpmColorKey        (1L<<14)

#define XpmColorTable      (1L<<15)
#define XpmReturnColorTable XpmColorTable

#define XpmReturnAllocPixels (1L<<16)
#define XpmAllocCloseColors (1L<<17)
#define XpmBitmapFormat    (1L<<18)

#define XpmAllocColor      (1L<<19)
#define XpmFreeColors      (1L<<20)
#define XpmColorClosure    (1L<<21)


/* XpmInfo value masks bits */
#define XpmComments        XpmInfos
#define XpmReturnComments  XpmComments

/* XpmAttributes mask_pixel value when there is no mask */
#ifndef FOR_MSW
#define XpmUndefPixel 0x80000000
#else
/* int is only 16 bit for MSW */
#define XpmUndefPixel 0x8000
#endif

/*
 * color keys for visual type, they must fit along with the number key of
 * each related element in xpmColorKeys[] defined in XpmI.h
 */
#define XPM_MONO        2
#define XPM_GREY4       3
#define XPM_GRAY4       3
#define XPM_GREY        4
#define XPM_GRAY        4
#define XPM_COLOR       5


/* macros for forward declarations of functions with prototypes */
#if  __STDC__ || defined(__cplusplus) || defined(c_plusplus)
#define FUNC(f, t, p) extern t f p
#define LFUNC(f, t, p) static t f p
#else
#define FUNC(f, t, p) extern t f()
#define LFUNC(f, t, p) static t f()
#endif


/*
 * functions declarations
 */

#ifdef __cplusplus
extern "C" {
#endif

/* FOR_MSW, all ..Pixmap.. are excluded, only the ..XImage.. are used */

#if !defined(FOR_MSW)
    FUNC(XpmCreatePixmapFromData, int, (Display *display,
                                        Drawable d,
                                        char **data,
                                        Pixmap *pixmap_return,
                                        Pixmap *shapemask_return,
                                        XpmAttributes *attributes));

    FUNC(XpmCreateDataFromPixmap, int, (Display *display,
                                        char ***data_return,
                                        Pixmap pixmap,
                                        Pixmap shapemask,
                                        XpmAttributes *attributes));

    FUNC(XpmReadFileToPixmap, int, (Display *display,
                                    Drawable d,
                                    char *filename,
                                    Pixmap *pixmap_return,
                                    Pixmap *shapemask_return,
                                    XpmAttributes *attributes));

    FUNC(XpmWriteFileFromPixmap, int, (Display *display,
                                       char *filename,
                                       Pixmap pixmap,
                                       Pixmap shapemask,
                                       XpmAttributes *attributes));
#endif

    FUNC(XpmCreateImageFromData, int, (Display *display,
                                       char **data,
                                       XImage **image_return,
                                       XImage **shapemask_return,
                                       XpmAttributes *attributes));

    FUNC(XpmCreateDataFromImage, int, (Display *display,
                                       char ***data_return,
                                       XImage *image,
                                       XImage *shapeimage,
                                       XpmAttributes *attributes));

    FUNC(XpmReadFileToImage, int, (Display *display,
                                   char *filename,
                                   XImage **image_return,
                                   XImage **shapeimage_return,
                                   XpmAttributes *attributes));

    FUNC(XpmWriteFileFromImage, int, (Display *display,
                                      char *filename,
                                      XImage *image,
                                      XImage *shapeimage,
                                      XpmAttributes *attributes));

    FUNC(XpmCreateImageFromBuffer, int, (Display *display,
                                         char *buffer,
                                         XImage **image_return,
                                         XImage **shapemask_return,
                                         XpmAttributes *attributes));
#if !defined(FOR_MSW)
    FUNC(XpmCreatePixmapFromBuffer, int, (Display *display,
                                          Drawable d,
                                          char *buffer,
                                          Pixmap *pixmap_return,
                                          Pixmap *shapemask_return,
                                          XpmAttributes *attributes));

    FUNC(XpmCreateBufferFromImage, int, (Display *display,
                                         char **buffer_return,
                                         XImage *image,
                                         XImage *shapeimage,
                                         XpmAttributes *attributes));

    FUNC(XpmCreateBufferFromPixmap, int, (Display *display,
                                          char **buffer_return,
                                          Pixmap pixmap,
                                          Pixmap shapemask,
                                          XpmAttributes *attributes));
#endif
    FUNC(XpmReadFileToBuffer, int, (char *filename, char **buffer_return));
    FUNC(XpmWriteFileFromBuffer, int, (char *filename, char *buffer));

    FUNC(XpmReadFileToData, int, (char *filename, char ***data_return));
    FUNC(XpmWriteFileFromData, int, (char *filename, char **data));

    FUNC(XpmAttributesSize, int, ());
    FUNC(XpmFreeAttributes, void, (XpmAttributes *attributes));
    FUNC(XpmFreeExtensions, void, (XpmExtension *extensions,
                                   int nextensions));

    FUNC(XpmFreeXpmImage, void, (XpmImage *image));
    FUNC(XpmFreeXpmInfo, void, (XpmInfo *info));
    FUNC(XpmGetErrorString, char *, (int errcode));
    FUNC(XpmLibraryVersion, int, ());

    /* XpmImage functions */
    FUNC(XpmReadFileToXpmImage, int, (char *filename,
                                      XpmImage *image,
                                      XpmInfo *info));

    FUNC(XpmWriteFileFromXpmImage, int, (char *filename,
                                         XpmImage *image,
                                         XpmInfo *info));
#if !defined(FOR_MSW)
    FUNC(XpmCreatePixmapFromXpmImage, int, (Display *display,
                                            Drawable d,
                                            XpmImage *image,
                                            Pixmap *pixmap_return,
                                            Pixmap *shapemask_return,
                                            XpmAttributes *attributes));
#endif
    FUNC(XpmCreateImageFromXpmImage, int, (Display *display,
                                           XpmImage *image,
                                           XImage **image_return,
                                           XImage **shapeimage_return,
                                           XpmAttributes *attributes));

    FUNC(XpmCreateXpmImageFromImage, int, (Display *display,
                                           XImage *image,
                                           XImage *shapeimage,
                                           XpmImage *xpmimage,
                                           XpmAttributes *attributes));
#if !defined(FOR_MSW)
    FUNC(XpmCreateXpmImageFromPixmap, int, (Display *display,
                                            Pixmap pixmap,
                                            Pixmap shapemask,
                                            XpmImage *xpmimage,
                                            XpmAttributes *attributes));
#endif
    FUNC(XpmCreateDataFromXpmImage, int, (char ***data_return,
                                          XpmImage *image,
                                          XpmInfo *info));

    FUNC(XpmCreateXpmImageFromData, int, (char **data,
                                          XpmImage *image,
                                          XpmInfo *info));

    FUNC(XpmCreateXpmImageFromBuffer, int, (char *buffer,
                                            XpmImage *image,
                                            XpmInfo *info));

    FUNC(XpmCreateBufferFromXpmImage, int, (char **buffer_return,
                                            XpmImage *image,
                                            XpmInfo *info));

    FUNC(XpmGetParseError, int, (char *filename,
                                 int *linenum_return,
                                 int *charnum_return));

    FUNC(XpmFree, void, (void *ptr));

#ifdef __cplusplus
} /* for C++ V2.0 */
#endif


/* backward compatibility */

/* for version 3.0c */
#define XpmPixmapColorError  XpmColorError
#define XpmPixmapSuccess     XpmSuccess
#define XpmPixmapOpenFailed  XpmOpenFailed
#define XpmPixmapFileInvalid XpmFileInvalid
#define XpmPixmapNoMemory    XpmNoMemory
#define XpmPixmapColorFailed XpmColorFailed

#define XpmReadPixmapFile(dpy, d, file, pix, mask, att) \
    XpmReadFileToPixmap(dpy, d, file, pix, mask, att)
#define XpmWritePixmapFile(dpy, file, pix, mask, att) \
    XpmWriteFileFromPixmap(dpy, file, pix, mask, att)

/* for version 3.0b */
#define PixmapColorError  XpmColorError
#define PixmapSuccess     XpmSuccess
#define PixmapOpenFailed  XpmOpenFailed
#define PixmapFileInvalid XpmFileInvalid
#define PixmapNoMemory    XpmNoMemory
#define PixmapColorFailed XpmColorFailed

#define ColorSymbol XpmColorSymbol

#define XReadPixmapFile(dpy, d, file, pix, mask, att) \
    XpmReadFileToPixmap(dpy, d, file, pix, mask, att)
#define XWritePixmapFile(dpy, file, pix, mask, att) \
    XpmWriteFileFromPixmap(dpy, file, pix, mask, att)
#define XCreatePixmapFromData(dpy, d, data, pix, mask, att) \
    XpmCreatePixmapFromData(dpy, d, data, pix, mask, att)
#define XCreateDataFromPixmap(dpy, data, pix, mask, att) \
    XpmCreateDataFromPixmap(dpy, data, pix, mask, att)

#endif

/****************************************   end ../h/../h/../xpm/xpm.h   */
      #endif                            /* HAVE_LIBXPM */

      #undef UNIX
      #define UNIX 0
   #else                                /* VMS */
      #undef VMS

#ifdef Redhat71
/* due to a header bug, we must commit a preemptive first strike of Xosdefs */
#include <X11/Xosdefs.h>

#ifdef X_WCHAR
#undef X_WCHAR
#endif
#ifdef X_NOT_STDC_ENV
#undef X_NOT_STDC_ENV
#endif
#endif                                  /* Redhat71 */

      #ifdef HAVE_LIBXPM


/****************************************  from ../h/../h/../xpm/xpm.h:  */

/*
 * Copyright (C) 1989-95 GROUPE BULL
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * GROUPE BULL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of GROUPE BULL shall not be
 * used in advertising or otherwise to promote the sale, use or other dealings
 * in this Software without prior written authorization from GROUPE BULL.
 */

/*****************************************************************************\
* xpm.h:                                                                      *
*                                                                             *
*  XPM library                                                                *
*  Include file                                                               *
*                                                                             *
*  Developed by Arnaud Le Hors                                                *
\*****************************************************************************/

/*
 * The code related to FOR_MSW has been added by
 * HeDu (hedu@cul-ipn.uni-kiel.de) 4/94
 */

#ifndef XPM_H
#define XPM_H

/*
 * first some identification numbers:
 * the version and revision numbers are determined with the following rule:
 * SO Major number = LIB minor version number.
 * SO Minor number = LIB sub-minor version number.
 * e.g: Xpm version 3.2f
 *      we forget the 3 which is the format number, 2 gives 2, and f gives 6.
 *      thus we have XpmVersion = 2 and XpmRevision = 6
 *      which gives  SOXPMLIBREV = 2.6
 *
 * Then the XpmIncludeVersion number is built from these numbers.
 */
#define XpmFormat 3
#define XpmVersion 4
#define XpmRevision 11
#define XpmIncludeVersion ((XpmFormat * 100 + XpmVersion) * 100 + XpmRevision)

#ifdef FOR_MSW
# define SYSV                   /* uses memcpy string.h etc. */
# include <malloc.h>


/****************************************  from ../h/../h/../xpm/simx.h:  */

/* [file not found] */

/****************************************   end ../h/../h/../xpm/simx.h   */
#define NEED_STRCASECMP         /* at least for MSVC++ */
#else /* FOR_MSW */
#  include <X11/Xlib.h>
#  include <X11/Xutil.h>
#endif /* FOR_MSW */

/* let's define Pixel if it is not done yet */
#if ! defined(_XtIntrinsic_h) && ! defined(PIXEL_T)
typedef unsigned long Pixel;    /* Index into colormap */
# define PIXEL_T
#endif


/* Return ErrorStatus codes:
 * null     if full success
 * positive if partial success
 * negative if failure
 */

#define XpmColorError    1
#define XpmSuccess       0
#define XpmOpenFailed   -1
#define XpmFileInvalid  -2
#define XpmNoMemory     -3
#define XpmColorFailed  -4

typedef struct {
    char *name;                 /* Symbolic color name */
    char *value;                /* Color value */
    Pixel pixel;                /* Color pixel */
}      XpmColorSymbol;

typedef struct {
    char *name;                 /* name of the extension */
    unsigned int nlines;        /* number of lines in this extension */
    char **lines;               /* pointer to the extension array of strings */
}      XpmExtension;

typedef struct {
    char *string;               /* characters string */
    char *symbolic;             /* symbolic name */
    char *m_color;              /* monochrom default */
    char *g4_color;             /* 4 level grayscale default */
    char *g_color;              /* other level grayscale default */
    char *c_color;              /* color default */
}      XpmColor;

typedef struct {
    unsigned int width;         /* image width */
    unsigned int height;        /* image height */
    unsigned int cpp;           /* number of characters per pixel */
    unsigned int ncolors;       /* number of colors */
    XpmColor *colorTable;       /* list of related colors */
    unsigned int *data;         /* image data */
}      XpmImage;

typedef struct {
    unsigned long valuemask;    /* Specifies which attributes are defined */
    char *hints_cmt;            /* Comment of the hints section */
    char *colors_cmt;           /* Comment of the colors section */
    char *pixels_cmt;           /* Comment of the pixels section */
    unsigned int x_hotspot;     /* Returns the x hotspot's coordinate */
    unsigned int y_hotspot;     /* Returns the y hotspot's coordinate */
    unsigned int nextensions;   /* number of extensions */
    XpmExtension *extensions;   /* pointer to array of extensions */
}      XpmInfo;

typedef int (*XpmAllocColorFunc)(
    Display*                    /* display */,
    Colormap                    /* colormap */,
    char*                       /* colorname */,
    XColor*                     /* xcolor */,
    void*                       /* closure */
);

typedef int (*XpmFreeColorsFunc)(
    Display*                    /* display */,
    Colormap                    /* colormap */,
    Pixel*                      /* pixels */,
    int                         /* npixels */,
    void*                       /* closure */
);

typedef struct {
    unsigned long valuemask;            /* Specifies which attributes are
                                           defined */

    Visual *visual;                     /* Specifies the visual to use */
    Colormap colormap;                  /* Specifies the colormap to use */
    unsigned int depth;                 /* Specifies the depth */
    unsigned int width;                 /* Returns the width of the created
                                           pixmap */
    unsigned int height;                /* Returns the height of the created
                                           pixmap */
    unsigned int x_hotspot;             /* Returns the x hotspot's
                                           coordinate */
    unsigned int y_hotspot;             /* Returns the y hotspot's
                                           coordinate */
    unsigned int cpp;                   /* Specifies the number of char per
                                           pixel */
    Pixel *pixels;                      /* List of used color pixels */
    unsigned int npixels;               /* Number of used pixels */
    XpmColorSymbol *colorsymbols;       /* List of color symbols to override */
    unsigned int numsymbols;            /* Number of symbols */
    char *rgb_fname;                    /* RGB text file name */
    unsigned int nextensions;           /* Number of extensions */
    XpmExtension *extensions;           /* List of extensions */

    unsigned int ncolors;               /* Number of colors */
    XpmColor *colorTable;               /* List of colors */
/* 3.2 backward compatibility code */
    char *hints_cmt;                    /* Comment of the hints section */
    char *colors_cmt;                   /* Comment of the colors section */
    char *pixels_cmt;                   /* Comment of the pixels section */
/* end 3.2 bc */
    unsigned int mask_pixel;            /* Color table index of transparent
                                           color */

    /* Color Allocation Directives */
    Bool exactColors;                   /* Only use exact colors for visual */
    unsigned int closeness;             /* Allowable RGB deviation */
    unsigned int red_closeness;         /* Allowable red deviation */
    unsigned int green_closeness;       /* Allowable green deviation */
    unsigned int blue_closeness;        /* Allowable blue deviation */
    int color_key;                      /* Use colors from this color set */

    Pixel *alloc_pixels;                /* Returns the list of alloc'ed color
                                           pixels */
    int nalloc_pixels;                  /* Returns the number of alloc'ed
                                           color pixels */

    Bool alloc_close_colors;            /* Specify whether close colors should
                                           be allocated using XAllocColor
                                           or not */
    int bitmap_format;                  /* Specify the format of 1bit depth
                                           images: ZPixmap or XYBitmap */

    /* Color functions */
    XpmAllocColorFunc alloc_color;      /* Application color allocator */
    XpmFreeColorsFunc free_colors;      /* Application color de-allocator */
    void *color_closure;                /* Application private data to pass to
                                           alloc_color and free_colors */

}      XpmAttributes;

/* XpmAttributes value masks bits */
#define XpmVisual          (1L<<0)
#define XpmColormap        (1L<<1)
#define XpmDepth           (1L<<2)
#define XpmSize            (1L<<3)      /* width & height */
#define XpmHotspot         (1L<<4)      /* x_hotspot & y_hotspot */
#define XpmCharsPerPixel   (1L<<5)
#define XpmColorSymbols    (1L<<6)
#define XpmRgbFilename     (1L<<7)
/* 3.2 backward compatibility code */
#define XpmInfos           (1L<<8)
#define XpmReturnInfos     XpmInfos
/* end 3.2 bc */
#define XpmReturnPixels    (1L<<9)
#define XpmExtensions      (1L<<10)
#define XpmReturnExtensions XpmExtensions

#define XpmExactColors     (1L<<11)
#define XpmCloseness       (1L<<12)
#define XpmRGBCloseness    (1L<<13)
#define XpmColorKey        (1L<<14)

#define XpmColorTable      (1L<<15)
#define XpmReturnColorTable XpmColorTable

#define XpmReturnAllocPixels (1L<<16)
#define XpmAllocCloseColors (1L<<17)
#define XpmBitmapFormat    (1L<<18)

#define XpmAllocColor      (1L<<19)
#define XpmFreeColors      (1L<<20)
#define XpmColorClosure    (1L<<21)


/* XpmInfo value masks bits */
#define XpmComments        XpmInfos
#define XpmReturnComments  XpmComments

/* XpmAttributes mask_pixel value when there is no mask */
#ifndef FOR_MSW
#define XpmUndefPixel 0x80000000
#else
/* int is only 16 bit for MSW */
#define XpmUndefPixel 0x8000
#endif

/*
 * color keys for visual type, they must fit along with the number key of
 * each related element in xpmColorKeys[] defined in XpmI.h
 */
#define XPM_MONO        2
#define XPM_GREY4       3
#define XPM_GRAY4       3
#define XPM_GREY        4
#define XPM_GRAY        4
#define XPM_COLOR       5


/* macros for forward declarations of functions with prototypes */
#if  __STDC__ || defined(__cplusplus) || defined(c_plusplus)
#define FUNC(f, t, p) extern t f p
#define LFUNC(f, t, p) static t f p
#else
#define FUNC(f, t, p) extern t f()
#define LFUNC(f, t, p) static t f()
#endif


/*
 * functions declarations
 */

#ifdef __cplusplus
extern "C" {
#endif

/* FOR_MSW, all ..Pixmap.. are excluded, only the ..XImage.. are used */

#if !defined(FOR_MSW)
    FUNC(XpmCreatePixmapFromData, int, (Display *display,
                                        Drawable d,
                                        char **data,
                                        Pixmap *pixmap_return,
                                        Pixmap *shapemask_return,
                                        XpmAttributes *attributes));

    FUNC(XpmCreateDataFromPixmap, int, (Display *display,
                                        char ***data_return,
                                        Pixmap pixmap,
                                        Pixmap shapemask,
                                        XpmAttributes *attributes));

    FUNC(XpmReadFileToPixmap, int, (Display *display,
                                    Drawable d,
                                    char *filename,
                                    Pixmap *pixmap_return,
                                    Pixmap *shapemask_return,
                                    XpmAttributes *attributes));

    FUNC(XpmWriteFileFromPixmap, int, (Display *display,
                                       char *filename,
                                       Pixmap pixmap,
                                       Pixmap shapemask,
                                       XpmAttributes *attributes));
#endif

    FUNC(XpmCreateImageFromData, int, (Display *display,
                                       char **data,
                                       XImage **image_return,
                                       XImage **shapemask_return,
                                       XpmAttributes *attributes));

    FUNC(XpmCreateDataFromImage, int, (Display *display,
                                       char ***data_return,
                                       XImage *image,
                                       XImage *shapeimage,
                                       XpmAttributes *attributes));

    FUNC(XpmReadFileToImage, int, (Display *display,
                                   char *filename,
                                   XImage **image_return,
                                   XImage **shapeimage_return,
                                   XpmAttributes *attributes));

    FUNC(XpmWriteFileFromImage, int, (Display *display,
                                      char *filename,
                                      XImage *image,
                                      XImage *shapeimage,
                                      XpmAttributes *attributes));

    FUNC(XpmCreateImageFromBuffer, int, (Display *display,
                                         char *buffer,
                                         XImage **image_return,
                                         XImage **shapemask_return,
                                         XpmAttributes *attributes));
#if !defined(FOR_MSW)
    FUNC(XpmCreatePixmapFromBuffer, int, (Display *display,
                                          Drawable d,
                                          char *buffer,
                                          Pixmap *pixmap_return,
                                          Pixmap *shapemask_return,
                                          XpmAttributes *attributes));

    FUNC(XpmCreateBufferFromImage, int, (Display *display,
                                         char **buffer_return,
                                         XImage *image,
                                         XImage *shapeimage,
                                         XpmAttributes *attributes));

    FUNC(XpmCreateBufferFromPixmap, int, (Display *display,
                                          char **buffer_return,
                                          Pixmap pixmap,
                                          Pixmap shapemask,
                                          XpmAttributes *attributes));
#endif
    FUNC(XpmReadFileToBuffer, int, (char *filename, char **buffer_return));
    FUNC(XpmWriteFileFromBuffer, int, (char *filename, char *buffer));

    FUNC(XpmReadFileToData, int, (char *filename, char ***data_return));
    FUNC(XpmWriteFileFromData, int, (char *filename, char **data));

    FUNC(XpmAttributesSize, int, ());
    FUNC(XpmFreeAttributes, void, (XpmAttributes *attributes));
    FUNC(XpmFreeExtensions, void, (XpmExtension *extensions,
                                   int nextensions));

    FUNC(XpmFreeXpmImage, void, (XpmImage *image));
    FUNC(XpmFreeXpmInfo, void, (XpmInfo *info));
    FUNC(XpmGetErrorString, char *, (int errcode));
    FUNC(XpmLibraryVersion, int, ());

    /* XpmImage functions */
    FUNC(XpmReadFileToXpmImage, int, (char *filename,
                                      XpmImage *image,
                                      XpmInfo *info));

    FUNC(XpmWriteFileFromXpmImage, int, (char *filename,
                                         XpmImage *image,
                                         XpmInfo *info));
#if !defined(FOR_MSW)
    FUNC(XpmCreatePixmapFromXpmImage, int, (Display *display,
                                            Drawable d,
                                            XpmImage *image,
                                            Pixmap *pixmap_return,
                                            Pixmap *shapemask_return,
                                            XpmAttributes *attributes));
#endif
    FUNC(XpmCreateImageFromXpmImage, int, (Display *display,
                                           XpmImage *image,
                                           XImage **image_return,
                                           XImage **shapeimage_return,
                                           XpmAttributes *attributes));

    FUNC(XpmCreateXpmImageFromImage, int, (Display *display,
                                           XImage *image,
                                           XImage *shapeimage,
                                           XpmImage *xpmimage,
                                           XpmAttributes *attributes));
#if !defined(FOR_MSW)
    FUNC(XpmCreateXpmImageFromPixmap, int, (Display *display,
                                            Pixmap pixmap,
                                            Pixmap shapemask,
                                            XpmImage *xpmimage,
                                            XpmAttributes *attributes));
#endif
    FUNC(XpmCreateDataFromXpmImage, int, (char ***data_return,
                                          XpmImage *image,
                                          XpmInfo *info));

    FUNC(XpmCreateXpmImageFromData, int, (char **data,
                                          XpmImage *image,
                                          XpmInfo *info));

    FUNC(XpmCreateXpmImageFromBuffer, int, (char *buffer,
                                            XpmImage *image,
                                            XpmInfo *info));

    FUNC(XpmCreateBufferFromXpmImage, int, (char **buffer_return,
                                            XpmImage *image,
                                            XpmInfo *info));

    FUNC(XpmGetParseError, int, (char *filename,
                                 int *linenum_return,
                                 int *charnum_return));

    FUNC(XpmFree, void, (void *ptr));

#ifdef __cplusplus
} /* for C++ V2.0 */
#endif


/* backward compatibility */

/* for version 3.0c */
#define XpmPixmapColorError  XpmColorError
#define XpmPixmapSuccess     XpmSuccess
#define XpmPixmapOpenFailed  XpmOpenFailed
#define XpmPixmapFileInvalid XpmFileInvalid
#define XpmPixmapNoMemory    XpmNoMemory
#define XpmPixmapColorFailed XpmColorFailed

#define XpmReadPixmapFile(dpy, d, file, pix, mask, att) \
    XpmReadFileToPixmap(dpy, d, file, pix, mask, att)
#define XpmWritePixmapFile(dpy, file, pix, mask, att) \
    XpmWriteFileFromPixmap(dpy, file, pix, mask, att)

/* for version 3.0b */
#define PixmapColorError  XpmColorError
#define PixmapSuccess     XpmSuccess
#define PixmapOpenFailed  XpmOpenFailed
#define PixmapFileInvalid XpmFileInvalid
#define PixmapNoMemory    XpmNoMemory
#define PixmapColorFailed XpmColorFailed

#define ColorSymbol XpmColorSymbol

#define XReadPixmapFile(dpy, d, file, pix, mask, att) \
    XpmReadFileToPixmap(dpy, d, file, pix, mask, att)
#define XWritePixmapFile(dpy, file, pix, mask, att) \
    XpmWriteFileFromPixmap(dpy, file, pix, mask, att)
#define XCreatePixmapFromData(dpy, d, data, pix, mask, att) \
    XpmCreatePixmapFromData(dpy, d, data, pix, mask, att)
#define XCreateDataFromPixmap(dpy, data, pix, mask, att) \
    XpmCreateDataFromPixmap(dpy, data, pix, mask, att)

#endif

/****************************************   end ../h/../h/../xpm/xpm.h   */
      #else                             /* HAVE_LIBXPM */
         #include <X11/Xlib.h>
      #endif                            /* HAVE_LIBXPM */

      #include <X11/Xutil.h>
      #include <X11/Xos.h>
      #include <X11/Xatom.h>

      #undef VMS
      #define VMS 0
   #endif                               /* VMS */

#endif                                  /* XWindows */

/*
 * Include this after Xlib stuff, jmorecfg.h expects this.
 */
#if HAVE_LIBJPEG && defined(Graphics)

#if defined(XWindows)
/* Some AMD64 Gentoo systems seem to have a buggy macros in
   jmorecfg.h, but if we include Xmd.h beforehand then we get better
   definitions of the macros. */
#include <X11/Xmd.h>
#endif

#ifdef NTGCC
/* avoid INT32 compile error in jmorecfg.h by pretending we used Xmd.h! */
#define XMD_H

/* avoid warnings over duplicate definition of HAVE_STDLIB_H in jpeglib.h */
#undef HAVE_STDLIB_H
#endif                                  /* NTGCC */



/****************************************  from ../h/../h/jpeglib.h:  */

/* [file not found] */

/****************************************   end ../h/../h/jpeglib.h   */


/****************************************  from ../h/../h/jerror.h:  */

/* [file not found] */

/****************************************   end ../h/../h/jerror.h   */
#ifndef HAVE_LIBPNG
#include <setjmp.h>
#endif                                  /* HAVE_LIBPNG */
/* we do not use their definitions of GLOBAL, LOCAL, or OF; we use our own */
#ifdef NTGCC
#undef boolean
#endif                                  /* NTGCC */
#undef GLOBAL
#undef LOCAL
#undef OF
#endif                                  /* HAVE_LIBJPEG */

#define VanquishReturn(s) return s;

/*
 * Feature-dependent includes.
 */
#ifndef HostStr
   #if !VMS && !Windows
      #include <sys/utsname.h>
   #endif                               /* !VMS && !Windows*/
#endif                                  /* HostStr */

#ifdef LoadFunc
#if NT
   void *dlopen(char *, int); /* LoadLibrary */
   void *dlsym(void *, char *sym); /* GetProcAddress */
   int dlclose(void *); /* FreeLibrary */
#else                                   /* NT */
   #include <dlfcn.h>
#endif                                  /* NT */
#endif                                  /* LoadFunc */



/****************************************  from ../h/../h/../h/filepat.h:  */

#ifndef FILEPAT_H
#define FILEPAT_H
/*
 * Typedefs and macros for filename wildcard expansion on some systems.
 *  The definitions provided here are:
 *
 *    typedef ... FINDFILE_T;
 *    // Current state of the filename wildcard expansion
 *
 *    int FINDFIRST ( char *pattern, FINDFILE_T *pfd );
 *    // Initializes *pfd and returns 1 if a file is found that matches the
 *    // pattern, 0 otherwise
 *
 *    int FINDNEXT ( FINDFILE_T *pfd );
 *    // Assuming that the last FINDFIRST/FINDNEXT call was successful,
 *    // updates *pfd and returns whether another match can be made.
 *
 *    char *FILENAME ( FINDFILE_T *pfd );
 *    // Assuming that the last FINDFIRST/FINDNEXT call was successful,
 *    // returns pointer to last found file name.
 *
 *    void FINDCLOSE ( FINDFILE_T *pfd );
 *    // Does any cleanup required after doing filenaame wildcard expansion.
 *
 * Also, the macro WildCards will be defined to be 1 if there is file
 * pattern matching is supported, 0 otherwise.  If !WildCards, then a
 * default set of typedef/macros will be provided that will return only one
 * match, the original pattern.
 */


#if WildCards

#if NT

#include <io.h>

typedef struct _FINDFILE_TAG {
   intptr_t             handle;
   struct _finddata_t   fileinfo;
   } FINDDATA_T;

#define FINDFIRST(pattern, pfd) \
   ( ( (pfd)->handle = _findfirst ( (pattern), &(pfd)->fileinfo ) ) != -1L )
#define FINDNEXT(pfd) ( _findnext ( (pfd)->handle, &(pfd)->fileinfo ) != -1 )
#define FILENAME(pfd)   ( (pfd)->fileinfo.name )
#define FINDCLOSE(pfd)  _findclose( (pfd)->handle )

#endif                                  /* NT */

#if MICROSOFT

#include <dos.h>

typedef struct _find_t FINDDATA_T;

#define FINDFIRST(pattern, pfd) (!_dos_findfirst ((pattern), _A_NORMAL, (pfd)))
#define FINDNEXT(pfd)   ( !_dos_findnext ( (pfd) ) )
#define FILENAME(pfd)   ( (pfd)->name )
#define FINDCLOSE(pfd)  ( (void) 0 )

#endif                                  /* MICROSOFT */

#if PORT
Deliberate Syntax Error                 /* Give it some thought */
#endif                                  /* PORT */
#else                                   /* WildCards */
typedef struct _NotWild { char *name; } FINDDATA_T;
#define FINDFIRST(pattern, pfd) ((pfd)->name = (pattern))
#define FINDNEXT(pfd)   ( 0 )
#define FILENAME(pfd)   ( (pfd)->name )
#define FINDCLOSE(pfd)  ( (void) 0 )

#endif                                  /* WildCards */
#endif

/****************************************   end ../h/../h/../h/filepat.h   */

#ifdef Dbm
#include <ndbm.h>
#endif                                  /* Dbm */

#ifdef ISQL
#ifndef BOOL
  /* to prevent double-typedef of BOOL on some platforms */
#ifdef MacOS
//#define BOOL rumplemacskin
#else
  #define BOOL int
#endif
#endif
  #include <sqlext.h>
#undef BOOL

#ifdef DebugHeap
#define Type(d)         (int)((((d).dword & F_Typecode) ? ((int)((d).dword & TypeMask)) : (heaperr("descriptor type error",BlkLoc(d),(d).dword), -1)))
#else
#define Type(d) (int)((d).dword & TypeMask)
#endif
  #define Precision 16

#endif                                  /* ISQL */

#ifdef Messaging
# include <tp.h>
#endif                                  /* Messaging */

#ifdef ConsoleWindow
#undef putc
#define putc Consoleputc
#endif                                  /* ConsoleWindow */

#if HAVE_LIBGL
#include <GL/gl.h>
#ifdef XWindows
#include <GL/glx.h>
#endif                                  /* XWindows */
#include <GL/glu.h>
#if HAVE_LIBFREETYPE
   #include <ft2build.h>
   #include FT_FREETYPE_H
   #define PNG_SKIP_SETJMP_CHECK        /*
                                         * Fixes compile error for Ubuntu 16.04:
                                         * 'expected [...] before __pngconf.h in
                                         * libpng already includes setjmp.h'
                                         */
#endif                                  /* HAVE_LIBFREETYPE */
#endif                                  /* HAVE_LIBGL */

#if HAVE_LIBZ
#  ifdef STDC
#    define OF(args)  args
#  else
#    define OF(args)  ()
#  endif

#if !VMS
#undef VMS
#endif

/*
 * On many platforms png.h includes zlib.h and including it again is an error
 * for a redefined type.  On many other platforms png.h does not include zlib.h
 * and this code needs to.  Apparently, this not including of zlib.h in png.h
 * occurs for libpng 1.5 and higher.
 */
#if HAVE_LIBPNG && defined(Graphics)
#include <png.h>
#if defined(NTGCC) || (defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10500))
#include <zlib.h>
#endif

#else                                   /* HAVE_LIBPNG */

#include <zlib.h>
#endif                                  /* HAVE_LIBPNG */

#ifndef VMS
#define VMS 0
#endif

#else                                   /* HAVE_LIBZ */

/* If you claim to have libpng, but you don't have libz, that's no good */
#if HAVE_LIBPNG
/*#include <png.h>*/
#endif                                  /* HAVE_LIBPNG */
#endif                                  /* HAVE_LIBZ */

#ifdef HAVE_VOICE


/****************************************  from ../h/../h/../lib/voice/jvoip.h:  */


struct VOIPSession;
typedef struct VOIPSession VSESSION;
typedef struct VOIPSession* PVSESSION;

#ifdef WIN32
        int StartupWinSocket(void);
        int CleanupWinSocket(void);
#endif

char * FetchListener(PVSESSION VSession, int pos);
char * FetchName(PVSESSION VSession, int pos);
char * FetchAddress(PVSESSION VSession, int pos);
int GetVListSize(PVSESSION VSession);

PVSESSION CreateVoiceSession(char SessionPort[5] , char Destinations[] );
void SetVoiceAttrib(PVSESSION VSession, char StrAttrib[]);
void CloseVoiceSession(PVSESSION VSession);



/****************************************   end ../h/../h/../lib/voice/jvoip.h   */
#endif                                  /* HAVE_VOICE */

#ifdef HAVE_LIBOPENAL
#if HAVE_ALTYPES
        #include <AL/altypes.h>
        #include <AL/alexttypes.h>
#endif                                  /* HAVE_ALTYPES */
        #include <AL/al.h>
        #include <AL/alc.h>
        #include <AL/alext.h>
/*
 * 10/2008: alut.h is a legacy header. Putting this in to see what breaks.
 */
#if HAVE_ALUT
        #include <AL/alut.h>
#endif
#endif                                  /* HAVE_LIBOPENAL */

/* Ogg Vorbis */
#ifdef HAVE_LIBOGG
        #include <vorbis/codec.h>
        #include <vorbis/vorbisfile.h>
#endif                                  /* HAVE_LIBOGG */

/* OpenCL */
#ifdef HAVE_LIBCL
        #include <CL/cl.h>
#endif                                  /* HAVE_LIBCL */

#ifdef HAVE_LIBSSL
/* openssl thinks we are a VMS system when VMS=0 */
#if !VMS
#undef VMS
#endif

#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/opensslv.h>

#ifndef VMS
#define VMS 0
#endif


#endif                                  /* HAVE_LIBSSL */

/* On some systems we get a definition of offsetof() and on some we don't.
 * Include stddef.h just in case: guards within stddef.h should prevent double inclusion.
 */
#include <stddef.h>

/****************************************   end ../h/../h/sys.h   */


/****************************************  from ../h/../h/typedefs.h:  */

/*
 * typdefs for the run-time system.
 */

typedef int ALIGN;              /* pick most stringent type for alignment */
typedef unsigned int DIGIT;

/*
 * Default sizing and such.
 */

/*
 * Establish typedefs for word and uword.
 * intptr_t cannot be used because it is defined in stdint.h (rtt does not
 * process system include files) so establish the size explicitly using the
 * definitions in auto.h planted by the configure script..
 */
#if (SIZEOF_INT == SIZEOF_INT_P)
   typedef int word;
   typedef unsigned int uword;
#elif (SIZEOF_LONG_INT == SIZEOF_INT_P)
   typedef long int word;
   typedef unsigned long int uword;
#elif defined(SIZEOF_LONG_LONG_INT) && (SIZEOF_LONG_LONG_INT == SIZEOF_INT_P)
   typedef long long int word;
   typedef unsigned long long int uword;
#else
   #error Cannot determine suitable typedefs for word and uword
#endif

   typedef void *pointer;
   typedef AllocType msize;

/*
 * Typedefs to make some things easier.
 */

typedef int (*fptr)();
typedef struct descrip *dptr;

typedef word C_integer;

/*
 * A success continuation is referenced by a pointer to an integer function
 *  that takes no arguments.
 */
typedef int (*continuation) (void);

#ifdef PthreadCoswitch
/*
 * Treat an Icon "cstate" array as an array of context pointers.
 * cstate[0] is used by Icon code that thinks it's setting a stack pointer.
 * We use cstate[1] to point to the actual context struct.
 * (Both of these are initialized to NULL by Icon 9.4.1 or later.)
 */
//typedef struct context **cstate;
#endif                                  /* PthreadCoswitch */

#if !COMPILER

   /*
    * Typedefs for the interpreter.
    */

   /*
    * Icode consists of operators and arguments.  Operators are small integers,
    *  while arguments may be pointers.  To conserve space in icode files on
    *  computers with 16-bit ints, icode is written by the linker as a mixture
    *  of ints and words (longs).  When an icode file is read in and processed
    *  by the interpreter, it looks like a C array of mixed ints and words.
    *  Accessing this "nonstandard" structure is handled by a union of int and
    *  word pointers and incrementing is done by incrementing the appropriate
    *  member of the union (see the interpreter).  This is a rather dubious
    *  method and certainly not portable.  A better way might be to address
    *  icode with a char *, but the incrementing code might be inefficient
    *  (at a place that experiences a lot of execution activity).
    *
    * For the moment, the dubious coding is isolated under control of the
    *  size of integers.
    */

   #if IntBits != WordBits

      typedef union {
         int *op;
         word *opnd;
         } inst;

      #else                             /* IntBits != WordBits */

      typedef union {
         word *op;
         word *opnd;
         } inst;

   #endif                               /* IntBits != WordBits */

#endif                                  /* COMPILER */

typedef enum TRuntime_Status_states {
  RTSTATUS_NORMAL=0,    /* Normal operation       */
  RTSTATUS_GC,          /* Garbage collection     */
  RTSTATUS_SIGNAL,      /* Normal Signal Handling */
  RTSTATUS_EXIT,        /* Normal Shutdown        */
  RTSTATUS_RUNERROR,    /* Runtime Error shutdown */
  RTSTATUS_SYSERROR,    /* System Error shutdown  */
  RTSTATUS_HARDERROR    /* Hardware Error shutdown, triggered by signals
                           SIGBUS, SIGFPE, SIGILL, and SIGSEGV */
  } TRuntime_Status;

/****************************************   end ../h/../h/typedefs.h   */


/****************************************  from ../h/../h/cstructs.h:  */

/*
 * cstructs.h - structures and accompanying manifest constants for functions
 *  in the common subdirectory.
 */

/*
 * fileparts holds a file name broken down into parts.
 */
struct fileparts {                      /* struct of file name parts */
   char *dir;                           /* directory */
   char *name;                          /* name */
   char *ext;                           /* extension */

#if VMS
   char *version;
#endif                                  /* VMS */

#if MVS
   char *member;
#endif                                  /* MVS */

   };

/*
 * xval - holds references to literal constants
 */
union xval {
   word ival;           /* integer */
   double rval;         /*  real */
   word sval;           /*  offset into string space of string */
   };

/*
 * str_buf references a string buffer. Strings are built a character
 *  at a time. When a buffer "fragment" is filled, another is allocated
 *  and the the current string copied to it.
 */
struct str_buf_frag {
   struct str_buf_frag *next;     /* next buffer fragment */
   char s[1];                     /* variable size buffer, really > 1 */
   };

struct str_buf {
   unsigned int size;             /* total size of current buffer */
   char *strtimage;               /* start of string currently being built */
   char *endimage;                /* next free character in buffer */
   char *end;                     /* end of current buffer */
   struct str_buf_frag *frag_lst; /* list of buffer fragments */
   struct str_buf *next;          /* buffers can be put on free list */
   };

#define AppChar(sbuf, c) do {\
   if ((sbuf).endimage >= (sbuf).end)\
      new_sbuf(&(sbuf));\
   *((sbuf).endimage)++ = (c); } while (0)

/*
 * implement contains information about the implementation of an operation.
 */
#define NoRsltSeq  -1L       /* no result sequence: {} */
#define UnbndSeq   -2L       /* unbounded result sequence: {*} */

#define DoesRet    01        /* operation (or "body" function) returns */
#define DoesFail   02        /* operation (or "body" function) fails */
#define DoesSusp   04        /* operation (or "body" function) suspends */
#define DoesEFail 010        /* fails through error conversion */
#define DoesFThru 020        /* only "body" functions can "fall through" */

struct implement {
   struct implement *blink;   /* link for bucket chain in hash tables */
   char oper_typ;             /* 'K'=keyword, 'F'=function, 'O'=operator */
   char prefix[2];            /* prefix to make start of name unique */
   char *name;                /* function/operator/keyword name */
   char *op;                  /* operator symbol (operators only) */
   int nargs;                 /* number of arguments operation requires */
   int *arg_flgs;             /* array of arg flags: deref/underef, var len*/
   long min_result;           /* minimum result sequence length */
   long max_result;           /* maiximum result sequence length */
   int resume;                /* flag - resumption after last result */
   int ret_flag;              /* DoesRet, DoesFail, DoesSusp */
   int use_rslt;              /* flag - explicitly uses result location */
   char *comment;             /* description of operation */
   int ntnds;                 /* size of tnds array */
   struct tend_var *tnds;     /* pointer to array of info about tended vars */
   int nvars;                 /* size of vars array */
   struct ord_var  *vars;     /* pointer to array of info about ordinary vars */
   struct il_code *in_line;    /* inline version of the operation */
   int iconc_flgs;            /* flags for internal use by the compiler */
   };

/*
 * These codes are shared between the data base and rtt. They are defined
 *  here, though not all are used by the data base.
 */
#define TndDesc   1  /* a tended descriptor */
#define TndStr    2  /* a tended character pointer */
#define TndBlk    3  /* a tended block pointer */
#define OtherDcl  4  /* a declaration that is not special */
#define IsTypedef 5  /* a typedef */
#define VArgLen   6  /* identifier for length of variable parm list */
#define RsltLoc   7  /* the special result location of an operation */
#define Label     8  /* label */
#define RtParm   16  /* undereferenced parameter of run-time routine */
#define DrfPrm   32  /* dereferenced parameter of run-time routine */
#define VarPrm   64  /* variable part of parm list (with RtParm or DrfPrm) */
#define PrmMark 128  /* flag - used while recognizing params of body fnc */
#define ByRef   256  /* flag - parameter to body function passed by reference */

/*
 * Flags to indicate what types are returned from the function implementing
 *  a body. These are unsed in determining the calling conventions
 *  of the function.
 */
#define RetInt   1  /* body/function returns a C_integer */
#define RetDbl   2  /* body/function returns a C_double */
#define RetOther 4  /* body (not function itself) returns something else */
#define RetNoVal 8  /* function returns no value */
#define RetSig  16  /* function returns a signal */

/*
 * tend_var contains information about a tended variable in the "declare {...}"
 *  action of an operation.
 */
struct tend_var {
   int var_type;           /* TndDesc, TndStr, or TndBlk */
   struct il_c *init;      /* initial value from declaration */
   char *blk_name;         /* TndBlk: struct name of block */
   };

/*
 * ord_var contains information about an ordinary variable in the
 *  "declare {...}" action of an operation.
 */
struct ord_var {
   char *name;        /* name of variable */
   struct il_c *dcl;  /* declaration of variable (includes name) */
   };

/*
 * il_code has information about an action in an operation.
 */
#define IL_If1     1
#define IL_If2     2
#define IL_Tcase1  3
#define IL_Tcase2  4
#define IL_Lcase   5
#define IL_Err1    6
#define IL_Err2    7
#define IL_Lst     8
#define IL_Const   9
#define IL_Bang   10
#define IL_And    11
#define IL_Cnv1   12
#define IL_Cnv2   13
#define IL_Def1   14
#define IL_Def2   15
#define IL_Is     16
#define IL_Var    17
#define IL_Subscr 18
#define IL_Block  19
#define IL_Call   20
#define IL_Abstr  21
#define IL_VarTyp 22
#define IL_Store  23
#define IL_Compnt 24
#define IL_TpAsgn 25
#define IL_Union  26
#define IL_Inter  27
#define IL_New    28
#define IL_IcnTyp 29
#define IL_Acase  30

#define CM_Fields -1

union il_fld {
   struct il_code *fld;
   struct il_c *c_cd;
   int *vect;
   char *s;
   word n;
   };

struct il_code {
   int il_type;
   union il_fld u[1];   /* actual number of fields varies with type */
   };

/*
 * The following manifest constants are used to describe types, conversions,
 *   and returned values. Non-negative numbers are reserved for types described
 *   in the type specification system.
 */
#define TypAny    -1
#define TypEmpty  -2
#define TypVar    -3
#define TypCInt   -4
#define TypCDbl   -5
#define TypCStr   -6
#define TypEInt   -7
#define TypECInt  -8
#define TypTStr   -9
#define TypTCset -10
#define RetDesc  -11
#define RetNVar  -12
#define RetSVar  -13
#define RetNone  -14

/*
 * il_c describes a piece of C code.
 */
#define ILC_Ref    1   /* nonmodifying reference to var. in sym. tab. */
#define ILC_Mod    2   /* modifying reference to var. in sym. tab */
#define ILC_Tend   3   /* tended var. local to inline block */
#define ILC_SBuf   4   /* string buffer */
#define ILC_CBuf   5   /* cset buffer */
#define ILC_Ret    6   /* return statement */
#define ILC_Susp   7   /* suspend statement */
#define ILC_Fail   8   /* fail statement */
#define ILC_Goto   9   /* goto */
#define ILC_CGto  10   /* conditional goto */
#define ILC_Lbl   11   /* label */
#define ILC_LBrc  12   /* '{' */
#define ILC_RBrc  13   /* '}' */
#define ILC_Str   14   /* arbitrary string of code */
#define ILC_EFail 15   /* errorfail statement */

#define RsltIndx -1   /* symbol table index for "result" */

struct il_c {
   int il_c_type;
   struct il_c *code[3];
   word n;
   char *s;
   struct il_c *next;
   };

/*
 * The parameter value of a run-time operation may be in one of several
 *  different locations depending on what conversions have been done to it.
 *  These codes are shared by rtt and iconc.
 */
#define PrmTend    1   /* in tended location */
#define PrmCStr    3   /* converted to C string: tended location */
#define PrmInt     4   /* converted to C int: non-tended location */
#define PrmDbl     8   /* converted to C double: non-tended location */

/*
 * Kind of RLT return statement supported.
 */
#define TRetNone  0   /* does not support an RTL return statement */
#define TRetBlkP  1   /* block pointer */
#define TRetDescP 2   /* descriptor pointer */
#define TRetCharP 3   /* character pointer */
#define TRetCInt  4   /* C integer */
#define TRetSpcl  5   /* RLT return statement has special form & semenatics */

/*
 * Codes for dereferencing needs.
 */
#define DrfNone  0  /* not a variable type */
#define DrfGlbl  1  /* treat as a global variable */
#define DrfCnst  2  /* type of values in variable doesn't change */
#define DrfSpcl  3  /* special dereferencing: trapped variable */

/*
 * Information about an Icon type.
 */
struct icon_type {
   char *id;            /* name of type */
   int support_new;     /* supports RTL "new" construct */
   int deref;           /* dereferencing needs */
   int rtl_ret;         /* kind of RTL return supported if any */
   char *typ;           /* for variable: initial type */
   int num_comps;       /* for aggregate: number of type components */
   int compnts;         /* for aggregate: index of first component */
   char *abrv;          /* abreviation used for type tracing */
   char *cap_id;        /* name of type with first character capitalized */
   };

/*
 * Information about a component of an aggregate type.
 */
struct typ_compnt {
   char *id;            /* name of component */
   int n;               /* position of component within type aggragate */
   int var;             /* flag: this component is an Icon-level variable */
   int aggregate;       /* index of type that owns the component */
   char *abrv;          /* abreviation used for type tracing */
   };

extern int num_typs;                 /* number of types in table */
extern struct icon_type icontypes[]; /* table of icon types */

/*
 * Type inference needs to know where most of the standard types
 *  reside. Some have special uses outside operations written in
 *  RTL code, such as the null type for initializing variables, and
 *  others have special semantics, such as trapped variables.
 */
extern int str_typ;                  /* index of string type */
extern int int_typ;                  /* index of integer type */
extern int rec_typ;                  /* index of record type */
extern int proc_typ;                 /* index of procedure type */
extern int coexp_typ;                /* index of co-expression type */
extern int stv_typ;                  /* index of sub-string trapped var type */
extern int ttv_typ;                  /* index of table-elem trapped var type */
extern int null_typ;                 /* index of null type */
extern int cset_typ;                 /* index of cset type */
extern int real_typ;                 /* index of real type */
extern int list_typ;                 /* index of list type */
extern int tbl_typ;                  /* index of table type */

extern int num_cmpnts;                 /* number of aggregate components */
extern struct typ_compnt typecompnt[]; /* table of aggregate components */
extern int str_var;                    /* index of trapped string variable */
extern int trpd_tbl;                   /* index of trapped table */
extern int lst_elem;                   /* index of list element */
extern int tbl_val;                    /* index of table element value */
extern int tbl_dflt;                   /* index of table default */

/*
 * minimum number of unsigned ints needed to hold the bits of a cset - only
 *  used in translators, not in the run-time system.
 */
#define BVectSize 16

/****************************************   end ../h/../h/cstructs.h   */


/****************************************  from ../h/../h/proto.h:  */

/*
 * proto.h -- prototypes for library functions.
 */

/*
 * The following code is operating-system dependent. [@proto.01].
 *  Prototypes for library functions.
 */

#if PORT
   Deliberate Syntax Error
#endif                                  /* PORT */

#if MSDOS
   #if MICROSOFT || TURBO || NT
      #include <dos.h>
   #endif                               /* MICROSOFT || TURBO ... */
#endif                                  /* MSDOS */

/*
 * End of operating-system specific code.
 */



/****************************************  from ../h/../h/../h/mproto.h:  */

/*
 * mproto.h -- prototypes for functions common to several modules.
 */

pointer alloc           (unsigned int n);
unsigned short *bitvect (char *image, int len);
void    clear_sbuf      (struct str_buf *sbuf);
int     cmp_pre         (char *pre1, char *pre2);
void    cset_init       (FILE *f, unsigned short *bv);
void    db_chstr        (char *s1, char *s2);
void    db_close        (void);
void    db_code         (struct implement *ip);
void    db_dscrd        (struct implement *ip);
void    db_err1         (int fatal, char *s1);
void    db_err2         (int fatal, char *s1, char *s2);
struct implement *db_ilkup (char *id, struct implement **tbl);
struct implement *db_impl  (int oper_typ);
int     db_open         (char *s, char **lrgintflg);
char    *db_string      (void);
int     db_tbl          (char *section, struct implement **tbl);
char *findonpath(char *name, char *buf, size_t len);
struct fileparts *fparse(char *s);
void    free_stbl       (void);
void    id_comment      (FILE *f);
void    init_sbuf       (struct str_buf *sbuf);
void    init_str        (void);
long    longwrite       (char *s,long len,FILE *file);
char    *makename       (char *dest,char *d,char *name,char *e);
long    millisec        (void);
struct il_code *new_il  (int il_type, int size);
void    new_sbuf        (struct str_buf *sbuf);
void    nxt_pre         (char *pre, char *nxt, int n);
char    *pathfind       (char *buf, char *path, char *name, char *extn);
int     ppch            (void);
void    ppdef           (char *name, char *value);
void    ppecho          (void);
int     ppinit          (char *fname, char *inclpath, int m4flag);
int     prt_i_str       (FILE *f, char *s, int len);
int     redirerr        (char *p);
char    *salloc         (char *s);
int     smatch          (char *s,char *t);
char    *spec_str       (char *s);
char    *str_install    (struct str_buf *sbuf);
int     tonum           (int c);
void    lear_sbuf       (struct str_buf *sbuf);

#ifdef ConsoleWindow
   int Consolefprintf(FILE *file, const char *format, ...);
   int Consoleprintf(const char *format, ...);
   int Consoleputc(int c, FILE *file);
   int Consolefflush(FILE *file);
#endif                                  /* ConsoleWindow */

#ifndef SysOpt
   int  getopt          (int argc, char * const argv[], const char *optstring);
#endif                                  /* NoSysOpt */

#if IntBits == 16
   long lstrlen         (char *s);
   void lqsort          (char *base, int nel, int width, int (*cmp)());
#endif                                  /* IntBits == 16 */

#define NewStruct(type)\
   (struct type *)alloc((unsigned int) sizeof (struct type))

char *relfile   (char *prog, char *mod);
#if UNIX
   FILE *pathOpen       (char *fname, char*mode);
#endif

#if NT
int unicon_win32_cmdline_to_argv(char *s, char ***avp, int dequote);
void unicon_win32_argv_free(int argc, char **argv);
#endif                                  /* NT */

/****************************************   end ../h/../h/../h/mproto.h   */

/*
 * These must be after prototypes to avoid clash with system
 * prototypes.
 */

#if IntBits == 16
   #define sbrk lsbrk
   #define strlen lstrlen
   #define qsort lqsort
#endif                                  /* IntBits == 16 */

/****************************************   end ../h/../h/proto.h   */


/****************************************  from ../h/../h/cpuconf.h:  */

/*
 *  Configuration parameters that depend on computer architecture.
 *  Some depend on values defined in config.h, which is always
 *  included before this file.
 */

#ifndef CStateSize
   #define CStateSize 15                /* size of C state for co-expressions */
#endif                                  /* CStateSize */

/*
 * The following definitions depend on the sizes of ints and pointers.
 */

/*
 * Most of the present implementations use 64-bit "words".  Note that
 *  WordBits is the number of bits in an Icon integer, not necessarily
 *  the number of bits in an int (given by IntBits).  For example,
 *  in MS-DOS an Icon integer is a long, not an int.
 *
 *  MaxStrLen must not be so large as to overlap flags.
 */

/*
 * 64-bit words.
 */

#if WordBits == 64

   #ifndef MinLong
      #define MinLong  ((word)0x8000000000000000) /* smallest long int */
   #endif

   #ifndef MaxLong
      #define MaxLong  ((word)0x7fffffffffffffff) /* largest long integer */
   #endif

   #define MaxStrLen 037777777777777777777L     /* maximum string length */

   #ifndef MaxNegInt
      #define MaxNegInt "-9223372036854775808"
   #endif

   #ifndef F_Nqual
      #define F_Nqual 0x8000000000000000        /* set if NOT string qualifier*/
   #endif                               /* F_Nqual */

   #ifndef F_Var
      #define F_Var     0x4000000000000000      /* set if variable */
   #endif                               /* F_Var */

   #ifndef F_Ptr
      #define F_Ptr     0x1000000000000000      /* set if value field is ptr */
   #endif                               /* F_Ptr */

   #ifndef F_Typecode
      #define F_Typecode  0x2000000000000000    /* set if dword incls typecode*/
   #endif                               /* F_Typecode */

#endif                                  /* WordBits == 64 */

/*
 * 32-bit words.
 */

#if WordBits == 32

   #define MaxLong  ((long int)017777777777L)   /* largest long integer */
   #define MinLong  ((long int)020000000000L)   /* smallest long integer */

   #define MaxNegInt "-2147483648"

   #define MaxStrLen 0777777777         /* maximum string length */

   #define F_Nqual      0x80000000      /* set if NOT string qualifier */
   #define F_Var        0x40000000      /* set if variable */
   #define F_Ptr        0x10000000      /* set if value field is pointer */
   #define F_Typecode   0x20000000      /* set if dword includes type code */

#endif                                  /* WordBits == 32 */

/*
 * Values that depend on the number of bits in an int (not necessarily
 * the same as the number of bits in a word).
 */

#if IntBits == 64
   #define LogIntBits   6                       /* log of IntBits */
   #define MaxUnsigned 01777777777777777777777L /* largest unsigned integer */
   #define MaxInt       0777777777777777777777L /* largest int */
   /*
    * Cset initialization and access macros.
    */
   #define fwd(w0, w1, w2, w3) \
    (((w0)&0xffff) | (((unsigned)(w1)&0xffff)<<16) | \
    (((unsigned)(w2)&0xffff)<<32) | (((unsigned)(w3)&0xffff)<<48))
   #define cset_display(w0,w1,w2,w3,w4,w5,w6,w7,w8,w9,wa,wb,wc,wd,we,wf) \
    {fwd(w0,w1,w2,w3),fwd(w4,w5,w6,w7),fwd(w8,w9,wa,wb),fwd(wc,wd,we,wf)}
   #define Cset32(b,c) (*CsetPtr(b,c)>>(32*CsetOff((b)>>5)))  /* 32b of cset */
#endif                                  /* IntBits == 64 */

#if IntBits == 32
   #define LogIntBits   5               /* log of IntBits */
   #define MaxUnsigned  037777777777    /* largest unsigned integer */
   #define MaxInt       017777777777    /* largest int */
   /*
    * Cset initialization and access macros.
    */
   #define twd(w0,w1)   (((w0)&0xffff) | (((unsigned)w1)<<16))
   #define cset_display(w0,w1,w2,w3,w4,w5,w6,w7,w8,w9,wa,wb,wc,wd,we,wf) \
      {twd(w0,w1),twd(w2,w3),twd(w4,w5),twd(w6,w7), \
       twd(w8,w9),twd(wa,wb),twd(wc,wd),twd(we,wf)}
   #define Cset32(b,c) (*CsetPtr(b,c))  /* 32 bits of cset */
#endif                                  /* IntBits == 32 */

#if IntBits == 16
   #define LogIntBits   4                       /* log of IntBits */
   #define MaxUnsigned ((unsigned int)0177777)  /* largest unsigned integer */
   #define MaxInt       077777                  /* largest int */

   #ifndef MaxListSlots
      #define MaxListSlots 8000         /* largest list-element block */
   #endif                               /* MaxListSlots */

   /*
    * Cset initialization and access macros.
    */
   #define cset_display(w0,w1,w2,w3,w4,w5,w6,w7,w8,w9,wa,wb,wc,wd,we,wf) \
      {w0,w1,w2,w3,w4,w5,w6,w7,w8,w9,wa,wb,wc,wd,we,wf}
   #define Cset32(b,c) (((unsigned long)(unsigned int)(*CsetPtr((b)+16,c))<<16) | \
      ((unsigned long)(unsigned int)(*CsetPtr(b,c))))  /* 32 bits of cset */
#endif                                  /* IntBits == 16 */

#ifndef LogHuge
   #define LogHuge 309                  /* maximum base-10 exp+1 of real */
#endif                                  /* LogHuge */

#ifndef Big
   #define Big 9007199254740992.        /* larger than 2^53 lose precision */
#endif                                  /* Big */

#ifndef Precision
   #define Precision 16                 /* digits in string from real */
#endif                                  /* Precision */

/*
 * Parameters that configure tables and sets:
 *
 *  HSlots      Initial number of hash buckets; must be a power of 2.
 *  LogHSlots   Log to the base 2 of HSlots.
 *
 *  HSegs       Maximum number of hash bin segments; the maximum number of
 *              hash bins is HSlots * 2 ^ (HSegs - 1).
 *
 *              If Hsegs is increased above 12, the arrays log2h[] and segsize[]
 *              in the runtime system will need modification.
 *
 *  MaxHLoad    Maximum loading factor; more hash bins are allocated when
 *              the average bin exceeds this many entries.
 *
 *  MinHLoad    Minimum loading factor; if a newly created table (e.g. via
 *              copy()) is more lightly loaded than this, bins are combined.
 *
 *  Because splitting doubles the number of hash bins, and combining halves it,
 *  MaxHLoad should be at least twice MinHLoad.
 */

#ifndef HSlots
      #define HSlots     16
      #define LogHSlots  4
#endif                                  /* HSlots */

#if ((1 << LogHSlots) != HSlots)
   Deliberate Syntax Error -- HSlots and LogHSlots are inconsistent
#endif                                  /* HSlots / LogHSlots consistency */

#ifndef HSegs
      #define HSegs      18
#endif                                  /* HSegs */

#ifndef MinHLoad
   #define MinHLoad  1
#endif                                  /* MinHLoad */

#ifndef MaxHLoad
   #define MaxHLoad  5
#endif                                  /* MaxHLoad */

/*
 * The number of bits in each base-B digit; the type DIGIT (unsigned int)
 *  in rt.h must be large enough to hold this many bits.
 *  It must be at least 2 and at most WordBits / 2.
 */
#define NB           (WordBits / 2)

/*
 * The number of decimal digits at which the image lf a large integer
 * goes from exact to approximate (to avoid possible long delays in
 * conversion from large integer to string because of its quadratic
 * complexity).
 */
#define MaxDigits       30

/*
 * Memory sizing.
 */

/*
 * # of co-expressions to allocate before garbage collecting (to cleanup co-expressions)
 * Possibly should be based on physical memory size.
 */
#ifndef AlcMax
   #define AlcMax 250
#endif                                  /* AlcMax */

/*
 * Maximum sized block that can be allocated (via malloc() or such).
 */
#ifndef MaxBlock
   #if IntBits == 16
      #define MaxBlock 65000            /* leaves room for malloc header */
   #else                                /* IntBits == 16 */
      #define MaxBlock MaxUnsigned
   #endif                               /* IntBits == 16 */
#endif                                  /* MaxBlock */

/*
 * What follows is default memory sizing. Implementations with special
 *  requirements may specify these values in define.h.
 */

#ifndef MaxStrSpace
   #if IntBits == 16
      #define MaxStrSpace 65000         /* size of the string space in bytes */
   #else                                /* IntBits == 16 */
      #define MaxStrSpace 500000        /* size of the string space in bytes */
   #endif                               /* IntBits == 16 */
#endif                                  /* MaxStrSpace */

#ifndef MaxAbrSize
   #if IntBits == 16
      #define MaxAbrSize 65000          /* size of the block region in bytes */
   #else                                /* IntBits == 16 */
      #define MaxAbrSize 500000         /* size of the block region in bytes */
   #endif                               /* IntBits == 16 */
#endif                                  /* MaxAbrSize */

#ifndef MStackSize
      #define MStackSize 50000          /* size of the main stack in words */
#endif                                  /* MStackSize */

#ifndef StackSize
   #define StackSize    2000            /* words in co-expression stack */
#endif                                  /* StackSize */

#ifndef QualLstSize
   #define QualLstSize  5000            /* size of qualifier pointer region */
#endif                                  /* QualLstSize */

#ifndef ActStkBlkEnts
   #ifdef CoExpr
      #define ActStkBlkEnts   25        /* number of entries in an astkblk */
   #else                                /* CoExpr */
      #define ActStkBlkEnts    1        /* number of entries in an astkblk */
   #endif                               /* CoExpr */
#endif                                  /* ActStkBlkEnts */

#ifndef RegionCushion
   #define RegionCushion 20             /* % memory cushion to avoid thrashing*/
#endif                                  /* RegionCushion */

#ifndef RegionGrowth
   #define RegionGrowth 200             /* % region growth when full */
#endif                                  /* RegionGrowth */

/*
 * Minimum regions sizes (presently not used).
 */
#ifndef MinStatSize
   #ifdef CoExpr
      #define MinStatSize       10240   /* size of the static region in bytes*/
   #else                                /* CoExpr */
      #define MinStatSize        1024   /* size of static region in bytes */
   #endif                               /* CoExpr */
#endif                                  /* MinStatSize */

#ifndef MinStrSpace
   #define MinStrSpace           5000   /* size of the string space in bytes */
#endif                                  /* MinStrSpace */

#ifndef MinAbrSize
   #define MinAbrSize            5000   /* size of the block region in bytes */
#endif                                  /* MinAbrSize */

#ifndef MinMStackSize
   #define MinMStackSize         2000   /* size of the main stack in words */
#endif                                  /* MinMStackSize */

#ifndef MinStackSize
   #define MinStackSize          1000   /* words in co-expression stack */
#endif                                  /* MinStackSize */

#ifndef MinQualLstSize
   #define MinQualLstSize         500   /* size of qualifier pointer region */
#endif                                  /* MinQualLstSize */

#ifndef GranSize
   #define GranSize                64   /* storage allocation granule size */
#endif                                  /* GranSize */

#ifndef Sqlinc
   #define Sqlinc 128*sizeof(dptr *)    /* qualifier pointer list increment */
#endif                                  /* Sqlinc */

/****************************************   end ../h/../h/cpuconf.h   */


/****************************************  from ../h/../h/monitor.h:  */

/*
 * monitor.h - This file contains definitions for the various
 * event codes and values that go to make up event streams.
 *
 * The macro structure here allows the entire set of events to be enabled
 * by a single macro (EventMon) or, each individual event can be enabled
 * separately, to produce specialized virtual machines.
 */

/*
 * Note: the blank character should *not* be used as an event code.
 */

/*
 * Allocation events use lowercase codes.
 */
#if defined(EventMon) || defined(E_Lrgint)
#undef E_Lrgint
#define E_Lrgint        '\114'          /* Large integer allocation */
#else
#define E_Lrgint 0
#endif

#if defined(EventMon) || defined(E_Real)
#undef E_Real
#define E_Real          '\144'          /* Real allocation */
#else
#define E_Real 0
#endif

#if defined(EventMon) || defined(E_Cset)
#undef E_Cset
#define E_Cset          '\145'          /* Cset allocation */
#else
#define E_Cset 0
#endif

#if defined(EventMon) || defined(E_File)
#undef E_File
#define E_File          '\147'          /* File allocation */
#else
#define E_File 0
#endif

#if defined(EventMon) || defined(E_Record)
#undef E_Record
#define E_Record        '\150'          /* Record allocation */
#else
#define E_Record 0
#endif

#if defined(EventMon) || defined(E_Tvsubs)
#undef E_Tvsubs
#define E_Tvsubs        '\151'          /* Substring tv allocation */
#else
#define E_Tvsubs 0
#endif

#if defined(EventMon) || defined(E_External)
#undef E_External
#define E_External      '\152'          /* External allocation */
#else
#define E_External 0
#endif

#if defined(EventMon) || defined(E_List)
#undef E_List
#define E_List          '\153'          /* List allocation */
#else
#define E_List 0
#endif

#if defined(EventMon) || defined(E_Lelem)
#undef E_Lelem
#define E_Lelem         '\155'          /* List element allocation */
#else
#define E_Lelem 0
#endif

#if defined(EventMon) || defined(E_Table)
#undef E_Table
#define E_Table         '\156'          /* Table allocation */
#else
#define E_Table 0
#endif

#if defined(EventMon) || defined(E_Telem)
#undef E_Telem
#define E_Telem         '\157'          /* Table element allocation */
#else
#define E_Telem 0
#endif

#if defined(EventMon) || defined(E_Tvtbl)
#undef E_Tvtbl
#define E_Tvtbl         '\160'          /* Table-element tv allocation */
#else
#define E_Tvtbl 0
#endif

#if defined(EventMon) || defined(E_Set)
#undef E_Set
#define E_Set           '\161'          /* Set allocation */
#else
#define E_Set 0
#endif

#if defined(EventMon) || defined(E_Selem)
#undef E_Selem
#define E_Selem         '\164'          /* Set element allocation */
#else
#define E_Selem 0
#endif

#if defined(EventMon) || defined(E_Slots)
#undef E_Slots
#define E_Slots         '\167'          /* Hash header allocation */
#else
#define E_Slots 0
#endif

#if defined(EventMon) || defined(E_CoCreate)
#undef E_CoCreate
#define E_CoCreate      '\177'          /* Co-expression creation */
#else
#define E_CoCreate 0
#endif

#if defined(EventMon) || defined(E_Coexpr)
#undef E_Coexpr
#define E_Coexpr        '\170'          /* Co-expression allocation */
#else
#define E_Coexpr 0
#endif

#if defined(EventMon) || defined(E_Refresh)
#undef E_Refresh
#define E_Refresh       '\171'          /* Refresh allocation */
#else
#define E_Refresh 0
#endif

#if defined(EventMon) || defined(E_Alien)
#undef E_Alien
#define E_Alien         '\172'          /* Alien allocation */
#else
#define E_Alien 0
#endif

#if defined(EventMon) || defined(E_Free)
#undef E_Free
#define E_Free          '\132'          /* Free region */
#else
#define E_Free 0
#endif

#if defined(EventMon) || defined(E_String)
#undef E_String
#define E_String        '\163'          /* String allocation */
#else
#define E_String 0
#endif


/*
 * Some other monitoring codes.
 */
#if defined(EventMon) || defined(E_BlkDeAlc)
#undef E_BlkDeAlc
#define E_BlkDeAlc      '\055'          /* Block deallocation */
#else
#define E_BlkDeAlc 0
#endif

#if defined(EventMon) || defined(E_StrDeAlc)
#undef E_StrDeAlc
#define E_StrDeAlc      '\176'          /* String deallocation */
#else
#define E_StrDeAlc 0
#endif


/*
 * These are not "events"; they are provided for uniformity in tools
 *  that deal with types.
 */
#if defined(EventMon) || defined(E_Integer)
#undef E_Integer
#define E_Integer       '\100'          /* Integer value pseudo-event */
#else
#define E_Integer 0
#endif

#if defined(EventMon) || defined(E_Null)
#undef E_Null
#define E_Null          '\044'          /* Null value pseudo-event */
#else
#define E_Null 0
#endif

#if defined(EventMon) || defined(E_Proc)
#undef E_Proc
#define E_Proc          '\045'          /* Procedure value pseudo-event */
#else
#define E_Proc 0
#endif

#if defined(EventMon) || defined(E_Kywdint)
#undef E_Kywdint
#define E_Kywdint       '\136'          /* Integer keyword value pseudo-event */
#else
#define E_Kywdint 0
#endif

#if defined(EventMon) || defined(E_Kywdpos)
#undef E_Kywdpos
#define E_Kywdpos       '\046'          /* Position value pseudo-event */
#else
#define E_Kywdpos 0
#endif

#if defined(EventMon) || defined(E_Kywdsubj)
#undef E_Kywdsubj
#define E_Kywdsubj      '\052'          /* Subject value pseudo-event */
#else
#define E_Kywdsubj 0
#endif


/*
 * Codes for main sequence events
 */

   /*
    * Timing events
    */
#if defined(EventMon) || defined(E_Tick)
#undef E_Tick
#define E_Tick          '\270'          /* Clock tick */
#else
#define E_Tick 0
#endif



   /*
    * Code-location event
    */
#if defined(EventMon) || defined(E_Loc)
#undef E_Loc
#define E_Loc           '\273'          /* Location change */
#else
#define E_Loc 0
#endif

#if defined(EventMon) || defined(E_Line)
#undef E_Line
#define E_Line          '\274'          /* Line change */
#else
#define E_Line 0
#endif


   /*
    * Virtual-machine instructions
    */
#if defined(EventMon) || defined(E_Opcode)
#undef E_Opcode
#define E_Opcode        '\240'          /* Virtual-machine instruction */
#else
#define E_Opcode 0
#endif

#if defined(EventMon) || defined(E_Operand)
#undef E_Operand
#define E_Operand       '\241'          /* Virtual-machine Operand*/
#else
#define E_Operand 0
#endif


   /*
    * Type-conversion events
    */
#if defined(EventMon) || defined(E_Aconv)
#undef E_Aconv
#define E_Aconv         '\111'          /* Conversion attempt */
#else
#define E_Aconv 0
#endif

#if defined(EventMon) || defined(E_Tconv)
#undef E_Tconv
#define E_Tconv         '\113'          /* Conversion target */
#else
#define E_Tconv 0
#endif

#if defined(EventMon) || defined(E_Nconv)
#undef E_Nconv
#define E_Nconv         '\116'          /* Conversion not needed */
#else
#define E_Nconv 0
#endif

#if defined(EventMon) || defined(E_Sconv)
#undef E_Sconv
#define E_Sconv         '\121'          /* Conversion success */
#else
#define E_Sconv 0
#endif

#if defined(EventMon) || defined(E_Fconv)
#undef E_Fconv
#define E_Fconv         '\112'          /* Conversion failure */
#else
#define E_Fconv 0
#endif


   /*
    * Structure events
    */
#if defined(EventMon) || defined(E_Lbang)
#undef E_Lbang
#define E_Lbang         '\301'          /* List generation */
#else
#define E_Lbang 0
#endif

#if defined(EventMon) || defined(E_Lcreate)
#undef E_Lcreate
#define E_Lcreate       '\302'          /* List creation */
#else
#define E_Lcreate 0
#endif

#if defined(EventMon) || defined(E_Lget)
#undef E_Lget
#define E_Lget          '\356'          /* List get/pop -- only E_Lget used */
#else
#define E_Lget 0
#endif

#if defined(EventMon) || defined(E_Lpop)
#undef E_Lpop
#define E_Lpop          '\356'          /* List get/pop */
#else
#define E_Lpop 0
#endif

#if defined(EventMon) || defined(E_Lpull)
#undef E_Lpull
#define E_Lpull         '\304'          /* List pull */
#else
#define E_Lpull 0
#endif

#if defined(EventMon) || defined(E_Lpush)
#undef E_Lpush
#define E_Lpush         '\305'          /* List push */
#else
#define E_Lpush 0
#endif

#if defined(EventMon) || defined(E_Lput)
#undef E_Lput
#define E_Lput          '\306'          /* List put */
#else
#define E_Lput 0
#endif

#if defined(EventMon) || defined(E_Lrand)
#undef E_Lrand
#define E_Lrand         '\307'          /* List random reference */
#else
#define E_Lrand 0
#endif

#if defined(EventMon) || defined(E_Lref)
#undef E_Lref
#define E_Lref          '\310'          /* List reference */
#else
#define E_Lref 0
#endif

#if defined(EventMon) || defined(E_Lsub)
#undef E_Lsub
#define E_Lsub          '\311'          /* List subscript */
#else
#define E_Lsub 0
#endif

#if defined(EventMon) || defined(E_Ldelete)
#undef E_Ldelete
#define E_Ldelete       '\357'          /* List delete */
#else
#define E_Ldelete 0
#endif

#if defined(EventMon) || defined(E_Rbang)
#undef E_Rbang
#define E_Rbang         '\312'          /* Record generation */
#else
#define E_Rbang 0
#endif

#if defined(EventMon) || defined(E_Rcreate)
#undef E_Rcreate
#define E_Rcreate       '\313'          /* Record creation */
#else
#define E_Rcreate 0
#endif

#if defined(EventMon) || defined(E_Rrand)
#undef E_Rrand
#define E_Rrand         '\314'          /* Record random reference */
#else
#define E_Rrand 0
#endif

#if defined(EventMon) || defined(E_Rref)
#undef E_Rref
#define E_Rref          '\315'          /* Record reference */
#else
#define E_Rref 0
#endif

#if defined(EventMon) || defined(E_Rsub)
#undef E_Rsub
#define E_Rsub          '\316'          /* Record subscript */
#else
#define E_Rsub 0
#endif

#if defined(EventMon) || defined(E_Sbang)
#undef E_Sbang
#define E_Sbang         '\317'          /* Set generation */
#else
#define E_Sbang 0
#endif

#if defined(EventMon) || defined(E_Screate)
#undef E_Screate
#define E_Screate       '\320'          /* Set creation */
#else
#define E_Screate 0
#endif

#if defined(EventMon) || defined(E_Sdelete)
#undef E_Sdelete
#define E_Sdelete       '\321'          /* Set deletion */
#else
#define E_Sdelete 0
#endif

#if defined(EventMon) || defined(E_Sinsert)
#undef E_Sinsert
#define E_Sinsert       '\322'          /* Set insertion */
#else
#define E_Sinsert 0
#endif

#if defined(EventMon) || defined(E_Smember)
#undef E_Smember
#define E_Smember       '\323'          /* Set membership */
#else
#define E_Smember 0
#endif

#if defined(EventMon) || defined(E_Srand)
#undef E_Srand
#define E_Srand         '\336'          /* Set random reference */
#else
#define E_Srand 0
#endif

#if defined(EventMon) || defined(E_Sval)
#undef E_Sval
#define E_Sval          '\324'          /* Set value */
#else
#define E_Sval 0
#endif

#if defined(EventMon) || defined(E_Tbang)
#undef E_Tbang
#define E_Tbang         '\325'          /* Table generation */
#else
#define E_Tbang 0
#endif

#if defined(EventMon) || defined(E_Tcreate)
#undef E_Tcreate
#define E_Tcreate       '\326'          /* Table creation */
#else
#define E_Tcreate 0
#endif

#if defined(EventMon) || defined(E_Tdelete)
#undef E_Tdelete
#define E_Tdelete       '\327'          /* Table deletion */
#else
#define E_Tdelete 0
#endif

#if defined(EventMon) || defined(E_Tinsert)
#undef E_Tinsert
#define E_Tinsert       '\330'          /* Table insertion */
#else
#define E_Tinsert 0
#endif

#if defined(EventMon) || defined(E_Tkey)
#undef E_Tkey
#define E_Tkey          '\331'          /* Table key generation */
#else
#define E_Tkey 0
#endif

#if defined(EventMon) || defined(E_Tmember)
#undef E_Tmember
#define E_Tmember       '\332'          /* Table membership */
#else
#define E_Tmember 0
#endif

#if defined(EventMon) || defined(E_Trand)
#undef E_Trand
#define E_Trand         '\337'          /* Table random reference */
#else
#define E_Trand 0
#endif

#if defined(EventMon) || defined(E_Tref)
#undef E_Tref
#define E_Tref          '\333'          /* Table reference */
#else
#define E_Tref 0
#endif

#if defined(EventMon) || defined(E_Tsub)
#undef E_Tsub
#define E_Tsub          '\334'          /* Table subscript */
#else
#define E_Tsub 0
#endif

#if defined(EventMon) || defined(E_Tval)
#undef E_Tval
#define E_Tval          '\335'          /* Table value */
#else
#define E_Tval 0
#endif


   /*
    * Scanning events
    */

#if defined(EventMon) || defined(E_Snew)
#undef E_Snew
#define E_Snew          '\340'          /* Scanning environment creation */
#else
#define E_Snew 0
#endif

#if defined(EventMon) || defined(E_Sfail)
#undef E_Sfail
#define E_Sfail         '\341'          /* Scanning failure */
#else
#define E_Sfail 0
#endif

#if defined(EventMon) || defined(E_Ssusp)
#undef E_Ssusp
#define E_Ssusp         '\266'          /* Scanning suspension */
#else
#define E_Ssusp 0
#endif

#if defined(EventMon) || defined(E_Sresum)
#undef E_Sresum
#define E_Sresum        '\267'          /* Scanning resumption */
#else
#define E_Sresum 0
#endif

#if defined(EventMon) || defined(E_Srem)
#undef E_Srem
#define E_Srem          '\344'          /* Scanning environment removal */
#else
#define E_Srem 0
#endif

#if defined(EventMon) || defined(E_Spos)
#undef E_Spos
#define E_Spos          '\346'          /* Scanning position */
#else
#define E_Spos 0
#endif


   /*
    * Assignment
    */

#if defined(EventMon) || defined(E_Assign)
#undef E_Assign
#define E_Assign        '\347'          /* Assignment */
#else
#define E_Assign 0
#endif

#if defined(EventMon) || defined(E_Value)
#undef E_Value
#define E_Value         '\350'          /* Value assigned */
#else
#define E_Value 0
#endif

#if defined(EventMon) || defined(E_Deref)
#undef E_Deref
#define E_Deref         '\363'          /* Dereference */
#else
#define E_Deref 0
#endif



   /*
    * Sub-string assignment
    */

#if defined(EventMon) || defined(E_Ssasgn)
#undef E_Ssasgn
#define E_Ssasgn        '\354'          /* Sub-string assignment */
#else
#define E_Ssasgn 0
#endif


   /*
    * Interpreter stack events
    */

#if defined(EventMon) || defined(E_Intcall)
#undef E_Intcall
#define E_Intcall       '\275'          /* interpreter call */
#else
#define E_Intcall 0
#endif

#if defined(EventMon) || defined(E_Intret)
#undef E_Intret
#define E_Intret        '\276'          /* interpreter return */
#else
#define E_Intret 0
#endif

#if defined(EventMon) || defined(E_Stack)
#undef E_Stack
#define E_Stack         '\272'          /* stack depth */
#else
#define E_Stack 0
#endif

#if defined(EventMon) || defined(E_Cstack)
#undef E_Cstack
#define E_Cstack                '\271'          /* C stack depth */
#else
#define E_Cstack 0
#endif

   /*
    * Expression events
    */
#if defined(EventMon) || defined(E_Ecall)
#undef E_Ecall
#define E_Ecall         '\143'          /* Call of operation */
#else
#define E_Ecall 0
#endif

#if defined(EventMon) || defined(E_Efail)
#undef E_Efail
#define E_Efail         '\251'          /* Failure from expression */
#else
#define E_Efail 0
#endif

#if defined(EventMon) || defined(E_Bsusp)
#undef E_Bsusp
#define E_Bsusp         '\250'          /* Suspension from operation */
#else
#define E_Bsusp 0
#endif

#if defined(EventMon) || defined(E_Esusp)
#undef E_Esusp
#define E_Esusp         '\141'          /* Suspension from alternation */
#else
#define E_Esusp 0
#endif

#if defined(EventMon) || defined(E_Lsusp)
#undef E_Lsusp
#define E_Lsusp         '\154'          /* Suspension from limitation */
#else
#define E_Lsusp 0
#endif

#if defined(EventMon) || defined(E_Eresum)
#undef E_Eresum
#define E_Eresum        '\236'          /* Resumption of expression */
#else
#define E_Eresum 0
#endif

#if defined(EventMon) || defined(E_Erem)
#undef E_Erem
#define E_Erem          '\237'          /* Removal of a suspended generator */
#else
#define E_Erem 0
#endif

#if defined(EventMon) || defined(E_Syntax)
#undef E_Esyntax
#define E_Syntax        '\242'          /* Source code syntax change */
#else
#define E_Syntax 0
#endif

   /*
    * Co-expression events
    */

#if defined(EventMon) || defined(E_Coact)
#undef E_Coact
#define E_Coact         '\101'          /* Co-expression activation */
#else
#define E_Coact 0
#endif

#if defined(EventMon) || defined(E_Coret)
#undef E_Coret
#define E_Coret         '\102'          /* Co-expression return */
#else
#define E_Coret 0
#endif

#if defined(EventMon) || defined(E_Cofail)
#undef E_Cofail
#define E_Cofail        '\104'          /* Co-expression failure */
#else
#define E_Cofail 0
#endif


   /*
    * Procedure events
    */

#if defined(EventMon) || defined(E_Pcall)
#undef E_Pcall
#define E_Pcall         '\103'          /* Procedure call */
#else
#define E_Pcall 0
#endif

#if defined(EventMon) || defined(E_Pfail)
#undef E_Pfail
#define E_Pfail         '\246'          /* Procedure failure */
#else
#define E_Pfail 0
#endif

#if defined(EventMon) || defined(E_Pret)
#undef E_Pret
#define E_Pret          '\245'          /* Procedure return */
#else
#define E_Pret 0
#endif

#if defined(EventMon) || defined(E_Psusp)
#undef E_Psusp
#define E_Psusp         '\243'          /* Procedure suspension */
#else
#define E_Psusp 0
#endif

#if defined(EventMon) || defined(E_Presum)
#undef E_Presum
#define E_Presum        '\244'          /* Procedure resumption */
#else
#define E_Presum 0
#endif

#if defined(EventMon) || defined(E_Prem)
#undef E_Prem
#define E_Prem          '\247'          /* Suspended procedure removal */
#else
#define E_Prem 0
#endif


#if defined(EventMon) || defined(E_Fcall)
#undef E_Fcall
#define E_Fcall         '\252'          /* Function call */
#else
#define E_Fcall 0
#endif

#if defined(EventMon) || defined(E_Ffail)
#undef E_Ffail
#define E_Ffail         '\256'          /* Function failure */
#else
#define E_Ffail 0
#endif

#if defined(EventMon) || defined(E_Fret)
#undef E_Fret
#define E_Fret          '\255'          /* Function return */
#else
#define E_Fret 0
#endif

#if defined(EventMon) || defined(E_Fsusp)
#undef E_Fsusp
#define E_Fsusp         '\253'          /* Function suspension */
#else
#define E_Fsusp 0
#endif

#if defined(EventMon) || defined(E_Fresum)
#undef E_Fresum
#define E_Fresum        '\254'          /* Function resumption */
#else
#define E_Fresum 0
#endif

#if defined(EventMon) || defined(E_Frem)
#undef E_Frem
#define E_Frem          '\257'          /* Function suspension removal */
#else
#define E_Frem 0
#endif


#if defined(EventMon) || defined(E_Ocall)
#undef E_Ocall
#define E_Ocall         '\260'          /* Operator call */
#else
#define E_Ocall 0
#endif

#if defined(EventMon) || defined(E_Ofail)
#undef E_Ofail
#define E_Ofail         '\262'          /* Operator failure */
#else
#define E_Ofail 0
#endif

#if defined(EventMon) || defined(E_Oret)
#undef E_Oret
#define E_Oret          '\261'          /* Operator return */
#else
#define E_Oret 0
#endif

#if defined(EventMon) || defined(E_Osusp)
#undef E_Osusp
#define E_Osusp         '\263'          /* Operator suspension */
#else
#define E_Osusp 0
#endif

#if defined(EventMon) || defined(E_Oresum)
#undef E_Oresum
#define E_Oresum        '\264'          /* Operator resumption */
#else
#define E_Oresum 0
#endif

#if defined(EventMon) || defined(E_Orem)
#undef E_Orem
#define E_Orem          '\265'          /* Operator suspension removal */
#else
#define E_Orem 0
#endif


   /*
    * Garbage collections
    */

#if defined(EventMon) || defined(E_Collect)
#undef E_Collect
#define E_Collect       '\107'          /* Garbage collection */
#else
#define E_Collect 0
#endif

#if defined(EventMon) || defined(E_EndCollect)
#undef E_EndCollect
#define E_EndCollect    '\360'          /* End of garbage collection */
#else
#define E_EndCollect 0
#endif

#if defined(EventMon) || defined(E_TenureString)
#undef E_TenureString
#define E_TenureString  '\361'          /* Tenure a string region */
#else
#define E_TenureString 0
#endif

#if defined(EventMon) || defined(E_TenureBlock)
#undef E_TenureBlock
#define E_TenureBlock   '\362'          /* Tenure a block region */
#else
#define E_TenureBlock 0
#endif


/*
 * Termination Events
 */
#if defined(EventMon) || defined(E_Error)
#undef E_Error
#define E_Error         '\105'          /* Run-time error */
#else
#define E_Error 0
#endif

#if defined(EventMon) || defined(E_Exit)
#undef E_Exit
#define E_Exit          '\130'          /* Program exit */
#else
#define E_Exit 0
#endif


   /*
    * I/O events
    */
#if defined(EventMon) || defined(E_MXevent)
#undef E_MXevent
#define E_MXevent       '\370'          /* monitor input event */
#else
#define E_MXevent 0
#endif

#if defined(EventMon) || defined(E_Literal)
#undef E_Literal
#define E_Literal       '\277'
#else
#define E_Literal 0
#endif

#if defined(EventMon) || defined(E_Signal)
#undef E_Signal
#define E_Signal        '\300'
#else
#define E_Signal 0
#endif

#if defined(EventMon) || defined(E_Pattern)
#undef E_Pattern
#define E_Pattern       '\060'
#else
#define E_Pattern 0
#endif

#if defined(EventMon) || defined(E_Pelem)
#undef E_Pelem
#define E_Pelem         '\061'
#else
#define E_Pelem 0
#endif

#if defined(EventMon) || defined(E_PatCode)
#undef E_PatCode
#define E_PatCode        '\062'
#else
#define E_PatCode 0
#endif

#if defined(EventMon) || defined(E_PatAttempt)
#undef E_PatAttempt
#define E_PatAttempt '\063'
#else
#define E_PatAttempt 0
#endif

#if defined(EventMon) || defined(E_PatMatch)
#undef E_PatMatch
#define E_PatMatch '\064'
#else
#define E_PatMatch 0
#endif

#if defined(EventMon) || defined(E_PatFail)
#undef E_PatFail
#define E_PatFail '\065'
#else
#define E_PatFail 0
#endif

#if defined(EventMon) || defined(E_PelemAttempt)
#undef E_PelemAttempt
#define E_PelemAttempt '\066'
#else
#define E_PelemAttempt 0
#endif

#if defined(EventMon) || defined(E_PelemMatch)
#undef E_PelemMatch
#define E_PelemMatch '\067'
#else
#define E_PelemMatch 0
#endif

#if defined(EventMon) || defined(E_PelemFail)
#undef E_PelemFail
#define E_PelemFail '\070'
#else
#define E_PelemFail 0
#endif

#if defined(EventMon) || defined(E_PatArg)
#undef E_PatArg
#define E_PatArg '\071'
#else
#define E_PatArg 0
#endif

#if defined(EventMon) || defined(E_PatVal)
#undef E_PatVal
#define E_PatVal '\072'
#else
#define E_PatVal 0
#endif

#if defined(EventMon) || defined(E_PatPush)
#undef E_PatPush
#define E_PatPush '\073'
#else
#define E_PatPush 0
#endif

#if defined(EventMon) || defined(E_PatPop)
#undef E_PatPop
#define E_PatPop '\074'
#else
#define E_PatPop 0
#endif

/*
 * Events for hash table details. The table events like E_Tsub
 * already provide keys.  E_HashNum is a number returned by hash().
 * E_HashSlots is an expansion of the buckets for a given set/table.
 * E_HashChain is the number of link list elements traversed in a lookup.
 */

#if defined(EventMon) || defined(E_HashNum)
#undef E_HashNum
#define E_HashNum       '\173'
#else
#define E_HashNum 0
#endif

#if defined(EventMon) || defined(E_HashSlots)
#undef E_HashSlots
#define E_HashSlots       '\174'
#else
#define E_HashSlots 0
#endif

#if defined(EventMon) || defined(E_HashChain)
#undef E_HashChain
#define E_HashChain       '\175'
#else
#define E_HashChain 0
#endif



/* unused pool.  how many event codes are unused?  DON'T USE 000.
                                        Decimal
000 001 002 003 004 005 006 007
010 011 012 013 014 015 016 017
020 021 022 023 024 025 026 027         16
030 031 032 033 034 035 036 037
                                                blank line for readability
040 041 042 043 047                     32
050 051     053 054     056 057

                    075 076 077
-------------------------------                 blank line for readability
                        106             64
110                 115     117
120     122 123 124 125 126 127
    131     133 134 135     137
-------------------------------                 blank line for readability
140     142             146             96

        162         165 166

-------------------------------                 blank line for readability
200 201 202 203 204 205 206 207         128     SPECIAL SECTION. From 128-191
210 211 212 213 214 215 216 217                 RESERVED FOR interp() stuff.
220 221 222 223 224 225 226 227         144
230 231 232 233 234 235
-------------------------------                 blank line for readability
                                        160     SPECIAL SECTION. From 128-191
                                                RESERVED FOR interp() stuff.


-------------------------------
            303                         192



        342 343     345
    351 352 353     355
                364 365 366 367
    371 372 373 374 375 376 377
*/

/****************************************   end ../h/../h/monitor.h   */


/****************************************  from ../h/../h/rmacros.h:  */

/*
 *  Definitions for macros and manifest constants used in the compiler
 *  interpreter.
 */

/*
 *  Definitions common to the compiler and interpreter.
 */

/*
 * Constants that are not likely to vary between implementations.
 */

#define BitOffMask (IntBits-1)
#define CsetSize (256/IntBits)  /* number of ints to hold 256 cset
                                 *  bits. Use (256/IntBits)+1 if
                                 *  256 % IntBits != 0 */
#define MinListSlots        8   /* number of elements in an expansion
                                 * list element block  */

#define MaxCvtLen          257  /* largest string in conversions; the extra
                                 *  one is for a terminating null */
#define MaxReadStr         512  /* largest string to read() in one piece */
#if IntBits==16
#define MaxIn             32767 /* largest number of bytes to read() at once */
#else
#define MaxIn           ((10*1024*1024)-1) /* max # of bytes to reads() at once */
#endif
#define RandA        1103515245 /* random seed multiplier */
#define RandC         453816694 /* random seed additive constant */
#define RanScale 4.65661286e-10 /* random scale factor = 1/(2^31-1) */

#define Pi 3.14159265358979323846264338327950288419716939937511

/*
 * File status flags in status field of file blocks.
 */
#define Fs_Read          01     /* read access */
#define Fs_Write         02     /* write access */
#define Fs_Create        04     /* file created on open */
#define Fs_Append       010     /* append mode */
#define Fs_Pipe         020     /* reading or writing on a pipe */
                                /* see also: BPipe down below */

/*                      040        this bit is now available */

#define Fs_Reading     0100     /* last file operation was read */
#define Fs_Writing     0200     /* last file operation was write */

/*#ifdef Graphics*/
   #define Fs_Window   0400     /* reading/writing on a window */
/*#endif */                                     /* Graphics */

#define Fs_Untrans    01000     /* untranslated mode file */
#define Fs_Directory  02000     /* reading a directory */

#ifdef Dbm
   #define Fs_Dbm       04000           /* a dbm file */
#endif                                  /* Dbm */

#ifdef PosixFns
   #define Fs_Socket    010000
   #define Fs_Buff      020000
   #define Fs_Unbuf     040000
   #define Fs_Listen   0100000
   #define Fs_BPipe    0200000          /* bidirectional pipe */

#if HAVE_LIBSSL
  #define Fs_Encrypt   0200000000      /* encrypted sockets */
#endif

#endif                                  /* PosixFns */

#ifdef ISQL
   #define Fs_ODBC      0400000
   #define RC_SUCCESSFUL(rc) (rc==SQL_SUCCESS || rc==SQL_SUCCESS_WITH_INFO)
   #define RC_NOTSUCCESSFUL(rc) (!(RC_SUCCESSFUL(rc)))
#endif                                  /* ISQL */

#ifdef Messaging
   #define Fs_Messaging 01000000
   #define Fs_Verify    02000000
#endif                                  /* Messaging */

/*#ifdef Graphics3D*/
   #define Fs_Window3D  04000000        /* reading/writing on a window */
/*#endif*/                                      /* Graphics3D */

#if HAVE_LIBZ
   #define Fs_Compress  010000000       /* reading/writing compressed file */
#endif                                  /* HAVE_LIBZ */

#ifdef HAVE_VOICE
   #define Fs_Voice     020000000               /* voice/audio connection */
#endif                                  /* HAVE_VOICE */

#ifdef PseudoPty
   #define Fs_Pty       040000000            /* pty */
#endif


/*
 * Thread status flags in status field of coexpr blocks.
 * Ts_Native can only be Ts_Sync.  Ts_Posix may be Sync or Async.
 */
#define Ts_Main         01              /* This is the main co-expression */
#define Ts_Thread       02              /* This is a thread */
#define Ts_Attached     04              /* OS-level thread attached to this ce */
#define Ts_Async       010              /* asynchronous (concurrent) thread */
#define Ts_Posix       020              /* POSIX (pthread-based) coexpression */

#define Ts_SoftThread   01000           /* soft thread */

#define SET_FLAG(X,F)        (X) |= (F)
#define UNSET_FLAG(X,F)      (X) &= ~(F)
#define CHECK_FLAG(X,F)      ((X) & (F))
#define NOT_CHECK_FLAG(X,F)  (!CHECK_FLAG(X,F))

#define IS_TS_MAIN(X)     CHECK_FLAG(X, Ts_Main)
#define IS_TS_THREAD(X)   CHECK_FLAG(X, Ts_Thread)
#define IS_TS_ATTACHED(X) CHECK_FLAG(X, Ts_Attached)
#define IS_TS_POSIX(X)    CHECK_FLAG(X, Ts_Posix)
#define IS_TS_ASYNC(X)    CHECK_FLAG(X, Ts_Async)
#define IS_TS_SYNC(X) (!IS_TS_ASYNC(X))
#define IS_TS_SOFTTHREAD(X) CHECK_FLAG(X, Ts_SoftThread)

/*#ifdef Graphics*/
   #define XKey_Window 0
   #define XKey_Fg 1

   #ifndef SHORT
      #define SHORT int
   #endif                               /* SHORT */
   #ifndef LONG
      #define LONG int
   #endif                               /* LONG */

   /*
    * Perform a "C" return, not processed by RTT
    */
   #define VanquishReturn(s) return s;
/*#endif*/                                      /* Graphics */

/*
 * Codes returned by runtime support routines.
 *  Note, some conversion routines also return type codes. Other routines may
 *  return positive values other than return codes. sort() places restrictions
 *  on Less, Equal, and Greater.
 *
 * The symbol Error is used in Windows 8.1 header file ws2tcpip.h, so Unicon's
 * Error has been renamed RunError.
 */

#define Less            -1
#define Equal           0
#define Greater         1

#define CvtFail         -2
#define Cvt             -3
#define NoCvt           -4
#define Failed          -5
#define Defaulted       -6
#define Succeeded       -7
#define RunError        -8

#define GlobalName      0
#define StaticName      1
#define ParamName       2
#define LocalName       3

#undef ToAscii
#undef FromAscii
#if EBCDIC == 2
   #define ToAscii(e) (FromEBCDIC[e])
   #define FromAscii(e) (ToEBCDIC[e])
#else                                   /* EBCDIC == 2 */
   #define ToAscii(e) (e)
   #define FromAscii(e) (e)
#endif                                  /* EBCDIC == 2 */

/*
 * Pointer to block.
 */
#define BlkLoc(d)       ((d).vword.bptr)

#define BlkMask(d)      ((struct b_mask *)((d).vword.bptr))

/*
 * Block reference macros.  This abstraction of the act of dereferencing a
 * block pointer does not add clarity, it allows runtime type checking of
 * block references, if DebugHeap is enabled.
 *
 * Blk   ("Block") - convert union block ptr to a typed block ptr
 * BlkD  ("Block (from) Descriptor") - fetch typed block ptr for a descriptor
 * BlkPH ("Block )
 */
#define BlkD(d,u) Blk(BlkLoc(d),u)
#ifndef DebugHeap
#define Blk(p,u) (&((p)->u))
#define BlkPH(p,u,s) ((p)->u.s)
#define BlkPE(p,u,s) ((p)->u.s)
#else                                   /* !DebugHeap */

/*
 * Debug Heap macros.  These add runtime checks to catch (most)
 * illegal block references resulting from untended pointers.
 * Use during new code development, when gdb and valgrind fail to help.
 */

/*
 * could make the ValidPtr check much pickier -- check if it is
 * in a block or icode region (only places blocks can appear)
 */
#define ValidPtr(p) (((unsigned long)(p)) > 256)

/*
 * Block references that do not use (the address of) a particular field.
 */
#ifdef __clang__
#define Blk(p,u) \
  _Pragma("clang diagnostic push")                                  \
  _Pragma("clang diagnostic ignored \"-Wunused-value\"")            \
  ((((!ValidPtr(p)) || ((p)->u.title != T_ ## u)) ?                 \
      (heaperr("invalid block",p, T_ ## u) , 1) : 1), &((p)->u))    \
  _Pragma("clang diagnostic pop")
#else
#define Blk(p,u) \
  ((((!ValidPtr(p)) || ((p)->u.title != T_ ## u)) ?                 \
      (heaperr("invalid block",p, T_ ## u) , 1) : 1), &((p)->u))
#endif

/*
 * Block references for generic (set|table) code.
 */
#define BlkPA(p,u,s,t,f) \
   ((ValidPtr(p) ? \
   ((((p)->Set.title == T_ ## s)||((p)->Set.title == T_ ## t)) ? ((p)->u.f) : \
      (heaperr("invalid block title", p, (p)->Set.title), ((p)->u.f))) : \
     (syserr("invalid pointer"), ((p)->u.f))))
#define BlkPH(p,u,f) BlkPA(p,u,Set,Table,f)
#define BlkPE(p,u,f) BlkPA(p,u,Selem,Telem,f)

#endif                                  /* DebugHeap */

/*
 * Check for null-valued descriptor.
 */
#define ChkNull(d)      ((d).dword==D_Null)

/*
 * Check for equivalent descriptors.
 */
#define EqlDesc(d1,d2)  ((d1).dword == (d2).dword && BlkLoc(d1) == BlkLoc(d2))

/*
 * Integer value.
 */
#define IntVal(d)       ((d).vword.integr)

/*
 * Offset from top of block to value of variable.
 */
#define Offset(d)       ((d).dword & OffsetMask)

/*
 * Check for pointer.
 */
#define Pointer(d)      ((d).dword & F_Ptr)

/*
 * Check for qualifier.
 */
#define Qual(d)         (!((d).dword & F_Nqual))

/*
 * Length of string.
 */
#define StrLen(q)       ((q).dword)

/*
 * Location of first character of string.
 */
#define StrLoc(q)       ((q).vword.sptr)

/*
 * Assign a C string to a descriptor. Assume it is reasonable to use the
 *   descriptor expression more than once, but not the string expression.
 */
#define AsgnCStr(d,s) (StrLoc(d) = (s), StrLen(d) = strlen(StrLoc(d)))

/*
 * Type of descriptor.
 */
#ifdef DebugHeap
#define Type(d)         (int)((((d).dword & F_Typecode) ? ((int)((d).dword & TypeMask)) : (heaperr("descriptor type error",BlkLoc(d),(d).dword), -1)))
#else                                   /* DebugHeap */
#define Type(d) (int)((d).dword & TypeMask)
#endif                                  /* DebugHeap */

/*
 * Check for variable.
 */
#define Var(d)          ((d).dword & F_Var)

/*
 * Location of the value of a variable.
 */
#define VarLoc(d)       ((d).vword.descptr)

/*
 *  Important note:  The code that follows is not strictly legal C.
 *   It tests to see if pointer p2 is between p1 and p3. This may
 *   involve the comparison of pointers in different arrays, which
 *   is not well-defined.  The casts of these pointers to unsigned "words"
 *   (longs or ints, depending) works with all C compilers and architectures
 *   on which Icon has been implemented.  However, it is possible it will
 *   not work on some system.  If it doesn't, there may be a "false
 *   positive" test, which is likely to cause a memory violation or a
 *   loop. It is not practical to implement Icon on a system on which this
 *   happens.
 */

#define InRange(p1,p2,p3) ((uword)(p2) >= (uword)(p1) && (uword)(p2) < (uword)(p3))

/*
 * Get floating-point number from real block.    * Get floating-point number into res from real block dp.
 * If Double is defined, the value may be misaligned.
 */
#ifdef Double
#ifdef DescriptorDouble
   #define GetReal(dp,res) *((struct size_dbl *)&(res)) =\
         *((struct size_dbl *)&((dp)->vword.realval))
#else                                   /* DescriptorDouble */
#ifdef DebugHeap
   #define GetReal(dp,res) (BlkD(*dp, Real), *((struct size_dbl *)&(res)) =\
         *((struct size_dbl *)&(BlkLoc(*dp)->Real.realval)))
#else                                   /* DebugHeap */
   #define GetReal(dp,res) *((struct size_dbl *)&(res)) =\
         *((struct size_dbl *)&((BlkLoc(*dp)->Real.realval)))
#endif                                  /* DebugHeap */
#endif                                  /* DescriptorDouble */

#else                                   /* Double */
#ifdef DescriptorDouble
   #define GetReal(dp,res)      res = dp->vword.realval
#else                                   /* DescriptorDouble */
   #define GetReal(dp,res)      res = BlkD(*dp,Real)->realval
#endif                                  /* DescriptorDouble */
#endif                                  /* Double */

#ifdef DescriptorDouble
   #define RealVal(d)           (d).vword.realval
#else                                   /* DescriptorDouble */
   #define RealVal(d)           BlkLoc(d)->Real.realval
#endif                                  /* DescriptorDouble */


/*
 * Absolute value, maximum, and minimum.
 */
   #define Abs(x) (((x) < 0) ? (-(x)) : (x))
   /*
    * gcc docs recommends these type-safe definitions for Max/Min
    */

#define Max(a,b)               \
  ({ __typeof__(a) _a = (a);   \
     __typeof__(b) _b = (b);   \
    _a > _b ? _a : _b; })

#define Min(a,b)               \
  ({ __typeof__ (a) _a = (a);  \
     __typeof__ (b) _b = (b);  \
    _a < _b ? _a : _b; })

/*
 * Number of elements of a C array, and element size.
 */
#define ElemCount(a) (sizeof(a)/sizeof(a[0]))
#define ElemSize(a) (sizeof(a[0]))

/*
 * Some C compilers take '\n' and '\r' to be the same, so the
 *  following definitions are used.
 */
#if EBCDIC
   /*
    * Note that, in EBCDIC, "line feed" and "new line" are distinct
    *  characters.  Icon's use of "line feed" is really "new line" in
    *  C terms.
    */
   #define LineFeed '\n'        /* if really "line feed", that's 37 */
   #define CarriageReturn '\r'
#else                                   /* EBCDIC */
   #define LineFeed  10
   #define CarriageReturn 13
   #define tonum(c)     (isdigit(c) ? (c - '0') : ((c & 037) + 9))
#endif                                  /* EBCDIC */


/*
 * Construct an integer descriptor.
 */
#define MakeInt(i,dp)           do { \
                         (dp)->dword = D_Integer; \
                         IntVal(*dp) = (word)(i); \
                         } while (0)

/*
 * Construct a real descriptor. dword set after vword so that we don't
 * have any half-baked reals tended at time of call to alcreal.
 */
#ifdef DescriptorDouble
#define MakeRealAlc(r,dp) do {\
   (dp)->vword.realval = r;\
   (dp)->dword = D_Real;\
   } while(0)
#else                                   /* !DescriptorDouble */
#define MakeRealAlc(r,dp) do { \
   BlkLoc(*dp) = (union block *)alcreal(r); \
   (dp)->dword = D_Real; \
   } while(0)
#endif                                  /* DescriptorDouble */

/*
 * Construct a string descriptor.
 */
#define MakeStr(s,len,dp)      do { \
                         StrLoc(*dp) = (s); \
                         StrLen(*dp) = (len); \
                         } while (0)

/*
 * Offset in word of cset bit.
 */
#define CsetOff(b)      ((b) & BitOffMask)

/*
 * Set bit b in cset c.
 */
#define Setb(b,c)       (*CsetPtr(b,c) |= (1u << CsetOff(b)))

/*
 * Test bit b in cset c.
 */
#define Testb(b,c)      ((*CsetPtr(b,c) >> CsetOff(b)) & 1u)

/*
 * Check whether a set or table needs resizing.
 */
#define SP(p) ((struct b_set *)p)
#define TooCrowded(p) \
   ((SP(p)->size > MaxHLoad*(SP(p)->mask+1)) && (SP(p)->hdir[HSegs-1] == NULL))
#define TooSparse(p) \
   ((SP(p)->hdir[1] != NULL) && (SP(p)->size < MinHLoad*(SP(p)->mask+1)))

/*
 * Definitions and declarations used for storage management.
 */
#define F_Mark          0100000         /* bit for marking blocks */

/*
 * Argument values for the built-in Icon user function "collect()".
 */
#define Static  1                       /* collection is for static region */
#define Strings 2                       /* collection is for strings */
#define Blocks  3                       /* collection is for blocks */

/*
 * Get type of block pointed at by x.
 */
#define BlkType(x)   (*(word *)x)

/*
 * BlkSize(x) takes the block pointed to by x and if the size of
 *  the block as indicated by bsizes[] is nonzero it returns the
 *  indicated size; otherwise it returns the second word in the
 *  block contains the size.
 */
#define BlkSize(x) (bsizes[*(word *)x & ~F_Mark] ? \
                     bsizes[*(word *)x & ~F_Mark] : *((word *)x + 1))

/*
 * Here are the events we support (in addition to keyboard characters)
 */
#define MOUSELEFT       (-1)
#define MOUSEMID        (-2)
#define MOUSERIGHT      (-3)
#define MOUSELEFTUP     (-4)
#define MOUSEMIDUP      (-5)
#define MOUSERIGHTUP    (-6)
#define MOUSELEFTDRAG   (-7)
#define MOUSEMIDDRAG    (-8)
#define MOUSERIGHTDRAG  (-9)
#define RESIZED         (-10)
#define WINDOWCLOSED    (-11)
#define MOUSEMOVED      (-12)
#define SCROLLUP        (-13)
#define SCROLLDOWN      (-14)
#define LASTEVENTCODE   SCROLLDOWN

/*
 * Type codes (descriptors and blocks).
 */
#define T_String        -1      /* string -- for reference; not used */
#define T_Null           0      /* null value */
#define T_Integer        1      /* integer */

#ifdef LargeInts
   #define T_Lrgint      2      /* long integer */
#endif                                  /* LargeInts */

#define T_Real           3      /* real number */
#define T_Cset           4      /* cset */
#define T_File           5      /* file */
#define T_Proc           6      /* procedure */
#define T_Record         7      /* record */
#define T_List           8      /* list header */
#define T_Lelem          9      /* list element */
#define T_Set           10      /* set header */
#define T_Selem         11      /* set element */
#define T_Table         12      /* table header */
#define T_Telem         13      /* table element */
#define T_Tvtbl         14      /* table element trapped variable */
#define T_Slots         15      /* set/table hash slots */
#define T_Tvsubs        16      /* substring trapped variable */
#define T_Refresh       17      /* refresh block */
#define T_Coexpr        18      /* co-expression */
#define T_External      19      /* external block */
#define T_Kywdint       20      /* integer keyword */
#define T_Kywdpos       21      /* keyword &pos */
#define T_Kywdsubj      22      /* keyword &subject */
#define T_Kywdwin       23      /* keyword &window */
#define T_Kywdstr       24      /* string keyword */
#define T_Kywdevent     25      /* keyword &eventsource, etc. */

#ifdef PatternType
#define T_Pattern       26      /* pattern header */
#define T_Pelem         27      /* pattern element */
#endif                                  /* PatternType */

#define T_Tvmonitored   28      /* Monitored trapped variable */
#define T_Intarray      29      /* integer array */
#define T_Realarray     30      /* real array */
#define T_Cons          31      /* generic link list element */

#define MaxType         31      /* maximum type number */

/*
 * Definitions for keywords.
 */

#define k_pos kywd_pos.vword.integr     /* value of &pos */
#define k_random kywd_ran.vword.integr  /* value of &random */
#define k_trace kywd_trc.vword.integr   /* value of &trace */
#define k_dump kywd_dmp.vword.integr    /* value of &dump */

#ifdef FncTrace
   #define k_ftrace kywd_ftrc.vword.integr      /* value of &ftrace */
#endif                                  /* FncTrace */

/*
 * Descriptor types and flags.
 */

#define D_Null          ((word)(T_Null     | D_Typecode))
#define D_Integer       ((word)(T_Integer  | D_Typecode))

#ifdef LargeInts
   #define D_Lrgint     ((word)(T_Lrgint | D_Typecode | F_Ptr))
#endif                                  /* LargeInts */

#ifdef DescriptorDouble
#define D_Real          ((word)(T_Real     | D_Typecode))
#else                                   /* DescriptorDouble */
#define D_Real          ((word)(T_Real     | D_Typecode | F_Ptr))
#endif                                  /* DescriptorDouble */
#define D_Cset          ((word)(T_Cset     | D_Typecode | F_Ptr))
#define D_File          ((word)(T_File     | D_Typecode | F_Ptr))
#define D_Proc          ((word)(T_Proc     | D_Typecode | F_Ptr))
#define D_List          ((word)(T_List     | D_Typecode | F_Ptr))
#define D_Lelem         ((word)(T_Lelem    | D_Typecode | F_Ptr))
#define D_Table         ((word)(T_Table    | D_Typecode | F_Ptr))
#define D_Telem         ((word)(T_Telem    | D_Typecode | F_Ptr))
#define D_Set           ((word)(T_Set      | D_Typecode | F_Ptr))
#define D_Selem         ((word)(T_Selem    | D_Typecode | F_Ptr))
#define D_Record        ((word)(T_Record   | D_Typecode | F_Ptr))
#define D_Tvsubs        ((word)(T_Tvsubs   | D_Typecode | F_Ptr | F_Var))
#define D_Tvtbl         ((word)(T_Tvtbl    | D_Typecode | F_Ptr | F_Var))
#define D_Tvmonitored   ((word)(T_Tvmonitored | D_Typecode | F_Ptr | F_Var))
#define D_Kywdint       ((word)(T_Kywdint  | D_Typecode | F_Ptr | F_Var))
#define D_Kywdpos       ((word)(T_Kywdpos  | D_Typecode | F_Ptr | F_Var))
#define D_Kywdsubj      ((word)(T_Kywdsubj | D_Typecode | F_Ptr | F_Var))
#define D_Refresh       ((word)(T_Refresh  | D_Typecode | F_Ptr))
#define D_Coexpr        ((word)(T_Coexpr   | D_Typecode | F_Ptr))
#define D_External      ((word)(T_External | D_Typecode | F_Ptr))
#define D_Slots         ((word)(T_Slots    | D_Typecode | F_Ptr))
#define D_Kywdwin       ((word)(T_Kywdwin  | D_Typecode | F_Ptr | F_Var))
#define D_Kywdstr       ((word)(T_Kywdstr  | D_Typecode | F_Ptr | F_Var))
#define D_Kywdevent     ((word)(T_Kywdevent | D_Typecode | F_Ptr | F_Var))
#ifdef PatternType
#define D_Pattern       ((word)(T_Pattern  | D_Typecode | F_Ptr))
#define D_Pelem         ((word)(T_Pelem    | D_Typecode | F_Ptr))
#endif                                  /* PatternType */
#define D_Intarray      ((word)(T_Intarray | D_Typecode | F_Ptr))
#define D_Realarray     ((word)(T_Realarray | D_Typecode | F_Ptr))

#define D_Var           ((word)(F_Var | F_Nqual | F_Ptr))
#define D_Typecode      ((word)(F_Nqual | F_Typecode))

#define TypeMask        63      /* type mask */
#define OffsetMask      (~(D_Var)) /* offset mask for variables */

/*
 * "In place" dereferencing. The 2nd version generates no E_Deref event;
 * it is for use during other events, to avoid spurious extra E_Deref's.
 */
#define Deref(d) if (Var(d)) deref(&d, &d)
#define Deref0(d) if (Var(d)) deref_0(&d, &d)

/*
 * Construct a substring trapped variable.
 */
#define SubStr(dest,var,len,pos)\
   if ((var)->dword == D_Tvsubs)\
      (dest)->vword.bptr = (union block *)alcsubs(len, (pos) +\
         BlkLoc(*(var))->Tvsubs.sspos - 1, &BlkLoc(*(var))->Tvsubs.ssvar);\
   else\
      (dest)->vword.bptr = (union block *)alcsubs(len, pos, (var));\
   (dest)->dword = D_Tvsubs;

/*
 * Find debug struct in procedure frame, assuming debugging is enabled.
 *  Note that there is always one descriptor in array even if it is not
 *  being used.
 */
#define PFDebug(pf) ((struct debug *)((char *)(pf).t.d +\
    sizeof(struct descrip) * ((pf).t.num ? (pf).t.num : 1)))

/*
 * Macro for initialized procedure block.
 */
#define B_IProc(n) struct {word title; word blksize; int (*ccode)();\
   word nparam; word ndynam; word nstatic; word fstatic;\
   struct sdescrip quals[n];}

/*
 * Check whether a number is not a power of 2
 */
#define not_poweroftwo(a) ((a) & (a-1))

#ifdef Concurrent

   #define CE_INBOX_SIZE        1024
   #define CE_OUTBOX_SIZE       1024
   #define CE_CEQUEUE_SIZE      64

   /* used in fmath.r, log() */
   #define lastbase             (curtstate->Lastbase)
   #define divisor              (curtstate->Divisor)

   /* used in fstr.r, map() */
   #define maptab               (curtstate->Maptab)
   #define maps2                (curtstate->Maps2)
   #define maps3                (curtstate->Maps3)

   /* used in rposix.r */
   #define callproc             (curtstate->Callproc)
   #define callproc_ibuf        (curtstate->Callproc_Ibuf)

   #define pollctr              (curtstate->Pollctr)

   #define curtstring           (curtstate->Curstring)
   #define curtblock            (curtstate->Curblock)


#define TURN_ON_CONCURRENT() do if (!is_concurrent) { \
      is_concurrent=1; global_curtstate = NULL; } while (0)

/*
#ifdef HAVE_KEYWORD__THREAD
#define CURTSTATE()
#define CURTSTATE_CE()
#else
*/

#define SYNC_GLOBAL_CURTSTATE()  do if (!is_concurrent) global_curtstate = \
      (struct threadstate *) pthread_getspecific(tstate_key); while (0)

#define TLS_CURTSTATE_ONLY()  struct threadstate *curtstate = \
      (struct threadstate *) pthread_getspecific(tstate_key);


#define GET_CURTSTATE()  struct threadstate *curtstate = \
    global_curtstate? global_curtstate: \
    (struct threadstate *) pthread_getspecific(tstate_key);

#define CURTSTATE_CE() struct b_coexpr *curtstate_ce = curtstate->c;

#ifdef NativeCoswitch
#define SYNC_CURTSTATE_CE() if (curtstate->c != curtstate_ce) curtstate_ce = curtstate->c;
#else                                   /* NativeCoswitch */
#define SYNC_CURTSTATE_CE()
#endif                                  /* NativeCoswitch */

#define CURTSTATE()  GET_CURTSTATE();
#define CURTSTATE_AND_CE() GET_CURTSTATE(); CURTSTATE_CE();

#ifdef TSTATARG
#define CURTSTATARG curtstate
#define RTTCURTSTATARG ,curtstate
#define CURTSTATVAR() CURTSTATE()
#else
#define CURTSTATARG
#define RTTCURTSTATARG
#if ConcurrentCOMPILER
#define CURTSTATVAR() CURTSTATE()
#else                                   /* ConcurrentCOMPILER */
#define CURTSTATVAR()
#endif                                  /* ConcurrentCOMPILER */
#endif                                  /* TSTATARG */
/*#endif*/

#define ssize    (curtstate->Curstring->size)
#define strbase  (curtstate->Curstring->base)
#define strend   (curtstate->Curstring->end)
#define strfree  (curtstate->Curstring->free)

#define abrsize  (curtstate->Curblock->size)
#define blkbase  (curtstate->Curblock->base)
#define blkend   (curtstate->Curblock->end)
#define blkfree  (curtstate->Curblock->free)

#else                                   /* Concurrent */

#define CURTSTATE()
#define CURTSTATE_CE()
#define CURTSTATE_AND_CE()
#define SYNC_GLOBAL_CURTSTATE()
#define TLS_CURTSTATE_ONLY()
#define SYNC_CURTSTATE_CE()

#define CURTSTATARG
#define RTTCURTSTATARG
#define CURTSTATVAR()
#define ssize    (curstring->size)
#define strbase  (curstring->base)
#define strend   (curstring->end)
#define strfree  (curstring->free)

#define abrsize  (curblock->size)
#define blkbase  (curblock->base)
#define blkend   (curblock->end)
#define blkfree  (curblock->free)
#endif                                  /* Concurrent */

#if COMPILER
#if ConcurrentCOMPILER
/*
 * ConcurrentCOMPILER claims to avoid threads hanging by periodically
 * answering thread_call's from within Poll().  This should probably
 * by reviewed by Jafar to answer: (A) is it correct and safe, and
 * (B) if so, should regular Concurrent be doing it?
 */
#ifdef Graphics
#define Poll() do{ \
  if (!pollctr--) pollctr = pollevent(); \
  if (thread_call){ \
    thread_control(TC_ANSWERCALL);}\
}while (0)
   #else                                /* Graphics */
#define Poll() do{ \
  if (thread_call){ \
  thread_control(TC_ANSWERCALL);\
  }\
  } while (0)
#endif                                   /* Graphics */
#else                                    /* ConcurrentCOMPILER */
   #ifdef Graphics
      #define Poll() if (!pollctr--) pollctr = pollevent()
   #else                                /* Graphics */
      #define Poll()
   #endif                               /* Graphics */
#endif                                  /* ConcurrentCOMPILER */

#else                                   /* COMPILER */

   /*
    * Definitions for the interpreter.
    */

   /*
    * Codes returned by invoke to indicate action.
    */
   #define I_Builtin    201     /* A built-in routine is to be invoked */
   #define I_Fail       202     /* goal-directed evaluation failed */
   #define I_Continue   203     /* Continue execution in the interp loop */
   #define I_Vararg     204     /* A function with a variable number of args */

   /*
    * Generator types.
    */
   #define G_Csusp              1
   #define G_Esusp              2
   #define G_Psusp              3
   #define G_Fsusp              4
   #define G_Osusp              5

   /*
    * Evaluation stack overflow margin
    */
   #define PerilDelta 100

   /*
    * Macro definitions related to descriptors.
    */

   /*
    * The following code is operating-system dependent [@rt.01].  Define
    *  PushAval for computers that store longs and pointers differently.
    */

   #if PORT
      #define PushAVal(x) PushVal(x)
      Deliberate Syntax Error
   #endif                               /* PORT */

   #if MVS || UNIX || VM || VMS
      #define PushAVal(x) PushVal(x)
   #endif                               /* MVS ... VMS */

   #if MSDOS
         #define PushAVal(x)  {sp++; \
                                stkword.stkadr = (char *)(x); \
                                *sp = stkword.stkint;}
   #endif                               /* MSDOS */

   /*
    * End of operating-system specific code.
    */

   /*
    * Macros for pushing values on the interpreter stack.
    */

   /*
    * Push descriptor.
    */
   #define PushDesc(d)  {*++sp = ((d).dword); sp++;*sp =((d).vword.integr);}

   /*
    * Push null-valued descriptor.
    */
   #define PushNull     {*++sp = D_Null; sp++; *sp = 0;}

   /*
    * Push word.
    */
   #define PushVal(v)   {*++sp = (word)(v);}

   /*
    * Macros related to function and operator definition.
    */

   /*
    * Procedure block for a function.
    */

   #if VMS
      #define FncBlock(f,nargs,deref) \
        struct b_iproc Cat(B,f) = {\
        T_Proc,\
        Vsizeof(struct b_proc),\
        Cat(Y,f),\
        nargs,\
        -1,\
        deref, 0,\
        {sizeof(Lit(f))-1,Lit(f)}};
   #else                                /* VMS */
      #define FncBlock(f,nargs,deref) \
        struct b_iproc Cat(B,f) = {\
        T_Proc,\
        Vsizeof(struct b_proc),\
        Cat(Z,f),\
        nargs,\
        -1,\
        deref, 0,\
        {sizeof(Lit(f))-1,Lit(f)}};
   #endif                               /* VMS */

   /*
    * Procedure block for an operator.
    */
   #define OpBlock(f,nargs,sname,xtrargs)\
        struct b_iproc Cat(B,f) = {\
        T_Proc,\
        Vsizeof(struct b_proc),\
        Cat(O,f),\
        nargs,\
        -1,\
        xtrargs,\
        0,\
        {sizeof(sname)-1,sname}};

   /*
    * Operator declaration.
    */
   #define OpDcl(nm,n,pn) OpBlock(nm,n,pn,0) Cat(O,nm)(cargp) register dptr cargp;

   /*
    * Operator declaration with extra working argument.
    */
   #define OpDclE(nm,n,pn) OpBlock(nm,-n,pn,0) Cat(O,nm)(cargp) register dptr cargp;

   /*
    * Agent routine declaration.
    */
   #define AgtDcl(nm) Cat(A,nm)(cargp) register dptr cargp;

   /*
    * Macros to access Icon arguments in C functions.
    */

   /*
    * n-th argument.
    */
   #define Arg(n)               (cargp[n])

   /*
    * Type field of n-th argument.
    */
   #define ArgType(n)   (cargp[n].dword)

   /*
    * Value field of n-th argument.
    */
   #define ArgVal(n)    (cargp[n].vword.integr)

   /*
    * Specific arguments.
    */
   #define Arg0 (cargp[0])
   #define Arg1 (cargp[1])
   #define Arg2 (cargp[2])
   #define Arg3 (cargp[3])
   #define Arg4 (cargp[4])
   #define Arg5 (cargp[5])
   #define Arg6 (cargp[6])
   #define Arg7 (cargp[7])
   #define Arg8 (cargp[8])

   /*
    * Miscellaneous macro definitions.
    */

   #ifdef MultiProgram
      #define handlers  (curpstate->Handlers)
      #define kywd_err  (curpstate->Kywd_err)
      #define kywd_prog  (curpstate->Kywd_prog)
      #define k_eventcode (curpstate->eventcode)
      #define k_eventsource (curpstate->eventsource)
      #define k_eventvalue (curpstate->eventval)
      #define kywd_trc  (curpstate->Kywd_trc)
      #define mainhead (curpstate->Mainhead)
      #define code (curpstate->Code)
      #define endcode (curpstate->Ecode)
      #define records (curpstate->Records)
      #define ftabp (curpstate->Ftabp)
      #ifdef FieldTableCompression
         #define ftabwidth (curpstate->Ftabwidth)
         #define foffwidth (curpstate->Foffwidth)
         #define ftabcp (curpstate->Ftabcp)
         #define ftabsp (curpstate->Ftabsp)
         #define focp (curpstate->Focp)
         #define fosp (curpstate->Fosp)
         #define fo (curpstate->Fo)
         #define bm (curpstate->Bm)
      #endif                            /* FieldTableCompression */
      #define fnames (curpstate->Fnames)
      #define efnames (curpstate->Efnames)
      #define globals (curpstate->Globals)
      #define eglobals (curpstate->Eglobals)
      #define gnames (curpstate->Gnames)
      #define egnames (curpstate->Egnames)
      #define statics (curpstate->Statics)
      #define estatics (curpstate->Estatics)
      #define n_globals (curpstate->NGlobals)
      #define n_statics (curpstate->NStatics)
      #define strcons (curpstate->Strcons)
      #define filenms (curpstate->Filenms)
      #define efilenms (curpstate->Efilenms)
      #define ilines (curpstate->Ilines)
      #define elines (curpstate->Elines)
      #define current_line_ptr (curpstate->Current_line_ptr)

/*#ifdef Graphics*/
         #define amperX   (curpstate->AmperX)
         #define amperY   (curpstate->AmperY)
         #define amperRow (curpstate->AmperRow)
         #define amperCol (curpstate->AmperCol)
         #define amperInterval (curpstate->AmperInterval)
         #define lastEventWin (curpstate->LastEventWin)
         #define lastEvFWidth (curpstate->LastEvFWidth)
         #define lastEvLeading (curpstate->LastEvLeading)
         #define lastEvAscent (curpstate->LastEvAscent)
         #define kywd_xwin (curpstate->Kywd_xwin)
         #define xmod_control (curpstate->Xmod_Control)
         #define xmod_shift (curpstate->Xmod_Shift)
         #define xmod_meta (curpstate->Xmod_Meta)
      #ifdef Graphics3D
         #define amperPick   (curpstate->AmperPick)
      #endif                            /* Graphics3D */
/*#endif*/                              /* Graphics */

      #define coexp_ser (curpstate->Coexp_ser)
      #define list_ser  (curpstate->List_ser)
      #define intern_list_ser  (curpstate->Intern_list_ser)
#ifdef PatternType
      #define pat_ser  (curpstate->Pat_ser)
#endif                                  /* PatternType */
      #define set_ser   (curpstate->Set_ser)
      #define table_ser (curpstate->Table_ser)
#endif                                  /* MultiProgram */
#endif                                  /* COMPILER */

#ifdef MultiProgram
      #define curstring (curpstate->stringregion)
      #define curblock  (curpstate->blockregion)

      #define coll_tot  (curpstate->colltot)
      #define coll_stat (curpstate->collstat)
      #define coll_str  (curpstate->collstr)
      #define coll_blk  (curpstate->collblk)

#ifdef Concurrent
      /* coexpr local*/
      #define lastop    (curtstate_ce->Lastop)
      #define lastopnd  (curtstate_ce->Lastopnd)
#else
      /* thread local*/
      #define lastop    (curtstate->Lastop)
      #define lastopnd  (curtstate->Lastopnd)
#endif                                  /* Concurrent */
#endif                                  /* MultiProgram */

#ifdef MultiProgram
      #define field_argp (curtstate->Field_argp)
      #define xargp     (curtstate->Xargp)
      #define xnargs    (curtstate->Xnargs)
      #ifdef PosixFns
         #define amperErrno (curtstate->AmperErrno)
      #endif

      #define line_num  (curtstate->Line_num)
#endif                                  /* MultiProgram */

#if defined(MultiProgram) || ConcurrentCOMPILER
      #define glbl_argp      (curtstate->Glbl_argp)

      #define kywd_pos       (curtstate->Kywd_pos)
      #define k_subject      (curtstate->ksub)
      #define kywd_ran       (curtstate->Kywd_ran)
      #define value_tmp      (curtstate->Value_tmp)

      #define k_current     (curtstate->K_current)
      #define k_errornumber (curtstate->K_errornumber)
      #define k_level       (curtstate->K_level)
      #define k_errortext   (curtstate->K_errortext)
      #define k_errorvalue  (curtstate->K_errorvalue)
#ifdef PatternType
      #define k_patindex    (curtstate->K_patindex)
#endif
      #define have_errval   (curtstate->Have_errval)
      #define t_errornumber (curtstate->T_errornumber)
      #define t_have_val    (curtstate->T_have_val)
      #define t_errorvalue  (curtstate->T_errorvalue)
      #define column    (curtstate->Column)
      #define lastline  (curtstate->Lastline)
      #define lastcol   (curtstate->Lastcol)

#ifdef Concurrent
      #define tend        (curtstate_ce->es_tend)
      #define pfp         (curtstate_ce->es_pfp)
#if !ConcurrentCOMPILER
      #define efp         (curtstate_ce->es_efp)
      #define gfp         (curtstate_ce->es_gfp)
      #define ipc         (curtstate_ce->es_ipc)
      #define oldipc      (curtstate_ce->es_oldipc)
      #define sp          (curtstate_ce->es_sp)
      #define ilevel      (curtstate_ce->es_ilevel)

      #define eret_tmp       (curtstate->Eret_tmp)
#endif                                  /* ConcurrentCOMPILER */

#ifndef StackCheck
      #define stack          (curtstate->Stack)
      #define stackend       (curtstate->Stackend)
#endif                                  /* StackCheck */

#ifdef PosixFns
      #define savedbuf       (curtstate->Savedbuf)
      #define nsaved         (curtstate->Nsaved)
#endif                                  /* PosixFns */

#endif                                  /* Concurrent */

#if !ConcurrentCOMPILER
      #define k_main        (curpstate->K_main)
      #define k_errout      (curpstate->K_errout)
      #define k_input       (curpstate->K_input)
      #define k_output      (curpstate->K_output)

      #define longest_dr    (curpstate->Longest_dr)
      #define dr_arrays     (curpstate->Dr_arrays)

#ifdef Arrays
      #define cprealarray   (curpstate->Cprealarray)
      #define cpintarray    (curpstate->Cpintarray)
#endif                                  /* Arrays */
      #define cplist        (curpstate->Cplist)
      #define cpset         (curpstate->Cpset)
      #define cptable       (curpstate->Cptable)
      #define EVStrAlc      (curpstate->EVstralc)
      #define interp        (curpstate->Interp)
      #define cnv_cset      (curpstate->Cnvcset)
      #define cnv_int       (curpstate->Cnvint)
      #define cnv_real      (curpstate->Cnvreal)
      #define cnv_str       (curpstate->Cnvstr)
      #define cnv_tcset     (curpstate->Cnvtcset)
      #define cnv_tstr      (curpstate->Cnvtstr)
      #define deref         (curpstate->Deref)
      #define alcbignum     (curpstate->Alcbignum)
      #define alccset       (curpstate->Alccset)
      #define alcfile       (curpstate->Alcfile)
      #define alchash       (curpstate->Alchash)
      #define alcsegment    (curpstate->Alcsegment)
#ifdef PatternType
      #define alcpattern    (curpstate->Alcpattern)
      #define alcpelem      (curpstate->Alcpelem)
      #define cnv_pattern   (curpstate->Cnvpattern)
      #define internal_match (curpstate->Internalmatch)
#endif                                  /* PatternType */
      #define alclist_raw   (curpstate->Alclist_raw)
      #define alclist       (curpstate->Alclist)
      #define alclstb       (curpstate->Alclstb)
      #define alcreal       (curpstate->Alcreal)
      #define alcrecd       (curpstate->Alcrecd)
      #define alcrefresh    (curpstate->Alcrefresh)
      #define alcselem      (curpstate->Alcselem)
      #define alcstr        (curpstate->Alcstr)
      #define alcsubs       (curpstate->Alcsubs)
      #define alctelem      (curpstate->Alctelem)
      #define alctvtbl      (curpstate->Alctvtbl)
      #define deallocate    (curpstate->Deallocate)
      #define reserve       (curpstate->Reserve)
#endif                                  /* ConcurrentCOMPILER */

#ifdef Concurrent
#if !ConcurrentCOMPILER
      #define ENTERPSTATE(p) if (((p)!=NULL)) { curpstate = (p); }
#endif                                  /* ConcurrentCOMPILER */
#else                                   /* Concurrent */
      #define ENTERPSTATE(p) if (((p)!=NULL)) { curpstate = (p); curtstate=p->tstate;}
#endif                                  /* Concurrent */

#else                                   /* MultiProgram */
 #define ENTERPSTATE(p)
#endif                                  /* MultiProgram */


#if COMPILER || !defined(MultiProgram)
   #define EVStrAlc(n)
#endif

/*
 * Constants controlling expression evaluation.
 */
#if COMPILER
   #define A_Resume     -1      /* expression failed: resume a generator */
   #define A_Continue   -2      /* expression returned: continue execution */
   #define A_FallThru   -3      /* body function: fell through end of code */
   #define A_Coact      1       /* co-expression activation */
   #define A_Coret      2       /* co-expression return */
   #define A_Cofail     3       /* co-expression failure */
#else                                   /* COMPILER */
   #define A_Resume     1       /* routine failed */
   #define A_Pret_uw    2       /* interp unwind for Op_Pret */
   #define A_Unmark_uw  3       /* interp unwind for Op_Unmark */
   #define A_Pfail_uw   4       /* interp unwind for Op_Pfail */
   #define A_Lsusp_uw   5       /* interp unwind for Op_Lsusp */
   #define A_Eret_uw    6       /* interp unwind for Op_Eret */
   #define A_Continue   7       /* routine returned */
   #define A_Coact      8       /* co-expression activated */
   #define A_Coret      9       /* co-expression returned */
   #define A_Cofail     10      /* co-expression failed */
   #ifdef MultiProgram
      #define A_MTEvent 11      /* multiProgram event */
   #endif                               /* MultiProgram */
   #ifdef PosixFns
      #define   A_Trapret       12      /* Return from stub  */
      #define   A_Trapfail      13      /* Fail from stub  */
   #endif                               /* PosixFns */
   #ifdef SoftThreads
      #define A_Coschedule      14      /* co-expression schedule */
   #endif                               /* SoftThreads */
#endif                                  /* COMPILER */

#ifdef SoftThreads
#define SOFT_THREADS_SIZE 16
#define SOFT_THREADS_TSLICE 500
#endif                          /* SoftThreads */

/*
 * Address of word containing cset bit b (c is a struct descrip of type Cset).
 */
#define CsetPtr(b,c)    (BlkD(c,Cset)->bits + (((b)&0377) >> LogIntBits))

#if MSDOS
      #define ptr2word(x) (uword)x
      #define word2ptr(x) ((char *)x)
#endif                                  /* MSDOS */

#if NT
#ifndef S_ISDIR
#define S_ISDIR(mod) ((mod) & _S_IFDIR)
#endif                                  /* no S_ISDIR */
#endif                                  /* NT */

#ifdef ISQL                             /* ODBC support */

   /*
    * Icon/ODBC error codes
    */
   #define ODBC_ERR_SZ            19

   #define NOT_ODBC_FILE_ERR    1100
   #define FREE_STMT_ERR        1101
   #define DISCONNECT_ERR       1102
   #define FREE_CONNECT_ERR     1103
   #define ALLOC_STMT_ERR       1104
   #define ALLOC_ENV_ERR        1105
   #define ALLOC_CONNECT_ERR    1106
   #define CONNECT_ERR          1107
   #define EXEC_DIRECT_ERR      1108
   #define CLOSE_CURSOR_ERR     1109
   #define COLUMNS_ERR          1110
   #define PRIMARY_KEYS_ERR     1111
   #define NUM_RESULT_COLS_ERR  1112
   #define DESCRIBE_COL_ERR     1113
   #define FETCH_ERR            1114
   #define TABLES_ERR           1115
   #define NO_KEY_DEFINED_ERR   1116
   #define TOO_MANY_KEYS_ERR    1117
   #define KEY_MISSING_ERR      1118

#endif                                  /* ISQL */


/*
 * flags for ConsoleFlags
 */
/* I/O redirection flags */
#define StdOutRedirect        1
#define StdErrRedirect        2
#define StdInRedirect         4
#define OutputToBuf           8

#define SEM_WAIT(semptr) while (sem_wait(semptr) != 0 ) { \
        if (errno==EINVAL) syserr("invalid semaphore"); \
        else if (errno != EINTR) {perror("sem_wait()"); syserr("sem_wait error");} }

#ifndef NamedSemaphores
#define SEM_CLOSE(sem_s) sem_destroy(sem_s)
#else
#define SEM_CLOSE(sem_s) sem_close(sem_s)
#endif /* NamedSemaphores */

#define FUNC_MUTEX_LOCK         1
#define FUNC_MUTEX_TRYLOCK      2
#define FUNC_MUTEX_UNLOCK       3
#define FUNC_MUTEX_INIT         4
#define FUNC_MUTEX_DESTROY      5
#define FUNC_COND_WAIT          6
#define FUNC_COND_INIT          7
#define FUNC_COND_DESTROY       8
#define FUNC_COND_TIMEDWAIT     9
#define FUNC_COND_SIGNAL        10
#define FUNC_THREAD_CREATE      11
#define FUNC_THREAD_JOIN        12
#define FUNC_SEM_OPEN           13
#define FUNC_SEM_INIT           14

#ifdef PthreadCoswitch
#define THREAD_CREATE(cp, t_stksize, msg)                               \
  do {                                                                  \
    int retval;                                                         \
    if (t_stksize){                                                     \
      pthread_attr_t attr;                                              \
      pthread_attr_init(&attr);                                         \
      pthread_attr_setstacksize(&attr, t_stksize);                      \
      retval = pthread_create(&cp->thread, &attr, nctramp, cp);         \
    }                                                                   \
    else                                                                \
      retval = pthread_create(&cp->thread, NULL, nctramp, cp);          \
    if (retval) handle_thread_error(retval, FUNC_THREAD_CREATE, msg);   \
  } while (0)

#define THREAD_JOIN( thrd, opt ) do { int retval;               \
        if ((retval=pthread_join(thrd, opt)) != 0)              \
          handle_thread_error(retval, FUNC_THREAD_JOIN, NULL);  \
      } while (0)

#define CREATE_CE_THREAD(cp, t_stksize, msg) do {                       \
        THREAD_CREATE(cp, t_stksize, msg);                              \
        cp->alive = 1;                                                  \
        cp->have_thread = 1;                                            \
        SET_FLAG(cp->status, Ts_Attached);                              \
        SET_FLAG(cp->status, Ts_Posix);                                 \
        /*if (!(nstat & Ts_Sync ))pthread_detach(&new->thread);*/       \
      } while (0)
#else                                  /* PthreadCoswitch */
#define THREAD_CREATE(cp, t_stksize, msg)
#define THREAD_JOIN(thrd, opt)
#define CREATE_CE_THREAD(cp, t_stksize, msg)
#endif                                  /* PthreadCoswitch */

#ifdef Concurrent

   #define MTX_OP_ASTR          0
   #define MTX_OP_AREAL         1
   #define MTX_OP_ACSET         2
   #define MTX_OP_ASTATIC       3
   #define MTX_OP_AGLOBAL       4
   #define MTX_OP_AMARK         5
   #define MTX_OP_AGOTO         6

   #define MTX_LIST_SER         7
   #define MTX_COEXP_SER        8
   #define MTX_SET_SER          9
   #define MTX_TABLE_SER        10
   #define MTX_PAT_SER          11

   #define MTX_STRHEAP          12
   #define MTX_BLKHEAP          13

   #define MTX_TLS_CHAIN        14

   #define MTX_CURFILE_HANDLE   15

   #define MTX_SEGVTRAP_N       16

   #define MTX_DR_TBL           17

   #define MTX_SOCK_MAP         18

   #define MTX_THREADCONTROL    19
   #define MTX_NARTHREADS       20
   #define MTX_COND_TC          21

   #define MTX_HANDLERS         22

   #define MTX_ALCNUM           23

   #define MTX_PUBLICSTRHEAP    24
   #define MTX_PUBLICBLKHEAP    25

   #define MTX_ROOT_FILEPIDS    26

   #define MTX_PATIMG_FUNCARR   27

   #define MTX_STKLIST          28
   #define MTX_POLLEVENT        29
   #define MTX_RECID            30

   #define MTX_NOMTEVENTS       31

   #define MTX_MUTEXES          32
   #define MTX_CONDVARS         33

   #define MTX_STRINGTOTAL      34
   #define MTX_BLOCKTOTAL       35
   #define MTX_COLL             36


   /* This should be the last mutex, becasue it has special initialization*/
   #define MTX_INITIAL          37


   /* total is:  */
   #define NUM_STATIC_MUTEXES   38

   /* used by wait4GC function*/


   #define TC_NONE -1

   #define TC_ANSWERCALL 0

   #define TC_CALLTHREADS 1
   #define TC_WAKEUPCALL 2
   #define TC_STOPALLTHREADS 3
   #define TC_KILLALLTHREADS 4

/*
 *  Lock mutex mtx. msg is a string name that refers to mtx, useful for
 *  error tracing.
 */

#define MUTEX_LOCK( mtx, msg)                                           \
      do                                                                \
        if (is_concurrent) {                                            \
          int __rv;                                                     \
          if ((__rv=pthread_mutex_lock(&(mtx))) != 0)                   \
            handle_thread_error(__rv, FUNC_MUTEX_LOCK, msg);            \
        }                                                               \
      while (0)

#define MUTEX_UNLOCK( mtx, msg)                                         \
      do                                                                \
        if (is_concurrent) {                                            \
          int __rv;                                                     \
          if ((__rv=pthread_mutex_unlock(&(mtx))) != 0)                 \
            handle_thread_error(__rv, FUNC_MUTEX_UNLOCK, msg);          \
        }                                                               \
      while (0)

#define MUTEX_TRYLOCK(mtx, isbusy, msg)                                 \
      do                                                                \
        if (is_concurrent) {                                            \
          if ((isbusy=pthread_mutex_trylock(&(mtx))) != 0) {    \
            if (isbusy != EBUSY){                                       \
              handle_thread_error(isbusy, FUNC_MUTEX_TRYLOCK, msg);     \
              isbusy = 0;                                               \
            }                                                           \
          }                                                             \
        } else isbusy = 0;                                              \
      while (0)

#define MUTEX_INIT( mtx, attr )                                 \
      do { int __rv;                                            \
        if ((__rv=pthread_mutex_init(&(mtx), attr)) != 0)       \
          handle_thread_error(__rv, FUNC_MUTEX_INIT, NULL);     \
      } while (0)

/*
 *  Lock mutex mutexes[mtx].
 */


#define MUTEX_INITID( mtx, attr )                                       \
      do {                                                              \
        int __rv;                                                       \
        mutexes[mtx] = malloc(sizeof(pthread_mutex_t));                 \
        if ((__rv=pthread_mutex_init(mutexes[mtx], attr)) != 0) \
          handle_thread_error(__rv, FUNC_MUTEX_INIT, NULL);             \
      } while (0)

#define MUTEXID(mtx) mutexes[mtx]

//BASIC: don't define __rv or check is_concurrent, enclosing code will do it
#define MUTEX_LOCKID_BASIC(mtx)                                         \
      if ((__rv=pthread_mutex_lock(mutexes[mtx])) != 0)                 \
          handle_thread_error(__rv, FUNC_MUTEX_LOCK, NULL);

#define MUTEX_UNLOCKID_BASIC(mtx)                                       \
          if ((__rv=pthread_mutex_unlock(mutexes[mtx])) != 0)           \
            handle_thread_error(__rv, FUNC_MUTEX_UNLOCK, NULL);


#define MUTEX_TRYLOCKID_BASIC(mtx, isbusy)                              \
      if ((isbusy=pthread_mutex_trylock(mutexes[mtx])) != 0) {          \
        if (isbusy != EBUSY){                                           \
          handle_thread_error(isbusy, FUNC_MUTEX_TRYLOCK, NULL);        \
          isbusy = 0;                                                   \
        }                                                               \
      }

// AWLAYS: Always lock the mutex, don't check is_concurrent
#define MUTEX_LOCKID_ALWAYS(mtx)                                        \
      do {                                                              \
        int __rv;                                                       \
        MUTEX_LOCKID_BASIC(mtx)                                         \
      } while (0)

#define MUTEX_UNLOCKID_ALWAYS(mtx)                                      \
      do {                                                              \
          int __rv;                                                     \
          MUTEX_UNLOCKID_BASIC(mtx);                                    \
      } while (0)

#define MUTEX_LOCKID(mtx) do if ( is_concurrent )  MUTEX_LOCKID_ALWAYS(mtx);  while (0)

#define MUTEX_UNLOCKID(mtx) do if ( is_concurrent )  MUTEX_UNLOCKID_ALWAYS(mtx);  while (0)

#define MUTEX_TRYLOCKID(mtx, isbusy)         \
      do                                     \
        if (is_concurrent) {                 \
          MUTEX_TRYLOCKID_BASIC(mtx, isbusy) \
            }  else isbusy = 0;              \
      while (0)

#define INC_LOCKID(x, mtx) do {MUTEX_LOCKID(mtx);  x++; MUTEX_UNLOCKID(mtx);} while (0)
#define DEC_LOCKID(x, mtx) do {MUTEX_LOCKID(mtx);  x--; MUTEX_UNLOCKID(mtx);} while (0)

#define INC_NARTHREADS_CONTROLLED_BASIC                 \
          MUTEX_LOCKID_BASIC(MTX_THREADCONTROL);        \
          MUTEX_LOCKID_BASIC(MTX_NARTHREADS);           \
          NARthreads++;                                 \
          MUTEX_UNLOCKID_BASIC(MTX_NARTHREADS);         \
          MUTEX_UNLOCKID_BASIC(MTX_THREADCONTROL);

#define INC_NARTHREADS_CONTROLLED_ALWAYS                \
      do {                                              \
        int __rv;                                       \
        INC_NARTHREADS_CONTROLLED_BASIC;                \
      } while (0)

#define INC_NARTHREADS_CONTROLLED                       \
      do                                                \
        if (is_concurrent) {                            \
          int __rv;                                     \
          INC_NARTHREADS_CONTROLLED_BASIC;              \
        }                                               \
        else                                            \
          NARthreads++;                                 \
      while (0)

#define DEC_NARTHREADS_BASIC                            \
          MUTEX_LOCKID_BASIC(MTX_NARTHREADS);           \
          NARthreads--;                                 \
          MUTEX_UNLOCKID_BASIC(MTX_NARTHREADS);

#define DEC_NARTHREADS_ALWAYS                           \
      do {                                              \
        int __rv;                                       \
        DEC_NARTHREADS_BASIC;                           \
      } while (0)


#define DEC_NARTHREADS                                  \
      do {                                              \
        if (is_concurrent) {                            \
          int __rv;                                     \
          DEC_NARTHREADS_BASIC;                         \
        }                                               \
        else                                            \
          NARthreads--;                                 \
      } while (0)

#define MUTEX_LOCKID_CONTROLLED_ALWAYS(mtx)             \
      do {                                              \
          int __rv;                                     \
          MUTEX_TRYLOCKID_BASIC(mtx, __rv);             \
          if (__rv==EBUSY){                             \
            DEC_NARTHREADS_BASIC;                       \
            MUTEX_LOCKID_BASIC(mtx);                    \
            INC_NARTHREADS_CONTROLLED_BASIC;            \
          }                                             \
      } while (0)

#define MUTEX_LOCKID_CONTROLLED(mtx)            \
      do                                        \
        if (is_concurrent)                      \
          MUTEX_LOCKID_CONTROLLED_ALWAYS(mtx);  \
      while (0)

#define MUTEX_LOCK_CONTROLLED(mtx, msg)         \
      do {                                      \
        if (is_concurrent) {                    \
          MUTEX_LOCKID_CONTROLLED_ALWAYS(mtx)   \
          int __rv;                             \
          MUTEX_TRYLOCK(mtx, __rv, msg);        \
          if (__rv==EBUSY){                     \
            DEC_NARTHREADS_BASIC;               \
            MUTEX_LOCK(mtx, msg);               \
            INC_NARTHREADS_CONTROLLED_BASIC;    \
          }                                     \
        }                                       \
      } while (0)

/********** block macros *************/
#define MUTEX_LOCKBLK(bp, msg) \
      do if (bp->shared) {MUTEX_LOCKID_ALWAYS(bp->mutexid);} while (0)

#define MUTEX_LOCKBLK_CONTROLLED(bp, msg) \
      do if (bp->shared) {MUTEX_LOCKID_CONTROLLED_ALWAYS(bp->mutexid);} while (0)

#define MUTEX_UNLOCKBLK(bp, msg) \
      do if (bp->shared) {MUTEX_UNLOCKID_ALWAYS(bp->mutexid);} while (0)

#define MUTEX_TRYLOCKBLK(bp, isbusy, msg) \
      do if (bp->shared) {MUTEX_TRYLOCKID_BASIC(bp->mutexid, isbusy);} while (0)


/* assume that the block is shared! */
#define MUTEX_LOCKBLK_NOCHK(bp, msg) \
   MUTEX_LOCKID(bp->mutexid)

#define MUTEX_LOCKBLK_CONTROLLED_NOCHK(bp, msg) \
   MUTEX_LOCKID_CONTROLLED(bp->mutexid)


#define MUTEX_UNLOCKBLK_NOCHK(bp, msg) \
   MUTEX_UNLOCKID(bp->mutexid)

#define MUTEX_TRYLOCKBLK_NOCHK(bp, isbusy, msg) \
   MUTEX_TRYLOCKID(bp->mutexid, isbusy)


#define C_PUT_PROTECTED(L, v)                                   \
      do {                                                      \
        MUTEX_LOCKBLK(BlkD(L, List));                           \
        c_put(&L, &v); MUTEX_UNLOCKBLK(BlkD(L, List));          \
      } while (0)

#define MUTEX_INITBLK(bp)                       \
      do {                                      \
        if (!bp->shared){                       \
          bp->mutexid = get_mutex(&rmtx_attr);  \
          bp->shared = 1;                       \
        }                                       \
      } while (0)

#define MUTEX_INITBLKID(bp, mtx)                \
      do {                                      \
        if (!bp->shared){                       \
          bp->mutexid = mtx;                    \
          bp->shared = 1;                       \
        }                                       \
      } while (0)

#define MUTEX_GETBLK(bp) mutexes[bp->mutexid]

#define CV_GETULLTBLK(bp) condvars[bp->cvfull]
#define CV_GETULLTBLK(bp) condvars[bp->cvfull]

#define CV_INITBLK(bp)                          \
      do {                                      \
        MUTEX_INITBLK(bp);                      \
        bp->cvfull = get_cv(bp->mutexid);       \
        bp->cvempty = get_cv(bp->mutexid);      \
        bp->full = 0;                           \
        bp->empty = 0;                          \
        bp->max = 1024;                         \
      } while (0)

#define CV_WAIT_ON_EXPR(expr, cv, mtxid)                                \
  while (expr) pthread_cond_wait(cv, MUTEXID(mtxid));

#define CV_WAIT(cv, mtxid)                                              \
      do {                                                              \
        int __rv;                                                       \
        if ((__rv=pthread_cond_wait(cv, MUTEXID(mtxid)))<0 ){           \
          fprintf(stderr, "condition variable wait failure %d\n", __rv); \
          exit(-1);                                                     \
        }                                                               \
      } while (0)

#define CV_INIT(cv, msg)                                                \
      do{                                                               \
        int __rv;                                                       \
        if ((__rv=pthread_cond_init(cv, NULL))<0 ){                     \
          handle_thread_error(__rv, FUNC_COND_INIT, msg);               \
        }                                                               \
      } while (0)

#define CV_WAIT_FULLBLK(bp) \
    pthread_cond_wait(condvars[bp->cvfull], MUTEX_GETBLK(bp));

#define CV_WAIT_EMPTYBLK(bp) \
    pthread_cond_wait(condvars[bp->cvempty], MUTEX_GETBLK(bp));

#define CV_SIGNAL_FULLBLK(bp) if (bp->full) { \
    pthread_cond_signal(condvars[bp->cvfull]);}

#define CV_SIGNAL_EMPTYBLK(bp) if (bp->empty) { \
    pthread_cond_signal(condvars[bp->cvempty]);}

#define CV_TIMEDWAIT_EMPTYBLK(bp, t)\
  pthread_cond_timedwait(condvars[bp->cvempty], MUTEX_GETBLK(bp), &t);

#define SUSPEND_THREADS() thread_control(TC_STOPALLTHREADS)
#define RESUME_THREADS() thread_control(TC_WAKEUPCALL)

#define DO_COLLECT(region) do { \
   SUSPEND_THREADS(); \
   collect(region); \
   RESUME_THREADS(); \
   } while(0)

#else                                   /* Concurrent */

#define MUTEX_INIT(mtx, attr)
#define MUTEX_INITID(mtx, attr)
#define MUTEXID(mtx)
#define MUTEX_LOCK(mtx, msg)
#define MUTEX_UNLOCK(mtx, msg)
#define MUTEX_TRYLOCK(mtx, isbusy, msg)

#define MUTEX_LOCKID(mtx)
#define MUTEX_UNLOCKID(mtx)
#define MUTEX_TRYLOCKID(mtx, isbusy)

#define MUTEX_LOCKID_ALWAYS(mtx)
#define MUTEX_UNLOCKID_ALWAYS(mtx)

#define MUTEX_LOCK_CONTROLLED(mtx, msg)
#define MUTEX_LOCKID_CONTROLLED(mtx)
#define INC_LOCKID(x, mtx)
#define DEC_LOCKID(x, mtx)
#define INC_NARTHREADS_CONTROLLED
#define DEC_NARTHREADS
#define INC_NARTHREADS_CONTROLLED_ALWAYS
#define DEC_NARTHREADS_CONTROLLED_ALWAYS

#define MUTEX_INITBLK(bp)
#define MUTEX_INITBLKID(bp, mtx)
#define MUTEX_LOCKBLK(bp, msg)
#define MUTEX_LOCKBLK_CONTROLLED(bp, msg)
#define MUTEX_LOCKBLK_NOCHK(bp, msg)
#define MUTEX_LOCKBLK_CONTROLLED_NOCHK(bp, msg)
#define MUTEX_UNLOCKBLK(bp, msg)
#define MUTEX_TRYLOCKBLK(bp, isbusy, msg)
#define C_PUT_PROTECTED(L, v)
#define CV_INITBLK(bp)
#define MUTEX_GETBLK(bp)
#define CV_GETULLTBLK(bp)
#define CV_GETULLTBLK(bp)

#define CV_WAIT_FULLBLK(bp)
#define CV_WAIT(cv, mtxid)

#define CV_WAIT_EMPTYBLK(bp)
#define CV_SIGNAL_FULLBLK(bp)

#define CV_SIGNAL_EMPTYBLK(bp)

#define CV_TIMEDWAIT_EMPTYBLK(bp, t)

#define SUSPEND_THREADS()
#define RESUME_THREADS()

#define DO_COLLECT(region) collect(region)

#define CV_WAIT_ON_EXPR(expr, cv, mtxid)

#define CV_INIT(cv, msg)

#define MUTEX_LOCKBLK_NOCHK(bp, msg)

#define MUTEX_UNLOCKBLK_NOCHK(bp, msg)

#define MUTEX_TRYLOCKBLK_NOCHK(bp, isbusy, msg)

#endif                                  /* Concurrent */

#ifdef LargeInts
/* determine the number of words needed for a bignum block with n digits */

#define LrgNeed(n)   ( ((sizeof(struct b_bignum) + ((n) - 1) * sizeof(DIGIT)) \
                       + WordSize - 1) & -WordSize )
#endif                                  /* LargeInts */


#define PRINT_TEXTURE_INFO(wt, msg)                     \
  do {\
  printf("%s\n", msg); \
  printf("refcount = %d", (wt)->refcount);      \
  printf("\ttexName  = %d", (wt)->texName);     \
  printf("\ttextype  = %d", (wt)->textype);     \
  printf("\tserial   = %d", (wt)->serial);      \
  printf("\twidth    = %d", (wt)->width);       \
  printf("\theight   = %d\n", (wt)->height);    \
  } while (0)


#define REPORT_OPENGL_ERROR(msg) \
 do { \
  int rc; \
   rc = glGetError(); \
   switch (rc){ \
 case GL_NO_ERROR : printf("%s NO GL ERROR\n", msg); break; \
 case GL_INVALID_ENUM : printf("%s GL ERROR: invalid enum\n", msg); break; \
 case GL_INVALID_OPERATION : printf("%s GL ERROR: invalid op\n", msg); break; \
 default: printf("%s GL ERROR: %d\n", msg, rc); \
    } \
 } while (0)

#ifdef Concurrent
#if ConcurrentCOMPILER
      #define public_stringregion  (Public_stringregion)
      #define public_blockregion  (Public_blockregion)
      #define coexpr_fnc (curtstate->Coexpr_fnc)
#else
      #define public_stringregion (curpstate->Public_stringregion)
      #define public_blockregion (curpstate->Public_blockregion)
#endif                                  /* ConcurrentCOMPILER */
      #define strtotal          (curtstate->stringtotal)
      #define blktotal          (curtstate->blocktotal)
#else                                   /* Concurrent */
#ifdef MultiProgram
      #define strtotal  (curpstate->stringtotal)
      #define blktotal  (curpstate->blocktotal)
#endif                                  /* MultiProgram */
#endif                                  /* Concurrent */

/*
 * Rationale for new pattern (element) codes.
 *
 * Append bottom 4 bits onto existing codes in order to encode their suffix.
 * There are apparently 5 extra values that can be associated with each family
 * that are not part of one of the suffixes, values 11-15.
 *
 * xxxx0000 ==  0 == not a code, a family
 * xxxx0001 ==  1 == not used
 * xxxx0010 ==  2 == _VP
 * xxxx0011 ==  3 == _CH
 * xxxx0100 ==  4 == _CS
 * xxxx0101 ==  5 == _Nat
 * xxxx0110 ==  6 == _NF
 * xxxx0111 ==  7 == _NP
 * xxxx1000 ==  8 == _VF
 * xxxx1001 ==  9 == _MF
 * xxxx1010 == 10 == _NMF
 *
 * The purpose of all this is so that code that analyzes and categorizes
 * pattern element codes, particularly debuggers and the like, can trivially
 * extract base function (family) and suffix, without lots of comparisons
 * and checks.
 *
 * Families. The next four bits will denote families:
 * 0000xxxx == Any    = 0
 * 0001xxxx == Break  = 16
 * 0010xxxx == Breakx = 32
 * 0011xxxx == NotAny = 48
 * 0100xxxx == NSpan  = 64
 * 0101xxxx == Span   = 80
 * 0110xxxx == Len    = 96
 * 0111xxxx == RPos   = 112
 * 1000xxxx == Pos    = 128
 * 1001xxxx == RTab   = 144
 * 1010xxxx == Tab    = 160
 * 1011xxxx == Arbno  = 176
 * 1100xxxx == String = 192
 *
 * According to this scheme, 207 or so is the highest assigned family-based
 * numbers. Numbers that are not part of a family are either a multiple of
 * 16 (+ 1) or else 208+.
 */
#ifdef PatternType
#define   PC_Arb_Y     208
#define   PC_Assign    209
#define   PC_Bal       210
#define   PC_BreakX_X   43
#define   PC_Abort     211
#define   PC_EOP       212
#define   PC_Fail      213
#define   PC_Fence     214
#define   PC_Fence_X   215
#define   PC_Fence_Y   216
#define   PC_R_Enter   217
#define   PC_R_Remove  218
#define   PC_R_Restore 219
#define   PC_Rest      220
#define   PC_Succeed   221
#define   PC_Unanchored 222

#define   PC_Alt        223
#define   PC_Arb_X      224
#define   PC_Arbno_S    187
#define   PC_Arbno_X    188

#define   PC_Rpat       225

#define   PC_Pred_Func  226

#define   PC_Assign_Imm  227
#define   PC_Assign_OnM  228

#define   PC_Any_VP        2
#define   PC_Break_VP     18
#define   PC_BreakX_VP    34
#define   PC_NotAny_VP    50
#define   PC_NSpan_VP     66
#define   PC_Span_VP      82
#define   PC_String_VP   194

#define   PC_Write_Imm   229
#define   PC_Write_OnM   230

#define   PC_Null        231
#define   PC_String      192

#define   PC_Setcur      232

#define   PC_Any_CH        3
#define   PC_Break_CH     19
#define   PC_BreakX_CH    35
#define   PC_Char        233
#define   PC_NotAny_CH    51
#define   PC_NSpan_CH     67
#define   PC_Span_CH      83

#define   PC_Any_CS        4
#define   PC_Break_CS     20
#define   PC_BreakX_CS    36
#define   PC_NotAny_CS    52
#define   PC_NSpan_CS     68
#define   PC_Span_CS      84

#define   PC_Arbno_Y     189

#define   PC_Len_Nat     101
#define   PC_Pos_Nat     133
#define   PC_RPos_Nat    117
#define   PC_RTab_Nat    149
#define   PC_Tab_Nat     165

#define   PC_Pos_NF      134
#define   PC_Len_NF      102
#define   PC_RPos_NF     118
#define   PC_RTab_NF     150
#define   PC_Tab_NF      166

#define   PC_Pos_NP      135
#define   PC_Len_NP      103
#define   PC_RPos_NP     119
#define   PC_RTab_NP     151
#define   PC_Tab_NP      167

#define   PC_Any_VF      8
#define   PC_Break_VF    24
#define   PC_BreakX_VF   40
#define   PC_NotAny_VF   56
#define   PC_NSpan_VF    72
#define   PC_Span_VF     88
#define   PC_String_VF  200
#define   PC_Func       234

   /*
    * These constants are added because of the way "unevaluated expressions"
    * are handled in unicon During the pattern construction process pattern
    * elements containing unevaluated expressions contain their string
    * representations. In the procedure pattern_match these string names are
    * resolved to the corresponding variable references.
    */

#define   PC_UNEVALVAR  235

#define   PC_STRINGFUNCCALL 236
#define   PC_BOOLFUNCCALL  237
#define   PC_STRINGMETHODCALL 238
#define   PC_BOOLMETHODCALL  239
#define   PC_String_MF  201
#define   PC_Pred_MF    240 /* suffix but no family? */

#define   PC_Pos_NMF    138
#define   PC_Len_NMF    106
#define   PC_RPos_NMF   122
#define   PC_RTab_NMF   154
#define   PC_Tab_NMF    170
#define   PC_Any_MF     9
#define   PC_Break_MF   25
#define   PC_BreakX_MF  41
#define   PC_NotAny_MF  57
#define   PC_NSpan_MF   73
#define   PC_Span_MF    89

#define   PC_Concat     241

/*
 * Symbols associated with providing detailed pattern images.
 */

/* pattern function and operator names. subscripts into patimg(). */
#define   PF_Any        0
#define   PF_Break      1
#define   PF_BreakX     2
#define   PF_NotAny     3
#define   PF_NSpan      4
#define   PF_Span       5
#define   PF_Len        6
#define   PF_RPos       7
#define   PF_Pos        8
#define   PF_RTab       9
#define   PF_Tab        10
#define   PF_Arbno      11
/* pattern image codes. parameters e.g. to get_patimage(). */
#define   PI_EMPTY      12
#define   PI_FPAREN     13
#define   PI_BPAREN     14
#define   PI_FBRACE     15
#define   PI_BBRACE     16
#define   PI_BQUOTE     17
#define   PI_QUOTE      18
#define   PI_SQUOTE     19
#define   PI_COMMA      20
#define   PI_PERIOD     21
#define   PI_CONCAT     22
#define   PI_ALT        23
#define   PI_ONM        24
#define   PI_IMM        25
#define   PI_SETCUR     26
#define   NUM_PATIMGS   27

/* pattern argument-type codes. argument #2 to arg_image(). */
#define   PT_MF  25
#define   PT_VF 26
#define   PT_VP 27
#define   PT_EVAL 28

#endif                                  /* PatternType */

#define INIT_ADDRINFO_HINTS(_hints, _fam, _sock, _flags, _proto)        \
      do {                                                              \
        memset(&_hints, 0, sizeof(struct addrinfo));                    \
        /* IPv4 or IPv6 or IP */                                        \
        _hints.ai_family = _fam;                                        \
        /* 0=>Any socket */                                             \
        _hints.ai_socktype = _sock;                                     \
        /* wildcard IP +  canonical name */                             \
        _hints.ai_flags = _flags;                                       \
        /* 0=>Any protocol */                                           \
        _hints.ai_protocol = _proto;                                    \
        _hints.ai_canonname = NULL;                                     \
        _hints.ai_addr = NULL;                                          \
        _hints.ai_next = NULL;                                          \
      } while (0)

#define SAFE_strncpy(_dst, _src, _bufsize)      \
      do {                                      \
        strncpy(_dst, _src, _bufsize - 1);      \
        _dst[_bufsize - 1] = '0';               \
      } while (0)

/*
 * Macro definition used by pollevent() to avoid magic numbers
 */
#define POLL_INTERVAL 400

#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 120000
#define vfork fork
#endif
#endif

/****************************************   end ../h/../h/rmacros.h   */


/****************************************  from ../h/../h/rstructs.h:  */

/*
 * Run-time data structures.
 */

/*
 * Structures common to the compiler and interpreter.
 */

/*
 * Run-time error numbers and text.
 */
struct errtab {
   int err_no;                  /* error number */
   char *errmsg;                /* error message */
   };

/*
 * Descriptor
 */

struct descrip {                /* descriptor */
   word dword;                  /*   type field */
   union {
      word integr;              /*   integer value */
#ifdef DescriptorDouble
      double realval;
#endif                          /*   DescriptorDouble */
      char *sptr;               /*   pointer to character string */
      union block *bptr;        /*   pointer to a block */
      dptr descptr;             /*   pointer to a descriptor */
      } vword;
   };

struct sdescrip {
   word length;                 /*   length of string */
   char *string;                /*   pointer to string */
   };

struct si_ {
  char *s;
  int i;
};
typedef struct si_ stringint;
typedef struct si_ *siptr;

/*
 * structure supporting dynamic record types
 */
struct b_proc_list {
   struct b_proc *this;
   struct b_proc_list *next;
};

#ifdef LargeInts
struct b_bignum {               /* large integer block */
   word title;                  /*   T_Lrgint */
   word blksize;                /*   block size */
   word msd, lsd;               /*   most and least significant digits */
   int sign;                    /*   sign; 0 positive, 1 negative */
   DIGIT digits[1];             /*   digits */
   };
#endif                                  /* LargeInts */

#ifndef DescriptorDouble
struct b_real {                 /* real block */
   word title;                  /*   T_Real */
   double realval;              /*   value */
   };
#endif                                  /* DescriptorDouble */

struct b_cset {                 /* cset block */
   word title;                  /*   T_Cset */
   word size;                   /*   size of cset */
   unsigned int bits[CsetSize];         /*   array of bits */
   };

#ifdef Unicode
 /*
  * Unicode string block
  */
struct b_unistr {
   word title;                       /* T_UniStr */
   word size;                        /* size in unicode character units, returned by *s */
   word lcidx_used;                  /* cache: last unicode character index used  */
   word lbidx_used;                  /* cache: last byte index used */
   char bsize;                       /* The number of characters in each cbindex block below,
                                      * k=1, 2,...,32
                                      */
   char encoding;                    /* In case we go beyound UTF-8, for now this field will
                                      * always be set to 1. 0 represents "pure" ASCII
                                      */
   /* char ielemsize; */             /* index element size, maybe inferrable from size */
   char reserved[6];                 /* explicit alighnment to 8-byte */
   union cbindex {                   /* mapping of characters to their byte indicies in sd below */
   char c[16];                       /* for short strings, this in-place table will be used */
   struct sdescrip sdb               /* if size>16, allocate indexes in string region */
   } u;

   /*
    * The actual string data is stored as a conventional string
    */
   struct sdescrip sd;
 };

 /*
  * Unicode cset block
  */
struct b_unicset {
   word title;
   word size;
   char neg;                         /* is this a negation set */
   char reserved[7];                 /* explicit alighnment to 8-byte */
   union block *cset;
   union block *set;
   };
#endif                          /* Unicode */

/*
 * This union was pulled out of struct b_file and made non-anonymous
 * in order to eliminate an error in some version of gcc on amd64.
 */
union f {
   FILE *fp;
#ifdef Graphics
   struct _wbinding *wb;
#endif
#ifdef Messaging
   struct MFile *mf;
#endif               /* Messaging */
#ifdef ISQL
   struct ISQLFile *sqlf;
#endif               /* ISQL */
#ifdef Dbm
   DBM *dbm;
#endif               /* Dbm */
#ifdef Audio
   struct AudioFile *af;
#endif               /* Audio */
#ifdef PseudoPty
     struct ptstruct *pt;
#endif                                  /* PseudoPty */
#if HAVE_LIBSSL
    SSL *ssl;
#endif                                  /* HAVE_LIBSSL */
   int fd;        /*   other int-based file descriptor */
   };

struct b_file {                 /* file block */
   word title;                  /*   T_File */
   union f fd;
   word status;                 /*   file status */
#ifdef Concurrent
   word mutexid;
#endif                          /* Concurrent */
   struct descrip fname;        /*   file name (string qualifier) */
   };

#ifdef ISQL
  struct ISQLFile {             /* SQL file */
    SQLHDBC hdbc;               /* used by open, close, query, fetch */
    SQLHSTMT hstmt;             /* statement handler */
    char *query;                /* SQL query buffer */
    long qsize;                 /* SQL query buffer size */
    char *tablename;
    struct b_proc *proc;        /* current record constructor procedure */
    int refcount;
    struct ISQLFile *previous, *next; /* links, so we can find & free these*/
  };

#endif                                  /* ISQL */

#ifdef Messaging
struct MFile {                  /* messaging file abstraction */
   int flags;                   /* request options */
   int state;                   /* our current action */
   Tp_t *tp;                    /* a libtp handle */
   Tpresponse_t *resp;          /* response from the last request */
   void *data;                  /* for storing extra connection data */
   };

struct Mpoplist {
   int msgnum;
   struct Mpoplist *next;
   struct Mpoplist *prev;
   };
#endif                                  /* Messaging */

struct b_lelem {                /* list-element block */
   word title;                  /*   T_Lelem */
   word blksize;                /*   size of block */
   union block *listprev;       /*   previous list-element block */
   union block *listnext;       /*   next list-element block */
   word nslots;                 /*   total number of slots */
   word first;                  /*   index of first used slot */
   word nused;                  /*   number of used slots */
   struct descrip lslots[1];    /*   array of slots */
   };

struct b_list {                 /* list-header block */
   word title;                  /*   T_List */
   word size;                   /*   current list size */
   word id;                     /*   identification number */
#ifdef Concurrent
   word shared;
   word mutexid;
   word max, full, empty ;
   word cvfull, cvempty;
#endif                          /* Concurrent */
   union block *listhead;       /*   pointer to first list-element block */
   union block *listtail;       /*   pointer to last list-element block */
   };

struct b_intarray {
   word title;                  /* T_Intarray */
   word blksize;                /* size of block */
   union block *listp;          /* pointer to the list block */
   union block *dims;           /* dimension sizes, NULL for 1D */
   word a[1];                   /* true array size == size, above */
   };

struct b_realarray {
   word title;                  /* T_Realarray */
   word blksize;                /* size of block */
   union block *listp;          /* pointer to the list block */
   union block *dims;           /* dimension sizes, NULL for 1D */
   double a[1];                 /* true array size == size, above */
   };

struct b_mask {                 /* mask block, used to access fields across blocks */
   word title;                  /*   T_Table, T_Set, T_List or, T_Record */
   word size;                   /*   size */
   word id;                     /*   identification number */
#ifdef Concurrent
   word shared;
   word mutexid;
#endif                          /* Concurrent */
   };

struct b_proc {                 /* procedure block */
   word title;                  /*   T_Proc */
   word blksize;                /*   size of block */

   #if COMPILER
        union {
           int (*p0)();
           int (*p1d)(dptr);
           int (*p2id)(int, dptr);
           int (*p2dd)(dptr, dptr);
           int (*p3idd)(int, dptr, dptr);
           int (*p4iddc)(int, dptr, dptr, continuation);
         } ccode;
   #else                                /* COMPILER */
      union {                   /*   entry points for */
         uword ioff;            /*     icode as offset */
         pointer icode;         /*     and icode as absolute pointer */
         union {                /*     and C routines */
           int (*p0)();
           int (*p1d)(dptr);
           int (*p2id)(int, dptr);
           int (*p2dd)(dptr, dptr);
           int (*p3idd)(int, dptr, dptr);
           int (*p4iddc)(int, dptr, dptr, continuation);
         } ccode;
      } entryp;
   #endif                               /* COMPILER */

   word nparam;                 /*   number of parameters */
   word ndynam;                 /*   number of dynamic locals */
   word nstatic;                /*   number of static locals */
   word fstatic;                /*   index (in global table) of first static */
   struct descrip pname;        /*   procedure name (string qualifier) */
   struct descrip lnames[1];    /*   list of local names (qualifiers) */
   };

struct b_record {               /* record block */
   word title;                  /*   T_Record */
   word blksize;                /*   size of block */
   word id;                     /*   identification number */
#ifdef Concurrent
   word shared;
   word mutexid;
#endif                          /* Concurrent */
   union block *recdesc;        /*   pointer to record constructor */
   struct descrip fields[1];    /*   fields */
   };

/*
 * Alternate uses for procedure block fields, applied to records.
 */
#define nfields nparam          /* number of fields */
#define recnum nstatic          /* record number */
#define recid fstatic           /* record serial number */
#define recname pname           /* record name */

struct b_selem {                /* set-element block */
   word title;                  /*   T_Selem */
   union block *clink;          /*   hash chain link */
   uword hashnum;               /*   hash number */
   struct descrip setmem;       /*   the element */
   };

/*
 * A set header must be a proper prefix of a table header,
 *  and a set element must be a proper prefix of a table element.
 */
struct b_set {                  /* set-header block */
   word title;                  /*   T_Set */
   word size;                   /*   size of the set */
   word id;                     /*   identification number */
#ifdef Concurrent
   word shared;
   word mutexid;
#endif                          /* Concurrent */
   word mask;                   /*   mask for slot num, equals n slots - 1 */
   struct b_slots *hdir[HSegs]; /*   directory of hash slot segments */
   };

struct b_table {                /* table-header block */
   word title;                  /*   T_Table */
   word size;                   /*   current table size */
   word id;                     /*   identification number */
#ifdef Concurrent
   word shared;
   word mutexid;
#endif                          /* Concurrent */
   word mask;                   /*   mask for slot num, equals n slots - 1 */
   struct b_slots *hdir[HSegs]; /*   directory of hash slot segments */
   struct descrip defvalue;     /*   default table element value */
   };

struct b_slots {                /* set/table hash slots */
   word title;                  /*   T_Slots */
   word blksize;                /*   size of block */
   union block *hslots[HSlots]; /*   array of slots (HSlots * 2^n entries) */
   };

struct b_telem {                /* table-element block */
   word title;                  /*   T_Telem */
   union block *clink;          /*   hash chain link */
   uword hashnum;               /*   for ordering chain */
   struct descrip tref;         /*   entry value */
   struct descrip tval;         /*   assigned value */
   };

struct b_tvsubs {               /* substring trapped variable block */
   word title;                  /*   T_Tvsubs */
   word sslen;                  /*   length of substring */
   word sspos;                  /*   position of substring */
   struct descrip ssvar;        /*   variable that substring is from */
   };

struct b_tvtbl {                /* table element trapped variable block */
   word title;                  /*   T_Tvtbl */
   union block *clink;          /*   pointer to table header block */
   uword hashnum;               /*   hash number */
   struct descrip tref;         /*   entry value */
   };

#ifdef EventMon
struct b_tvmonitored {          /* Monitored variable block */
   word title;                  /*   T_Tvmonitored */
   word cur_actv;               /*   current co-expression activation */
   struct descrip tv;           /*   the variable in the other program */
   };
#endif                          /* EventMon */

struct b_external {             /* external block */
   word title;                  /*   T_External */
   word blksize;                /*   size of block */
   word exdata[1];              /*   words of external data */
   };

struct astkblk {                  /* co-expression activator-stack block */
   int nactivators;               /*   number of valid activator entries in
                                   *    this block */
   struct astkblk *astk_nxt;      /*   next activator block */
   struct actrec {                /*   activator record */
      word acount;                /*     number of calls by this activator */
      struct b_coexpr *activator; /*     the activator itself */
      } arec[ActStkBlkEnts];
   };

#ifdef PatternType
struct b_pattern {            /*Pattern header block*/
    word title;             /*T_Pattern*/
    word id;
    word stck_size;         /* size of stack for pattern history during match*/
    union block * pe;           /*   pattern element */
};

struct b_pelem {                      /* Pattern element block */
    word title;                     /* T_Pelem       */
    word pcode;                     /* Indicates Pattern type*/
    union block * pthen;            /*  Pointer to succeeding pointer element*/
    word index;                     /* posn of pattern elem in pointer chain
                                     * (used in image) */
    word *origin_ipc;               /* where elem was constructed
                                     * (used in debugging) */
    struct descrip parameter;           /*   parameter */
};
#endif                                  /* PatternType */

/*
 * The following "generic link list" structure type is useful for
 * at least the Windows temp file list.
 */
struct b_cons {
   word title;                  /* T_Cons */
   union block *data;
   union block *next;
   };


/*
 * Structure for keeping set/table generator state across a suspension.
 */
struct hgstate {                /* hashed-structure generator state */
   int segnum;                  /* current segment number */
   word slotnum;                /* current slot number */
   word tmask;                  /* structure mask before suspension */
   word sgmask[HSegs];          /* mask in use when the segment was created */
   uword sghash[HSegs];         /* hashnum in process when seg was created */
   };


/*
 * Structure for chaining tended descriptors.
 */
struct tend_desc {
   struct tend_desc *previous;
   int num;
   struct descrip d[1]; /* actual size of array indicated by num */
   };

/*
 * Structure for mapping string names of functions and operators to block
 * addresses.
 */
struct pstrnm {
   char *pstrep;
   struct b_proc *pblock;
   };

struct dpair {
   struct descrip dr;
   struct descrip dv;
   };

/*
 * Allocated memory region structure.  Each program has linked lists of
 * string and block regions.
 */
struct region {
   word  size;                          /* allocated region size in bytes */
   char *base;                          /* start of region */
   char *end;                           /* end of region */
   char *free;                          /* free pointer */
   struct region *prev, *next;          /* forms a linked list of regions */
#ifdef Concurrent
   struct region *Tprev, *Tnext;        /* forms a linked list of public regions. i.e not owned by any thread */
#endif                                  /* Concurrent */
   struct region *Gprev, *Gnext;        /* global (all programs) lists */
   };

#ifdef Double
   /*
    * Data type the same size as a double but without alignment requirements.
    */
   struct size_dbl {
       char s[sizeof(double)];
       };
#endif                                  /* Double */


#if COMPILER

/*
 * Structures for the compiler.
 *
 * If you modify struct p_frame, you have to correspondingly modify
 * the struct PF* structures in src/iconc/codegen.c, which are expected
 * to be compatible extensions. Don't forget initialization code.
 */
   struct p_frame {
      struct p_frame *old_pfp;
      struct descrip *old_argp;
      struct descrip *rslt;
      continuation succ_cont;
#ifdef PatternType
      struct b_table *pattern_cache; /* cache variable refs used in a pattern */
#endif                                  /* PatternType */
      struct tend_desc t;
      };
   #endif                               /* COMPILER */

/*
 * when debugging is enabled a debug struct is placed after the tended
 *  descriptors in the procedure frame.
 */
struct debug {
   struct b_proc *proc;
   char *old_fname;
   int old_line;
   };

union numeric {                 /* long integers or real numbers */
   word integer;
   double real;
   #ifdef LargeInts
      struct b_bignum *big;
   #endif                               /* LargeInts */
   };

/*
 * We want to support pthreads eventually even under COMPILER.
 * Towards that end, threadstate defined for both COMPILER and VM,
 * but a lot of fields are VM-only.
 */
struct threadstate {

  /*
   * the threadstate is tied not only to a thread, but also to
   * a coexpression (for now!), since there is a one to one mapping
   * between a co-expressn and it is corresponding thread
   * Note: (c is also equavelent to ctx->c)
   */

  struct b_coexpr *c;

#if ConcurrentCOMPILER
  continuation Coexpr_fnc;     /* function containing co-expression code */
#endif                                  /* ConcurrentCOMPILER */

#ifdef Concurrent
   pthread_t tid;
   int Pollctr;

   /* used in fmath.r, log() */
   double Lastbase;
   double Divisor;

   /* used in fstr.r, map() */
   struct descrip Maps2;
   struct descrip Maps3;
   char Maptab[256];

   /* used in rposix.r */
   word *Callproc;
   word Callproc_Ibuf[100];

#ifdef PosixFns
   char Savedbuf[BUFSIZ];
   int Nsaved;
#endif                                  /* PosixFns */
#endif                                  /* Concurrent */
   /* signal mask? etc. */

   /*
    * VM-specific per-thread variables.
    */
#if !COMPILER
#ifndef Concurrent
   word Lastop;
#endif                                  /* Concurrent */
   struct descrip Value_tmp;      /* TLS  */
   dptr Xargp;                    /* TLS  */
   word Xnargs;                   /* TLS  */
/* struct ef_marker *Efp;       * Expression frame pointer */
/* struct gf_marker *Gfp;       * Generator frame pointer */
/* struct pf_marker *Pfp;       * procedure frame pointer */
/* inst Ipc;                    * Interpreter program counter */
/* inst Oldipc;                  * the previous ipc, fix returned line zero */
/* word *Sp;            * Stack pointer */
/* int Ilevel;                  * Depth of recursion in interp() */
   word *Stack;                         /* Interpreter stack */
   word *Stackend;                      /* End of interpreter stack */
#endif                                  /* !COMPILER */
   dptr Glbl_argp; /*TLS*/                      /* global argp */

   struct descrip Kywd_pos;         /* TLS */
   struct descrip ksub;             /* TLS */
   struct descrip Kywd_ran;        /*  TLS  */
#ifdef PatternType
   int  K_patindex;                /* TLS */
#endif                                 /* PatternType */


   dptr Field_argp;                     /* TLS -- see comment in imisc.r */

   struct descrip K_current;      /* TLS  */
   int K_errornumber;             /* TLS  */
   int K_level;                   /* TLS  */
   struct descrip K_errortext;    /* TLS  */
   struct descrip K_errorvalue;   /* TLS  */
   int Have_errval;               /* TLS  */
   int T_errornumber;             /* TLS  */
   int T_have_val;
   struct descrip T_errorvalue;   /* TLS  */

#ifdef PosixFns
   struct descrip AmperErrno;  /* TLS */
#endif                                  /* PosixFns */

  word Line_num,   /* line number for current execution point */
    Column, Lastline, Lastcol; /*TLS*/

  /*  struct tend_desc *Tend;  * chain of tended descriptors */

  struct descrip Eret_tmp;      /* eret value during unwinding */

#ifdef Concurrent
  struct region *Curstring;    /*  separate regions vs shared      */
  struct region *Curblock;     /*     same above     */
#ifdef DescripAmpAllocated
  struct descrip stringtotal;                   /* cumulative total allocation */
  struct descrip blocktotal;                    /* cumulative total allocation */
#else                                   /* DescripAmpAllocated */
  uword stringtotal;                    /* cumulative total allocation */
  uword blocktotal;                     /* cumulative total allocation */
#endif                                  /* DescripAmpAllocated */

#ifdef SoftThreads
  int sthrd_tick;
  int sthrd_size;
  int sthrd_cur;
  struct b_coexpr * sthrds[SOFT_THREADS_SIZE];
  struct b_coexpr * owner; /* the co-expression where the thread spawned */
#endif                                  /* SoftThreads */
#endif                                  /* Concurrent */

#ifdef MultiProgram
  struct progstate *pstate;
#endif


/*
 * Structure for chaining threadstate structs.
 * The first node will be for the main thread, it  will be always the first.
 * New nodes will be added to the end of the chain, setting roottstate->prev
 * to point to the last node will make it easy to add at the end. The chain
 * is circular in one direction, backward, but not forward.
 */
  struct threadstate *prev;
  struct threadstate *next;
  };

#if !COMPILER

/*
 * Structures for the interpreter.
 */

/*
 * Declarations for entries in tables associating icode location with
 *  source program location.
 */
struct ipc_fname {
   word ipc_saved;      /* offset of instruction into code region */
   word fname;          /* offset of file name into string region */
   };

struct ipc_line {
   word ipc_saved;      /* offset of instruction into code region */
   int line;            /* line number */
   };

#ifdef MultiProgram
/*
 * Program state encapsulation.  This consists of the VARIABLE parts of
 * many global structures.
 */
struct progstate {
   long hsize;                          /* size of icode, 0 = C|Python|... */
        /* hsize is a constant defined at load time, MT safe */
   struct progstate *parent;
        /* parent is a constant defined at load time, MT safe */
   struct progstate *next;
        /* next is a link list, seldom used, needs mutex */
   struct descrip parentdesc;           /* implicit "&parent" */
        /* parentdesc is a constant defined at load time, MT safe */
   struct descrip eventmask;            /* implicit "&eventmask" */
        /* eventmask is read-only (to me), MT safe */
   struct descrip eventcount;           /* implicit "&eventcount" */
   struct descrip valuemask;
   struct descrip eventcode;            /* &eventcode */
   struct descrip eventval;             /* &eventval */
   struct descrip eventsource;          /* &eventsource */


   /* Systems don't have more than, oh, about 50 signals, eh?
    * Currently in the system there is 40 of them            */
   struct descrip Handlers[41];
   /*int Inited; not used anymore */
   int signal;
   /*
    * trapped variable keywords' values
    */
   struct descrip Kywd_err;          /* Probably mutex. not important now */
   struct descrip Kywd_prog;

   struct descrip Kywd_trc;         /* leave global for now   */
   struct b_coexpr *Mainhead;
   char *Code;
   char *Ecode;
   word *Records;
   int *Ftabp;
   #ifdef FieldTableCompression
      short Ftabwidth, Foffwidth;
      unsigned char *Ftabcp, *Focp;
      short *Ftabsp, *Fosp;
      int *Fo;
      char *Bm;
   #endif                               /* FieldTableCompression */
   dptr Fnames, Efnames;
   dptr Globals, Eglobals;
   dptr Gnames, Egnames;
   dptr Statics, Estatics;
   int NGlobals, NStatics;
   char *Strcons;
   struct ipc_fname *Filenms, *Efilenms;
   struct ipc_line *Ilines, *Elines;
  struct ipc_line * Current_line_ptr;  /* not used or what ?*/


   #ifdef Graphics
      struct descrip AmperX, AmperY, AmperRow, AmperCol;/* &x, &y, &row, &col */
      struct descrip AmperInterval;                     /* &interval */
      struct descrip LastEventWin;                      /* last Event() win */
      int LastEvFWidth;
      int LastEvLeading;
      int LastEvAscent;
      uword PrevTimeStamp;                              /* previous timestamp */
      uword Xmod_Control, Xmod_Shift, Xmod_Meta;        /* control,shift,meta */
      struct descrip Kywd_xwin[2];                      /* &window + ... */

   #ifdef Graphics3D
      struct descrip AmperPick;                         /* &pick */
   #endif                               /* Graphics3D */
   #endif                               /* Graphics */



   word Coexp_ser;                      /* this program's serial numbers */
   word List_ser;
   word Intern_list_ser;
#ifdef PatternType
   word Pat_ser;
#endif                                  /* PatternType */
   word Set_ser;
   word Table_ser;

   word Kywd_time_elsewhere;            /* ???? TLS vs global  &time spent in other programs */
   word Kywd_time_out;                  /* ????  TLS vs global &time at last program switch out */

#ifdef Concurrent
   word mutexid_stringtotal;
   word mutexid_blocktotal;
   word mutexid_coll;

   struct region *Public_stringregion;         /*  separate regions vs shared */
   struct region *Public_blockregion;          /*     same above     */
#endif                                  /* Concurrent */

   struct region *stringregion;         /*  separate regions vs shared      */
   struct region *blockregion;          /*     same above     */

  /* in case we have separate heaps, i.e ThreadHeap is defined
   * total here will be only for "dead" threads */
#ifdef DescripAmpAllocated
   struct descrip stringtotal;                  /* cumulative total allocation */
   struct descrip blocktotal;                   /* cumulative total allocation */
#else                                   /* DescripAmpAllocated */
   uword stringtotal;                   /* cumulative total allocation */
   uword blocktotal;                    /* cumulative total allocation */
#endif                                  /* DescripAmpAllocated */

   word colltot;                        /*  m      total number of collections */
   word collstat;                       /*  u      number of static collect requests */
   word collstr;                        /*  t      number of string collect requests */
   word collblk;                        /*  ex     number of block collect requests */

   struct descrip K_main;
   struct b_file K_errout;
   struct b_file K_input;
   struct b_file K_output;


   /* dynamic record types */

  int yyy;

  int Longest_dr;
  struct b_proc_list **Dr_arrays;

   /*
    * Function Instrumentation Fields.
    */
#ifdef Arrays
   int (*Cprealarray)(dptr, dptr, word, word);
   int (*Cpintarray)(dptr, dptr, word, word);
#endif                                  /* Arrays */
   int (*Cplist)(dptr, dptr, word, word);
   int (*Cpset)(dptr, dptr, word);
   int (*Cptable)(dptr, dptr, word);
   void (*EVstralc)(word);
#ifdef TSTATARG
   int (*Interp)(int,dptr, struct threadstate*);
#else                                    /* TSTATARG */
   int (*Interp)(int,dptr);
#endif                                   /* TSTATARG */
   int (*Cnvcset)(dptr,dptr);
   int (*Cnvint)(dptr,dptr);
   int (*Cnvreal)(dptr,dptr);
   int (*Cnvstr)(dptr,dptr);
   int (*Cnvtcset)(struct b_cset *,dptr,dptr);
   int (*Cnvtstr)(char *,dptr,dptr);
   void (*Deref)(dptr,dptr);
   struct b_bignum * (*Alcbignum)(word);
   struct b_cset * (*Alccset)();
   struct b_file * (*Alcfile)(FILE*,int,dptr);
   union block * (*Alchash)(int);
   struct b_slots * (*Alcsegment)(word);
#ifdef PatternType
   struct b_pattern * (*Alcpattern)(word);
   struct b_pelem * (*Alcpelem)(word, word *);
   int (*Cnvpattern)(dptr,dptr);
   int (*Internalmatch)(char*,int,int,struct descrip,
                       struct b_pelem*,int*,int*,int,int);
#endif                                  /* PatternType */
   struct b_list *(*Alclist_raw)(uword,uword);
   struct b_list *(*Alclist)(uword,uword);
   struct b_lelem *(*Alclstb)(uword,uword,uword);
#ifndef DescriptorDouble
   struct b_real *(*Alcreal)(double);
#endif                                  /* DescriptorDouble */
   struct b_record *(*Alcrecd)(int, union block *);
   struct b_refresh *(*Alcrefresh)(word *, int, int);
   struct b_selem *(*Alcselem)(dptr, uword);
   char *(*Alcstr)(char *, word);
   struct b_tvsubs *(*Alcsubs)(word, word, dptr);
   struct b_telem *(*Alctelem)(void);
   struct b_tvtbl *(*Alctvtbl)(dptr, dptr, uword);
   struct b_tvmonitored *(*Alctvmonitored) (dptr);
   void (*Deallocate)(union block *);
   char * (*Reserve)(int, word);

   struct threadstate *tstate, maintstate;

   };
#endif                                  /* MultiProgram */

/*
 * Frame markers
 */
struct ef_marker {              /* expression frame marker */
   inst ef_failure;             /*   failure ipc */
   struct ef_marker *ef_efp;    /*   efp */
   struct gf_marker *ef_gfp;    /*   gfp */
   word ef_ilevel;              /*   ilevel */
   };

struct pf_marker {              /* procedure frame marker */
   word pf_nargs;               /*   number of arguments */
   struct pf_marker *pf_pfp;    /*   saved pfp */
   struct ef_marker *pf_efp;    /*   saved efp */
   struct gf_marker *pf_gfp;    /*   saved gfp */
   dptr pf_argp;                /*   saved argp */
   inst pf_ipc;                 /*   saved ipc */
   word pf_ilevel;              /*   saved ilevel */
   dptr pf_scan;                /*   saved scanning environment */
#ifdef PatternType
    struct b_table *pattern_cache; /* used to cache the variable references used in a pattern*/
#endif                                  /* PatternType */

   struct descrip pf_locals[1]; /*   descriptors for locals */
   };

struct gf_marker {              /* generator frame marker */
   word gf_gentype;             /*   type */
   struct ef_marker *gf_efp;    /*   efp */
   struct gf_marker *gf_gfp;    /*   gfp */
   inst gf_ipc;                 /*   ipc */
   struct pf_marker *gf_pfp;    /*   pfp */
   dptr gf_argp;                /*   argp */
   };

/*
 * Generator frame marker dummy -- used only for sizing "small"
 *  generator frames where procedure information need not be saved.
 *  The first five members here *must* be identical to those for
 *  gf_marker.
 */
struct gf_smallmarker {         /* generator frame marker */
   word gf_gentype;             /*   type */
   struct ef_marker *gf_efp;    /*   efp */
   struct gf_marker *gf_gfp;    /*   gfp */
   inst gf_ipc;                 /*   ipc */
   };

/*
 * b_iproc blocks are used to statically initialize information about
 *  functions.  They are identical to b_proc blocks except for
 *  the pname field which is a sdescrip (simple/string descriptor) instead
 *  of a descrip.  This is done because unions cannot be initialized.
 */

struct b_iproc {                /* procedure block */
   word ip_title;               /*   T_Proc */
   word ip_blksize;             /*   size of block */
   int (*ip_entryp)();          /*   entry point (code) */
   word ip_nparam;              /*   number of parameters */
   word ip_ndynam;              /*   number of dynamic locals */
   word ip_nstatic;             /*   number of static locals */
   word ip_fstatic;             /*   index (in global table) of first static */

   struct sdescrip ip_pname;    /*   procedure name (string qualifier) */
   struct descrip ip_lnames[1]; /*   list of local names (qualifiers) */
   };
#endif                                  /* COMPILER */

struct b_coexpr {               /* co-expression stack block */
   word title;                  /*   T_Coexpr */
   word size;                   /*   number of results produced */
   word id;                     /*   identification number */
   word status;                 /*   status (native/posix, sync/async,  etc) */
#ifdef Concurrent
   word shared;
   word mutexid;
   struct descrip *handdata;     /*   result just handed  to the current ce */
   struct descrip cequeue;       /*   CEs waiting to receive results   */
   struct descrip inbox, outbox; /*   pending send/receive queues */
   word ini_blksize, ini_ssize;  /*   initial blksize and string size to want */

#ifdef SoftThreads
  int sthrd_tick;
  struct b_coexpr * parent;
#endif                                  /* SoftThreads */

#endif                                  /* Concurrent */
#ifdef EventMon
   word actv_count;             /*   number of times activated using EvGet() */
#endif                          /* EventMon */
   struct b_coexpr *nextstk;    /*   pointer to next allocated stack */
   struct tend_desc *es_tend;   /*   current tended pointer */
   dptr es_argp;                /*   current argument pointer */
   dptr tvalloc;                /*   where to place transmitted value */
   struct descrip freshblk;     /*   refresh block pointer */
   struct astkblk *es_actstk;   /*   pointer to activation stack structure */
   int coexp_act;               /*   used to pass signal across activations */
                                /*   back to whomever activates, if they care */
#if COMPILER
   continuation fnc;            /*   function containing co-expression code */
   struct p_frame *es_pfp;      /*   current procedure frame pointer */
   char *file_name;             /*   current file name */
   word line_num;               /*   current line_number */
/* see p_frame pf below */
#else                                   /* COMPILER */
   struct pf_marker *es_pfp;    /*   current pfp */
   struct ef_marker *es_efp;    /*   efp */
   struct gf_marker *es_gfp;    /*   gfp */
   inst es_ipc;                 /*   ipc */
   inst es_oldipc;              /*   oldipc */
   word es_ilevel;              /*   interpreter level */
   word *es_sp;                 /*   sp */
   word *es_stack;              /*   beginning of interpreter stack */
   word *es_stackend;           /*   end of interpreter stack */
   word Lastop;

   #ifdef MultiProgram
      struct progstate *program;
   #endif                               /* MultiProgram */
#endif                                  /* COMPILER */

#ifdef PthreadCoswitch
/* from the Icon pthreads-based co-expression implementation. */
   pthread_t thread;    /* thread ID (thread handle) */
   sem_t sema;          /* synchronization semaphore (if unnamed) */
   sem_t *semp;         /* pointer to semaphore */
   int alive;           /* set zero when thread is to die */

   int tmplevel;
   int have_thread;
#ifdef Concurrent
   struct threadstate *tstate;
   int isProghead;
#endif                                  /* Concurrent */
#endif                                  /* PthreadCoswitch */

     word cstate[CStateSize];   /*   C state information (registers, etc.) */
#if COMPILER
   struct p_frame pf;           /*   initial procedure frame */
#endif
/* WARNING:   pf ^ _must_ be the LAST item in b_coexpr
 * es_pfp points ^ HERE, so
 * the new pframes will be put _right_ after this!
 * anything you add after pf will be _clobbered_
 * ref: rcoexpr.r: sblkp->es_pfp = &sblkp->pf;
 * ref: rstructs.h, 2001 version
 */
   }; /* b_coexpr */

struct b_refresh {              /* co-expression refresh block */
   word title;                  /*   T_Refresh */
   word blksize;                /*   size of block */
   word nlocals;                /*   number of local variables */
#if COMPILER
   word nargs;                  /*   number of arguments */
   word ntemps;                 /*   number of temporary descriptors */
   word wrk_size;               /*   size of non-descriptor work area */
#else                                   /* COMPILER */
   word *ep;                    /*   entry point */
   struct pf_marker pfmkr;      /*   marker for enclosing procedure */
#endif                                  /* COMPILER */
   struct descrip elems[1];     /*   args and locals (VM: including Arg0) */
   };

union block {                   /* general block */
#ifndef DescriptorDouble
   struct b_real Real;
#endif                                  /* DescriptorDouble */
   struct b_cset Cset;
   struct b_file File;
   struct b_proc Proc;
   struct b_record Record;
   struct b_list List;
   struct b_lelem Lelem;
   struct b_set Set;
   struct b_selem Selem;
   struct b_table Table;
   struct b_telem Telem;
   struct b_tvsubs Tvsubs;
   struct b_tvtbl Tvtbl;
#ifdef EventMon
   struct b_tvmonitored Tvmonitored;
#endif                                  /* EventMon */
   struct b_refresh Refresh;
   struct b_coexpr Coexpr;
   struct b_external External;
   struct b_slots Slots;

#ifdef PatternType
   struct b_pattern Pattern;
   struct b_pelem Pelem;
#endif                                  /* PatternType */
#ifdef LargeInts
   struct b_bignum Lrgint;
#endif                          /* LargeInts */
#ifdef Arrays
   struct b_intarray Intarray;
   struct b_realarray Realarray;
#endif                                  /* Arrays */
   struct b_mask Mask;
   };

#ifdef PseudoPty
struct ptstruct {
#if NT
   HANDLE master_read, master_write;
   HANDLE slave_pid;
#else                                   /* WIN32 */
   int master_fd, slave_fd;             /* master, slave pty file descriptor */
   pid_t slave_pid;                     /* process id of slave  */
#endif                                  /* WIN32 */

   char slave_filename[256];/* pty slave filename associated with master pty */
   char slave_command[256]; /* name of executable associated with slave */
};
#endif                                  /* PseudoPty */

/****************************************   end ../h/../h/rstructs.h   */

#ifdef Graphics


/****************************************  from ../h/../h/graphics.h:  */

/*
 * graphics.h - macros and types used in Icon's graphics interface.
 */

#define MAXDISPLAYNAME  128

#ifdef XWindows


/****************************************  from ../h/../h/../h/xwin.h:  */

#ifdef XWindows

#define DRAWOP_AND                      GXand
#define DRAWOP_ANDINVERTED              GXandInverted
#define DRAWOP_ANDREVERSE               GXandReverse
#define DRAWOP_CLEAR                    GXclear
#define DRAWOP_COPY                     GXcopy
#define DRAWOP_COPYINVERTED             GXcopyInverted
#define DRAWOP_EQUIV                    GXequiv
#define DRAWOP_INVERT                   GXinvert
#define DRAWOP_NAND                     GXnand
#define DRAWOP_NOOP                     GXnoop
#define DRAWOP_NOR                      GXnor
#define DRAWOP_OR                       GXor
#define DRAWOP_ORINVERTED               GXorInverted
#define DRAWOP_ORREVERSE                GXorReverse
#define DRAWOP_REVERSE                  0x10
#define DRAWOP_SET                      GXset
#define DRAWOP_XOR                      GXxor

#define XLFD_Foundry     1
#define XLFD_Family      2
#define XLFD_Weight      3
#define XLFD_Slant       4
#define XLFD_SetWidth    5
#define XLFD_AddStyle    6
#define XLFD_Size        7
#define XLFD_PointSize   8
#define XLFD_Spacing    11
#define XLFD_CharSet    13

#define TEXTWIDTH(w,s,n) XTextWidth((w)->context->font->fsp, s, n)
#define SCREENDEPTH(w)\
        DefaultDepth((w)->window->display->display, w->window->display->screen)
#define ASCENT(w) ((w)->context->font->fsp->ascent)
#define DESCENT(w) ((w)->context->font->fsp->descent)
#define LEADING(w) ((w)->context->leading)
#define FHEIGHT(w) ((w)->context->font->height)
#define FWIDTH(w) ((w)->context->font->fsp->max_bounds.width)
#define LINEWIDTH(w) ((w)->context->linewidth)
#define DISPLAYHEIGHT(w)\
        DisplayHeight(w->window->display->display, w->window->display->screen)
#define DISPLAYWIDTH(w)\
        DisplayWidth(w->window->display->display, w->window->display->screen)
#define FS_SOLID FillSolid
#define FS_STIPPLE FillStippled
#define hidecrsr(x) /* noop */
#define UpdateCursorPos(x, y) /* noop */
#define showcrsr(x) /* noop */
#define SysColor XColor
/* 8-bit primary components of a current fg or bg index, used in 3D code */
#define RED(colrindex) ((w->context->display->colors[colrindex].r)>>8)
#define GREEN(colrindex) ((w->context->display->colors[colrindex].g)>>8)
#define BLUE(colrindex) ((w->context->display->colors[colrindex].b)>>8)
#define ARCWIDTH(arc) ((arc).width)
#define ARCHEIGHT(arc) ((arc).height)
#define RECX(rec) ((rec).x)
#define RECY(rec) ((rec).y)
#define RECWIDTH(rec) ((rec).width)
#define RECHEIGHT(rec) ((rec).height)
#define ANGLE(ang) (-(ang) * 180 / Pi * 64)
#define EXTENT(ang) (-(ang) * 180 / Pi * 64)
#define ISICONIC(w) ((w)->window->iconic == IconicState)
#define ISFULLSCREEN(w) (0)
#define ISROOTWIN(w) ((w)->window->iconic == RootState)
#define ISNORMALWINDOW(w) ((w)->window->iconic == NormalState)
#define ICONFILENAME(w) ((w)->window->iconimage)
#define ICONLABEL(w) ((w)->window->iconlabel)
#define WINDOWLABEL(w) ((w)->window->windowlabel)
#define RootState IconicState+1
#define MaximizedState IconicState+2
#define HiddenState IconicState+3

/*
 * Input masks not defined by X itself, but stored in the
 * inputmask field of the wstate structure.
 */
#define WindowClosureMask    (1L<<30)

/*
 * This macro allows the "true" X input masks to be
 * obtained from the inputmask field.
 */
#define XMasks(f)            ((f) & ((1L<<25)-1))

/*
 * The following constants define limitations in the system, gradually being
 * removed as this code is rewritten to use dynamic allocation.
 */
#define DMAXCOLORS      256
#define WMAXCOLORS      256
#define MAXCOLORNAME    40
#define CLR_SHARED          0
#define CLR_MUTABLE         1
#define NUMCURSORSYMS   78

/*
 * Macros to ease coding in which every X call must be done twice.
 */
#define RENDER2(func,v1,v2) {\
   if (stdwin) func(stddpy, stdwin, stdgc, v1, v2); \
   func(stddpy, stdpix, stdgc, v1, v2);}
#define RENDER3(func,v1,v2,v3) {\
   if (stdwin) func(stddpy, stdwin, stdgc, v1, v2, v3); \
   func(stddpy, stdpix, stdgc, v1, v2, v3);}
#define RENDER4(func,v1,v2,v3,v4) {\
   if (stdwin) func(stddpy, stdwin, stdgc, v1, v2, v3, v4); \
   func(stddpy, stdpix, stdgc, v1, v2, v3, v4);}
#define RENDER6(func,v1,v2,v3,v4,v5,v6) {\
   if (stdwin) func(stddpy, stdwin, stdgc, v1, v2, v3, v4, v5, v6); \
   func(stddpy, stdpix, stdgc, v1, v2, v3, v4, v5, v6);}
#define RENDER7(func,v1,v2,v3,v4,v5,v6,v7) {\
   if (stdwin) func(stddpy, stdwin, stdgc, v1, v2, v3, v4, v5, v6, v7); \
   func(stddpy, stdpix, stdgc, v1, v2, v3, v4, v5, v6, v7);}

#define MAXDESCENDER(w) (w->context->font->fsp->max_bounds.descent)

/*
 * Macros to perform direct window system calls from graphics routines
 */

#define STDLOCALS_RENDER(w)                             \
   wsp ws = (w)->window;                                \
   GC      stdgc  = (w)->context->gc;                   \
   Display *stddpy = ws->display->display;              \
   Window  stdwin  = ws->win;                           \
   Pixmap  stdpix  = ws->pix;

#define STDLOCALS(w)                                    \
   wcp wc = (w)->context;                               \
   wsp ws = (w)->window;                                \
   wdp wd = (w)->window->display;                       \
   GC      stdgc  = wc->gc;                             \
   Display *stddpy = wd->display;                       \
   Window  stdwin  = ws->win;                           \
   Pixmap  stdpix  = ws->pix;

#define drawarcs(w, arcs, narcs) \
   { STDLOCALS_RENDER(w); RENDER2(XDrawArcs,arcs,narcs); }
#define drawlines(w, points, npoints) \
   { STDLOCALS_RENDER(w); RENDER3(XDrawLines,points,npoints,CoordModeOrigin); }
#define drawpoints(w, points, npoints) \
   { STDLOCALS_RENDER(w); RENDER3(XDrawPoints,points,npoints,CoordModeOrigin); }
#define drawrectangles(w, recs, nrecs) { \
   int i; \
   STDLOCALS_RENDER(w); \
   for(i=0; i<nrecs; i++) { \
     RENDER4(XDrawRectangle,recs[i].x,recs[i].y,recs[i].width,recs[i].height);\
     }}

#define drawsegments(w, segs, nsegs) \
   { STDLOCALS_RENDER(w); RENDER2(XDrawSegments,segs,nsegs); }
#define drawstrng(w, x, y, s, slen) \
   { STDLOCALS_RENDER(w); RENDER4(XDrawString, x, y, s, slen); }
#define fillarcs(w, arcs, narcs) \
   { STDLOCALS_RENDER(w); RENDER2(XFillArcs, arcs, narcs); }
#define fillpolygon(w, points, npoints) \
   { STDLOCALS_RENDER(w); RENDER4(XFillPolygon, points, npoints, Complex, CoordModeOrigin); }

/*
 * "get" means remove them from the Icon list and put them on the ghost queue
 */
#define EVQUEGET(w,d) { \
   wsp ws = (w)->window; \
   if (!c_get((struct b_list *)BlkLoc(ws->listp),&d)) fatalerr(0,NULL); \
   if (Qual(d)) {\
      ws->eventQueue[ws->eQfront++] = *StrLoc(d); \
      if (ws->eQfront >= EQUEUELEN) ws->eQfront = 0; \
      ws->eQback = ws->eQfront; \
      } \
   }

#define EVQUEEMPTY(w) (BlkD((w)->window->listp,List)->size == 0)

/*
 * Colors.  These are allocated within displays; they are currently
 * statically bounded to DMAXCOLORS colors per display.  Pointers
 * into the display's color table are also kept on a per-window
 * basis so that they may be (de)allocated when a window is cleared.
 * Colors are aliased by r,g,b value.  Allocations by name and r,g,b
 * share when appropriate.
 *
 * Color (de)allocation comprises a simple majority of the space
 * requirements of the current implementation.  A monochrome-only
 * version would take a lot less space.
 *
 * The name field is the string returned by WAttrib.  For a mutable
 * color this is of the form "-47" followed by a second C string
 * containing the current color setting.
 *
 * Note the structure is a simple array with a hash table superimposed
 *
 */
typedef struct wcolor {
   int            refcount;
   char           name[6+MAXCOLORNAME];  /* name for WAttrib & WColor reads */
   unsigned short r, g, b;               /* rgb for colorsearch */
   unsigned long  c;                     /* X pixel value */
   int            type;                  /* CLR_SHARED or CLR_MUTABLE */
   int prev, next;                       /* hash table bucket prev/next */
} *wclrp;

/*
 * macros performing row/column to pixel y,x translations
 * computation is 1-based and depends on the current font's size.
 * exception: XTOCOL as defined is 0-based, because that's what its
 * clients seem to need.
 */
#define ROWTOY(w,row) ((row-1) * LEADING(w) + ASCENT(w))
#define COLTOX(w,col) ((col-1) * FWIDTH(w))
#define YTOROW(w,y)   ((y>0) ? ((y) / LEADING(w) + 1) : ((y) / LEADING(w)))
#define XTOCOL(w,x)  (!FWIDTH(w) ? (x) : ((x) / FWIDTH(w)))

/*
 * Utility macros to extract RGB color components when dealing with TRUE COLOR visuals.
 */

#define TRUECOLOR_DECLARE_AND_INIT_RGB_VARS(red_mask, green_mask, blue_mask)    \
   unsigned long rshift=0, rbits=0, gshift=0, gbits=0, bshift=0, bbits=0;       \
   do {                                                                         \
      unsigned long rmask = red_mask, gmask = green_mask, bmask = blue_mask;    \
      while (!(rmask & 1)) { rshift++; rmask >>= 1; }                           \
      while (rmask & 1) { rbits++; rmask >>= 1; }                               \
      if (rbits>8) { rshift += rbits-8; rbits = 8; }                            \
      while (!(gmask & 1)) { gshift++; gmask >>= 1; }                           \
      while (gmask & 1) { gbits++; gmask >>= 1; }                               \
      if (gbits>8) { gshift += gbits-8; gbits = 8;}                             \
      while (!(bmask & 1)) { bshift++; bmask >>= 1; }                           \
      while (bmask & 1) { bbits++; bmask >>= 1; }                               \
      if (bbits>8) { bshift += bbits-8; bbits = 8; }                            \
   } while (0)

#define TRUECOLOR_GET_RGB_BYTE(c, cshifts, cbits) (((c >> cshift) & ((1 << cbits)-1)) << (8-cbits))
#define TRUECOLOR_GET_RGB_RED(c)   (((c >> rshift) & ((1 << rbits)-1))  << (8-rbits))
#define TRUECOLOR_GET_RGB_GREEN(c) (((c >> gshift) & ((1 << gbits)-1))  << (8-gbits))
#define TRUECOLOR_GET_RGB_BLUE(c)  (((c >> bshift) & ((1 << bbits)-1))  << (8-bbits))

#endif                                  /* XWindows */

/****************************************   end ../h/../h/../h/xwin.h   */
#endif                                  /* XWindows */

#ifdef MSWindows


/****************************************  from ../h/../h/../h/mswin.h:  */

/*
 * mswin.h - macros and types used in the MS Windows graphics interface.
 */

#define DRAWOP_AND                      R2_MASKPEN
#define DRAWOP_ANDINVERTED              R2_MASKNOTPEN
#define DRAWOP_ANDREVERSE               R2_NOTMASKPEN
#define DRAWOP_CLEAR                    R2_BLACK
#define DRAWOP_COPY                     R2_COPYPEN
#define DRAWOP_COPYINVERTED             R2_NOTCOPYPEN
#define DRAWOP_EQUIV                    R2_NOTXORPEN
#define DRAWOP_INVERT                   R2_NOT
#define DRAWOP_NAND                     R2_MASKNOTPEN
#define DRAWOP_NOOP                     R2_NOP
#define DRAWOP_NOR                      R2_MERGENOTPEN
#define DRAWOP_OR                       R2_MERGEPEN
#define DRAWOP_ORINVERTED               R2_MERGEPENNOT
#define DRAWOP_ORREVERSE                R2_NOTMERGEPEN
#define DRAWOP_REVERSE                  R2_USER1
#define DRAWOP_SET                      R2_WHITE
#define DRAWOP_XOR                      R2_XORPEN

#define TEXTWIDTH(w,s,n) textWidth(w, s, n)
#define SCREENDEPTH(w) getdepth(w)
#define ASCENT(w)  ((w)->context->font->ascent)
#define ASCENTC(wc)  ((wc)->font->ascent)
#define DESCENT(w) ((w)->context->font->descent)
#define LEADING(w) ((w)->context->leading)
#define FHEIGHT(w) ((w)->context->font->height)
#define FHEIGHTC(wc) ((wc)->font->height)
#define FWIDTH(w)  ((w)->context->font->charwidth)
#define FWIDTHC(wc)  ((wc)->font->charwidth)
#define LINEWIDTH(w) ((w)->context->pen.lopnWidth.x)
#define DISPLAYHEIGHT(w) devicecaps(w, VERTRES)
#define DISPLAYWIDTH(w) devicecaps(w, HORZRES)
#define wflush(w) /* noop */
#define SysColor unsigned long
#define RED(x) GetRValue(x)
#define GREEN(x) GetGValue(x)
#define BLUE(x) GetBValue(x)
#define ARCWIDTH(arc) (arc).width
#define ARCHEIGHT(arc) (arc).height
/*
 * These get fixed up in the window-system-specific code
 */
#define RECX(rec) (rec).left
#define RECY(rec) (rec).top
#define RECWIDTH(rec) (rec).right
#define RECHEIGHT(rec) (rec).bottom
/*
 *
 */
#define ANGLE(ang) (ang)
#define EXTENT(ang) (ang)
#define FULLARC 2 * Pi
#define ISICONIC(w) (IsIconic((w)->window->iconwin))
#define ISFULLSCREEN(w) 0
#define ISROOTWIN(w) (0) 0
#define ISNORMALWINDOW(w) 0
#define ICONFILENAME(w) ""
#define ICONLABEL(w) ((w)->window->iconlabel)
#define WINDOWLABEL(w) ((w)->window->windowlabel)

#define MAXDESCENDER(w) DESCENT(w)

/*
 * gemeotry bitmasks
 */
#define GEOM_WIDTH           1
#define GEOM_HEIGHT          2
#define GEOM_POSX            4
#define GEOM_POSY            8
/*
 * fill styles
 */
#define FS_SOLID             1
#define FS_STIPPLE           2
#define FS_OPAQUESTIPPLE     4
/*
 * the special ROP code for mode reverse
 */
#define R2_USER1            (R2_LAST << 1)
/*
 * window states
 */
#define WS_NORMAL            0
#define WS_MIN               1
#define WS_MAX               2

/*
 * input masks
 */
#define PointerMotionMask    1
#define WindowClosureMask    2
#define KeyReleaseMask       4
#define TouchInputMask       8

/*
 * something I think should be #defined
 */
#define EOS                  '\0'

/* size of the working buffer, used for dialog messages and such */
#define PMSTRBUFSIZE         2048
/*
 * the bitmasks for the modifier keys
 */
#define ControlMask          (1L << 16L)
#define Mod1Mask             (2L << 16L)
#define ShiftMask            (4L << 16L)
#define VirtKeyMask          (8L << 16L)

/* some macros for Windows */

#define MAKERGB(r,g,b) RGB(r,g,b)
#define RGB16TO8(x) if ((x) > 0xff) (x) = (((x) >> 8) & 0xff)
#define hidecrsr(ws) if (ws->hasCaret) HideCaret(ws->iconwin)
#define showcrsr(ws) if (ws->hasCaret) ShowCaret(ws->iconwin)
#define FNTWIDTH(size) ((size) & 0xFFFF)
#define FNTHEIGHT(size) ((size) >> 16)
#define MAKEFNTSIZE(height, width) (((height) << 16) | (width))
#define WaitForEvent(msgnum, msgstruc) ObtainEvents(NULL, WAIT_EVT, msgnum, msgstruc)

/*
 * "get" means remove them from the Icon list and put them on the ghost que
 */
#define EVQUEGET(ws,d) { \
  int i;\
  if (!c_get(BlkD((ws)->listp, List),&d)) fatalerr(0,NULL); \
  if (Qual(d)) {\
      (ws)->eventQueue[(ws)->eQfront++] = *StrLoc(d); \
      if ((ws)->eQfront >= EQUEUELEN) (ws)->eQfront = 0; \
      (ws)->eQback = (ws)->eQfront; \
      } \
  }
#define EVQUEEMPTY(ws) (BlkD((ws)->listp,List)->size == 0)

#define CLR_SHARED          0
#define CLR_MUTABLE         1
#define MAXCOLORNAME    40
/*
 * color structure, inspired by X code (xwin.h)
 */
typedef struct wcolor {
  int           refcount;
  char          name[6+MAXCOLORNAME];   /* name for WAttrib & WColor reads */
  SysColor      c;
  int           type;                   /* CLR_SHARED or CLR_MUTABLE */
} *wclrp;

/*
 * we make the segment structure look like this so that we can
 * cast it to POINTL structures that can be passed to GpiPolyLineDisjoint
 */
typedef struct {
   LONG x1, y1;
   LONG x2, y2;
   } XSegment;

typedef POINT XPoint;
typedef RECT XRectangle;

typedef struct {
  LONG x, y;
  LONG width, height;
  double angle1, angle2;
  } XArc;

/*
 * macros performing row/column to pixel y,x translations
 * computation is 1-based and depends on the current font's size.
 * exception: XTOCOL as defined is 0-based, because that's what its
 * clients seem to need.
 */
#define ROWTOY(wb, row)  ((row - 1) * LEADING(wb) + ASCENT(wb))
#define COLTOX(wb, col)  ((col - 1) * FWIDTH(wb))
#define YTOROW(wb, y)    (((y) - ASCENT(w)) /  LEADING(wb) + 1)
#define XTOCOL(w,x)  (!FWIDTH(w) ? (x) : ((x) / FWIDTH(w)))

/*
 * system size values
 */
#define BORDERWIDTH      (GetSystemMetrics(SM_CXBORDER)) /* 1 */
#define BORDERHEIGHT     (GetSystemMetrics(SM_CYBORDER)) /* 1 */
#define TITLEHEIGHT      (GetSystemMetrics(SM_CYCAPTION)) /* 20 */
#define FRAMEWIDTH       (GetSystemMetrics(SM_CXFRAME))   /* 4 */
#define FRAMEHEIGHT      (GetSystemMetrics(SM_CYFRAME))   /* 4 */

#define STDLOCALS(w) \
   wcp wc = (w)->context;\
   wsp ws = (w)->window;\
   HWND stdwin = ws->win;\
   HBITMAP stdpix = ws->pix;\
   HDC stddc = CreateWinDC(w);\
   HDC pixdc = CreatePixDC(w, stddc);

#define STDFONT \
   { if(stdwin)SelectObject(stddc, wc->font->font); SelectObject(pixdc,wc->font->font); }

#define FREE_STDLOCALS(w) do { SelectObject(pixdc, (w)->window->theOldPix); ReleaseDC((w)->window->iconwin, stddc); DeleteDC(pixdc); } while (0)

#define MAXXOBJS 8

#define GammaCorrection 2.2

#define glXSwapBuffers(foo, bar) { \
HDC stddc = CreateWinDC(w);\
         SwapBuffers(stddc);\
ReleaseDC(w->window->iconwin, stddc);\
}

/****************************************   end ../h/../h/../h/mswin.h   */
#endif                                  /* MSWindows */

#if Graphics3D
#if HAVE_LIBGL


/****************************************  from ../h/../h/../h/opengl.h:  */

/*
 * opengl.h - macros and structures for OpenGL-specific implementation
 *            of Unicon graphics facilities
 */

//#define GL2D_DRAWARRAYS 1 /* Punt this off as a TODO item */

#ifdef GL2D_DEBUG
#define glprintf(s, ...) printf(stderr,s, ##__VA_ARGS__)
#else                                   /* GL2D_DEBUG */
#define glprintf(s, ...)
#endif                                  /* GL2D_DEBUG */

/* Definitions for attribute buffermode */
#define UGL_IMMEDIATE   1
#define UGL_BUFFERED    0
/* Legacy definitons */
#define IMMEDIATE3D     UGL_IMMEDIATE
#define BUFFERED3D      UGL_BUFFERED


/*
 * mesh modes.
 */
#define U3D_POINTS         GL_POINTS
#define U3D_LINES          GL_LINES
#define U3D_LINE_STRIP     GL_LINE_STRIP
#define U3D_LINE_LOOP      GL_LINE_LOOP
#define U3D_TRIANGLES      GL_TRIANGLES
#define U3D_TRIANGLE_FAN   GL_TRIANGLE_FAN
#define U3D_TRIANGLE_STRIP GL_TRIANGLE_STRIP
#define U3D_QUADS          GL_QUADS
#define U3D_QUAD_STRIP     GL_QUAD_STRIP
#define U3D_POLYGON        GL_POLYGON

#define U2D_LINE_LOOP      GL_LINE_LOOP
#define U2D_LINE_STRIP     GL_LINE_STRIP
#define U2D_POLYGON        GL_POLYGON

/*
 * texture modes.
 */
#define U3D_REPLACE        GL_REPLACE
#define U3D_BLEND          GL_BLEND
#define U3D_MODULATE       GL_MODULATE

/*
 * Graphical primitive IDs
 */
#define GL2D_BLIMAGE            9000
#define GL2D_FILLPOLYGON        9001
#define GL2D_DRAWPOLYGON        9002
#define GL2D_DRAWSEGMENT        9003
#define GL2D_DRAWLINE           9004
#define GL2D_DRAWPOINT          9005
#define GL2D_DRAWCIRCLE         9006
#define GL2D_FILLCIRCLE         9007
#define GL2D_DRAWARC            9008
#define GL2D_FILLARC            9009
#define GL2D_DRAWRECTANGLE      9010
#define GL2D_FILLRECTANGLE      9011
#define GL2D_COPYAREA           9012
#define GL2D_ERASEAREA          9013
#define GL2D_STRIMAGE           9014
#define GL2D_READIMAGE          9015
#define GL2D_DRAWSTRING         9016
#define GL2D_WWRITE             9017

/*
 * Attribute primitive IDs
 */
/* colors */
#define GL2D_FG                 9050
#define GL2D_BG                 9051
#define GL2D_REVERSE            9052
#define GL2D_GAMMA              9053
#define GL2D_DRAWOP             9054

/* fonts */
#define GL2D_FONT               9055
#define GL2D_LEADING            9056

/* lines/fills */
#define GL2D_LINEWIDTH          9057
#define GL2D_LINESTYLE          9058
#define GL2D_FILLSTYLE          9059
#define GL2D_PATTERN            9060

/* positioning */
#define GL2D_CLIP               9061
#define GL2D_DX                 9062
#define GL2D_DY                 9063

/*
 * line styles
 */
#define GL2D_LINE_SOLID         0
#define GL2D_LINE_DASHED        1
#define GL2D_LINE_STRIPED       2

/*
 * fill styles
 */
#define GL2D_FILL_SOLID         0
#define GL2D_FILL_TEXTURED      1
#define GL2D_FILL_MASKED        2

/*
 * drawops
 */
#define GL2D_DRAWOP_COPY        GL_COPY
#define GL2D_DRAWOP_REVERSE     GL_XOR


/*
 * Structures
 */

/*
 * For a linked list color structure
 */
typedef struct color {
   char name[6+MAXCOLORNAME];
   unsigned short r, g, b, a;
   /* for referencing a mutable color (negative) */
   int id;
#ifdef XWindows
   unsigned long c; /* X11 color handle */
#endif                                  /* XWindows */
   struct color *prev, *next;
   } *clrp;

/*
 * Object for storing font characters (uses textures)
 */
struct fontsymbol {
   unsigned char *pixmap;
   int width, height;
   int advance, top_bearing, left_bearing;
   unsigned int texid, index;
   };


/*
 * A version of *MakeCurrent that checks for redundant state changes.
 */
#ifdef XWindows
#define MakeCurrent(w) do {\
   wsp ws = (w)->window;\
   if (ws->ctx != ws->display->currCtx) {\
      if (ws->iconic == HiddenState)\
         glXMakeCurrent(ws->display->display, ws->pbuf, ws->ctx);\
      else\
         glXMakeCurrent(ws->display->display, ws->win, ws->ctx);\
      ws->display->currCtx = ws->ctx;\
      }\
   } while(0)

#define UnbindCurrent(wd) do {\
   glXMakeCurrent(wd->display, None, NULL);\
   wd->currCtx = NULL;\
   } while(0)

#endif                                  /* XWindows */

/*
 * TODO: Make MSWindows version check for redundant state changes
 */
#ifdef MSWindows
#define MakeCurrent(w) do {\
   wsp ws = (w)->window;\
   HDC stddc = CreateWinDC(w); \
   wglMakeCurrent(stddc, ws->ctx);\
   ReleaseDC(ws->iconwin, stddc);\
   } while(0)

#define UnbindCurrent(wd)
#endif                                  /* MSWindows */

#define FlushWindow(w) do {\
   if ((w)->window->buffermode == UGL_BUFFERED)\
      swapbuffers((w), 1);\
   else if ((w)->window->buffermode == UGL_IMMEDIATE)\
      glFlush();\
   } while(0);

/*
 * Wrappers for OpenGL functions that check return values (prefixed with UGL)
 */

/*
 * There is at least one OpenGL function that is generating
 * an error currently. When there is enough time, just these
 * error macros to find out what is it. As of yet, nothing
 * seems to be running poorly.
 */
#define UGLGetError(msg) do {\
   unsigned int err;\
   while ((err = glGetError()) != GL_NO_ERROR)\
      glprintf("OpenGL error 0x%x from" #msg "\n",err);\
   } while(0)

/*
 * General OpenGL error checker that handles nothing.
 * Currently for debugging
 */
#define CheckGLError(func) do {\
   unsigned int err;\
   func;\
   UGLGetError(func);\
   } while(0)

#define UGLTexImage2D(wd, target, level, internalfmt, width, height, border,\
   format, type, data, retval) \
   do {\
   unsigned int err, errcount = 0;\
   glTexImage2D(target,level,internalfmt,width,height,border,format,type,data);\
   while ((err = glGetError()) != GL_NO_ERROR) {\
      if (err == GL_OUT_OF_MEMORY) {\
         if (!errcount) {\
            delete_first_tex(wd, (wd)->numTexIds/2);\
            glTexImage2D(target,level,internalfmt,width,height,border,format,\
                         type,data);\
            }\
         /* if failed already, then let it die */\
         else return retval;\
         errcount++;\
         }\
      }\
   } while(0)

/*
 * There is a floating error in gpxtest.icn for procedure copying
 * It is happening before the entire hidden
 * window's contents are copied to the main window.
 * TODO: find the error to make sure it doesn't become
 * a future problem. Reminder: set a breakpoint at
 * gl_copyArea or copyarea2d to find it.
 *
 * The error is incorrectly diagnosed to be a result of
 * glBindTexture, but uncommenting the while loop shows
 * it to be true.
 */
#define UGLBindTexture(target, texid) do {\
   unsigned int err;\
/*\
   while ((err = glGetError()) != GL_NO_ERROR)\
      glprintf("previous OpenGL error 0x%x\n",err);\
*/\
   glBindTexture(target, texid);\
   while ((err = glGetError()) != GL_NO_ERROR) {\
      switch (err) {\
         case GL_INVALID_ENUM:\
            glprintf("Invalid texture target %d\n",(int)target);\
            break;\
         case GL_INVALID_VALUE:\
            glprintf("Texture id %u was not generated from a previous call to glGenTextures()\n",(unsigned int)texid);\
            break;\
         case GL_INVALID_OPERATION:\
            glprintf("Texture id %u does not match the target specified from the call to glGenTextures()\n",(unsigned int)texid);\
            break;\
         default:\
            glprintf("Residual OpenGL error 0x%x\n",err);\
            break;\
         }\
      }\
   } while(0)

#ifdef XWindows
#define ApplyBuffermode(w, mode) do {\
   if ((mode) == UGL_BUFFERED || (w)->window->iconic == HiddenState) {\
      glReadBuffer(GL_BACK);\
      glDrawBuffer(GL_BACK);\
      }\
   else if ((mode) == UGL_IMMEDIATE) {\
      glReadBuffer(GL_FRONT);\
      glDrawBuffer(GL_FRONT);\
      }\
   } while(0)
#else                                   /* XWindows */
#define ApplyBuffermode(w, mode)
#endif                                  /* XWindows */


/*
 * For Unicon graphics, it would be useful to designate specific classes
 * of operations to each bit of the stencil buffer.
 */
#define GL2D_DRAW_BIT 0x01
#define GL2D_PATT_BIT 0x02
#define GL2D_ERASE_BIT 0x04

/*
 * {mask} determines the bitplane(s) affected.
 * {val} is the value the stencil buffer is cleared to.
 * {action} determines the the action to be taken when the stencil
 * test passes.
 */
#define EnableStencilWrite(mask, val, action) do {\
   glStencilMask(mask);\
   glStencilOp(GL_KEEP, GL_KEEP, action);\
   glClearStencil(val);\
   glClear(GL_STENCIL_BUFFER_BIT);\
   } while(0)

#define DisableStencilWrite() do {\
   glStencilMask(0x0);\
   glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);\
   } while(0)

/*
 * glStencilFunc() with a mask of 0 lets the stencil test pass regardless
 * of what values are in the stencil buffer. Otherwise, it will only let
 * pixels that are equal to the bits in {mask} pass the stencil test.
 */
#define SetStencilFunc(w, mask) \
   glStencilFunc(GL_EQUAL, 0xFF, (w)->window->stencil_mask|mask)
#define DefaultStencilFunc(w) SetStencilFunc(w, 0)

/*
 * Miscellaneous
 */
#define POLY_COMPLEX 1 /* self-intersecting "convex" */
#define POLY_CONVEX 2
#define POLY_NONCONVEX 3

/*
 * Macros for GPU pixel format. (buf) and other values must be of the same
 * type. Automating GPU pixel format configuration is a TODO item.
 */
#define AssignRGBA(buf, r, g, b, a) do {\
   (buf)[0] = r;\
   (buf)[1] = g;\
   (buf)[2] = b;\
   (buf)[3] = a;\
   } while(0)

#define AssignBGRA(buf, r, g, b, a) do {\
   (buf)[0] = b;\
   (buf)[1] = g;\
   (buf)[2] = r;\
   (buf)[3] = a;\
   } while(0)

#define AssignRGB(buf, r, g, b) do {\
   (buf)[0] = r;\
   (buf)[1] = g;\
   (buf)[2] = b;\
   } while(0)

#define AssignBGR(buf, r, g, b) do {\
   (buf)[0] = b;\
   (buf)[1] = g;\
   (buf)[2] = r;\
   } while(0)

/*
 * Macro for convenience
 */
#define UpdateRenderContext(w, intcode) do {\
   if (!(w)->window->initAttrs && !(w)->window->updateRC &&\
       (w)->window->lastwcserial != (w)->context->serial)\
      {\
      int rv = updaterendercontext(w, intcode);\
      if (rv != Succeeded) return rv;\
      }\
   } while(0)

/*
 * Helper macro for getting 2d record constructors
 *
 * rec_structor2d() could return NULL if the program runs out of memory.
 * If it returns NULL with memory to spare, it would be a syserr().
 */
#define Get2dRecordConstr(constr, code) do {\
   if (constr == NULL) {\
      if ((constr = rec_structor2d(code)) == NULL) {\
         return RunError;\
         }\
      }\
   } while(0)\

/*
 * Macros for context attribute application
 */

/*
 * The OpenGL logical operations interfere with transparency (i.e. when
 * GL_COLOR_LOGIC_OP is enabled, GL_BLEND is disabled)
 * Disable GL_COLOR_LOGIC_OP for drawop="copy" and enable
 * it for drawop="reverse"/"xor".
 */
#define ApplyDrawop(w, drawop) do {\
   if (drawop == GL2D_DRAWOP_COPY) {\
      glDisable(GL_COLOR_LOGIC_OP);\
      }\
   else if (drawop == GL2D_DRAWOP_REVERSE) {\
      glEnable(GL_COLOR_LOGIC_OP);\
      }\
   SetDrawopColorState(w, drawop, FG);\
   } while(0)

#define ApplyGamma(w) SetDrawopColorState(w, (w)->window->wcrender.drawop, FG)
#define ApplyLinewidth(linewidth) glLineWidth(linewidth);

/*
 * Get macros for user-modifiable DL record fields.
 * Should they Fail or RunError on an unexpected type?
 */
#define GetInt(d, intgr) do {\
   /*if (is:integer(d))*/\
   if ((d).dword == D_Integer)\
      intgr = IntVal(d);\
   /*else if (is:real(d))*/\
   else if ((d).dword == D_Real)\
      intgr = (int)RealVal(d);\
   else\
      return RunError;/* expected Int/Dbl */\
   } while(0)

#define GetDouble(d, dbl) do {\
   /*if (is:integer(d))*/\
   if ((d).dword == D_Integer)\
      dbl = (double)IntVal(d);\
   /*else if (is:real(d))*/\
   else if ((d).dword == D_Real)\
      dbl = (double)RealVal(d);\
   else\
      return RunError;/* expected Int/Dbl */\
   } while(0)

#define GetStr(d, s, len) do {\
   if (Qual(d)) {\
      s = StrLoc(d);\
      len = StrLen(d);\
      }\
   else\
      return RunError; /* expected string */\
   } while(0)

#define GetStrLoc(d, s) do {\
   if (Qual(d))\
      s = StrLoc(d);\
   else\
      return RunError; /* expected string */\
   } while(0)

/*
 * Macros for checking user-changed DL record fields
 */
#define RecalcTranslation(w) \
   ((w)->window->dx_flag | (w)->window->dy_flag)

/*
 * Need to compare some real values. Choose an epsilon
 */
#define UGL_EPSILON 1e-4
#define RealEqual(r1, r2) (Abs(r1 - r2) <= UGL_EPSILON)

#define RecalcCircle(rp) \
   ((IntVal((rp)->fields[3]) != IntVal((rp)->fields[8])) ||\
    (IntVal((rp)->fields[4]) != IntVal((rp)->fields[9])) ||\
    RealEqual(RealVal((rp)->fields[5]), RealVal((rp)->fields[10])) ||\
    RealEqual(RealVal((rp)->fields[6]), RealVal((rp)->fields[11])) ||\
    RealEqual(RealVal((rp)->fields[7]), RealVal((rp)->fields[12]))\
   )

#define UpdateCircle(rp) do {\
   IntVal((rp)->fields[8]) = (word)IntVal((rp)->fields[3]);\
   IntVal((rp)->fields[9]) = (word)IntVal((rp)->fields[4]);\
   RealVal((rp)->fields[10]) = RealVal((rp)->fields[5]);\
   RealVal((rp)->fields[11]) = RealVal((rp)->fields[6]);\
   RealVal((rp)->fields[12]) = RealVal((rp)->fields[7]);\
   } while(0)

#define RecalcArc(rp) \
   ((IntVal((rp)->fields[3]) != IntVal((rp)->fields[9])) ||\
    (IntVal((rp)->fields[4]) != IntVal((rp)->fields[10])) ||\
    (IntVal((rp)->fields[5]) != IntVal((rp)->fields[11])) ||\
    (IntVal((rp)->fields[6]) != IntVal((rp)->fields[12])) ||\
    RealEqual(RealVal((rp)->fields[7]), RealVal((rp)->fields[13])) ||\
    RealEqual(RealVal((rp)->fields[8]), RealVal((rp)->fields[14]))\
   )

#define UpdateArc(rp) do {\
   IntVal((rp)->fields[9]) = (word)IntVal((rp)->fields[3]);\
   IntVal((rp)->fields[10]) = (word)IntVal((rp)->fields[4]);\
   IntVal((rp)->fields[11]) = (word)IntVal((rp)->fields[5]);\
   IntVal((rp)->fields[12]) = (word)IntVal((rp)->fields[6]);\
   RealVal((rp)->fields[13]) = RealVal((rp)->fields[7]);\
   RealVal((rp)->fields[14]) = RealVal((rp)->fields[8]);\
   } while(0)

#define RecalcRect(rp) \
   ((IntVal((rp)->fields[3]) != IntVal((rp)->fields[7])) ||\
    (IntVal((rp)->fields[4]) != IntVal((rp)->fields[8])) ||\
    (IntVal((rp)->fields[5]) != IntVal((rp)->fields[9])) ||\
    (IntVal((rp)->fields[6]) != IntVal((rp)->fields[10]))\
   )

#define UpdateRect(rp) do {\
   IntVal((rp)->fields[7]) = (word)IntVal((rp)->fields[3]);\
   IntVal((rp)->fields[8]) = (word)IntVal((rp)->fields[4]);\
   IntVal((rp)->fields[9]) = (word)IntVal((rp)->fields[5]);\
   IntVal((rp)->fields[10]) = (word)IntVal((rp)->fields[6]);\
   } while(0)

/*
 * Macros for managing integrated 2D/3D mode
 */

#define DepthRange2d() glDepthRange(0.0,0.0)
#define DepthRange3d() glDepthRange(0.05,1.0)
#define DepthRangeMax() glDepthRange(1.0,1.0)

#define IS_CLIP(w) ((w)->window->wcrender.clipx != 0 ||\
                    (w)->window->wcrender.clipy != 0 ||\
                    (w)->window->wcrender.clipw != -1 ||\
                    (w)->window->wcrender.cliph != -1)

/*
 * Make sure that OpenGL states stay consistent to 2D/3D rendering modes
 */
#define SwitchMode2d(w) do {\
   if (IS_CLIP(w))\
      glEnable(GL_SCISSOR_TEST);\
   DepthRange2d();\
   } while(0)

#define SwitchMode3d(w) do {\
   if (IS_CLIP(w))\
      glDisable(GL_SCISSOR_TEST);\
   DepthRange3d();\
   } while(0)

#define UGL2D 0
#define UGL3D 1
#define ApplyRendermode(w,is_3d) do {\
   (w)->window->rendermode = is_3d;\
   if (is_3d)\
      SwitchMode3d(w);\
   else\
      SwitchMode2d(w);\
   } while(0)

#define CheckRendermode(w) do {\
   if ((w)->window->rendermode != (w)->context->rendermode) {\
      ApplyRendermode(w, w->context->rendermode);\
      }\
   } while(0)

/*
 * Viewing volume definitions
 */
//#define CWIDTH 0.25
//#define CNEAR 0.25
//#define CFAR 50000.0
//#define CHEIGHT(w) (CWIDTH*((double)w->window->height)/((double)w->window->width))

#define CNEAR 0.25
#define CFAR 50000.0
#define DEFAULT_CWIDTH 0.25
#define CWIDTH(w) ((w)->window->camwidth)
#define CHEIGHT(w) ((w)->window->camwidth*((double)w->window->height)/\
                    ((double)w->window->width))
#define HALF_CWIDTH(w) (CWIDTH(w)/2.0)
#define HALF_CHEIGHT(w) (CHEIGHT(w)/2.0)

/* Projection definitons */
#define UGL_PERSPECTIVE 0
#define UGL_ORTHOGONAL  1

#define UGLProj(w) do {\
   wsp ws = (w)->window;\
   if (ws->projection == UGL_PERSPECTIVE)\
      glFrustum(-HALF_CWIDTH(w),HALF_CWIDTH(w),-HALF_CHEIGHT(w),\
                HALF_CHEIGHT(w),CNEAR,CFAR);\
   else\
      glOrtho(-HALF_CWIDTH(w),HALF_CWIDTH(w),-HALF_CHEIGHT(w),HALF_CHEIGHT(w),\
                CNEAR,CFAR);\
   } while(0)

#define SetWindowSize(w) do {\
   wsp ws = (w)->window;\
   glViewport(0, 0, (GLsizei)ws->width, (GLsizei)ws->height);\
   glMatrixMode(GL_PROJECTION);\
   glLoadIdentity();\
   UGLProj(w);\
   glMatrixMode(GL_MODELVIEW);\
   } while(0)

/*
 * Checks to see if (x, y, w, h) are the defaults set by rectargs(). If they
 * aren't, subtract dx/dy.
 */
#define RemoveDxDy(win, x, y, w, h) do {\
   wsp ws = win->window;\
   wcp wcr = &(ws->wcrender);\
   if (x != 0 || y != 0 || w != ws->width || h != ws->height) {\
      x -= wcr->dx;\
      y -= wcr->dy;\
      }\
   } while(0)

/*
 * Adds dx/dy back in via render context.
 * Uses rectargs() logic like RemoveDxDy()
 */
#define AddDxDy(win, x, y, w, h) do {\
   wsp ws = win->window;\
   wcp wcr = &(ws->wcrender);\
   if (x != 0 || y != 0 || w != ws->width || h != ws->height) {\
      x += wcr->dx;\
      y += wcr->dy;\
      }\
   } while(0)

/*
 * For translating from pixel (Unicon) to world (OpenGL) coordinates.
 * In relation to the camera, the center of the window is (0,0) in world
 * coordinates.
 */
#define PIXW(w) (w->window->width)
#define PIXH(w) (w->window->height)
#define CLIPW(w) (CWIDTH(w))
#define CLIPH(w) (CHEIGHT(w))

/*
 * For translating from Unicon to OpenGL coordinates
 *
 * Any pixel rendering operations must use GLWORLDCOORD_*().
 *
 * Any line rendering operations that use OpenGL defined primitives
 * (GL_POLYGON, GL_LINES, etc) must use GLWORLDCOORD_RENDER*().
 * OpenGL renders lines with the diamond rule. GLWORLDCOORD_RENDER_*() offsets
 * the pixel value by 0.5 so that it starts in the center of a pixel.
 */
#define GLWORLDCOORD_X(w, px) ((px)*CLIPW(w)/(double)PIXW(w)-CLIPW(w)/2.0)
#define GLWORLDCOORD_Y(w, py) \
   ((PIXH(w)-(py))*CLIPH(w)/(double)PIXH(w)-CLIPH(w)/2.0)
#define GLWORLDCOORD_RENDER_X(w, px) \
   ((px+0.5)*CLIPW(w)/(double)PIXW(w)-CLIPW(w)/2.0)
#define GLWORLDCOORD_RENDER_Y(w, py) \
   ((PIXH(w)-(py+0.5))*CLIPH(w)/(double)PIXH(w)-CLIPH(w)/2.0)

/*
 * For translating radius in pixels to that of the world coordinate system.
 *
 * The transformation must keep the correct arc-to-window-dimension
 * ratios when transforming from pixel to world dimensions.
 */
#define GLRADIUS_X(w, pr) ((pr)/PIXW(w)*CLIPW(w))
#define GLRADIUS_Y(w, pr) ((pr)/PIXH(w)*CLIPH(w))

/*
 * Sets a color {struct color}.
 *
 * Whenever a color is set, set the X11 color handle to -1 (default).
 *
 * Should the colorname include alpha?
 */
#ifdef XWindows
#define SetColor(clr, red, green, blue, alpha, index) do {\
   sprintf((clr).name,"%ld,%ld,%ld",(long)red,(long)green,(long)blue);\
   (clr).r = red;\
   (clr).g = green;\
   (clr).b = blue;\
   (clr).a = alpha;\
   (clr).id = index;\
   /* TODO: make this look through {wd->colors} to see if already allocated */\
   if (red == 0 && green == 0 && blue == 0 )\
      (clr).c = 0;\
   else if (red == 65535 && green == 65535 && blue == 65535)\
      (clr).c = 1;\
      /*(clr).pixel = 1;*/\
   else\
      (clr).c = -1;\
      /*(clr).pixel = -1;*/\
   } while(0)
#else                                   /* XWindows */
#define SetColor(clr, red, green, blue, alpha, index) do {\
   sprintf((clr).name,"%ld,%ld,%ld",(long)red,(long)green,(long)blue);\
   (clr).r = red;\
   (clr).g = green;\
   (clr).b = blue;\
   (clr).a = alpha;\
   (clr).id = index;\
   } while(0)
#endif                                  /* XWindows */

/*
 * Gets a color from type {struct color}. Works whether {color}
 * is mutable or not. If it is mutable and it cannot be found,
 * set the color to black (talk to Dr. J about this).
 *
 * The returned color values are unsigned short (US).
 */
#define GetColorUS(w, clr, red, green, blue, alpha) do {\
   if ((clr).id < 0) { /* have a mutable */\
      struct color *mclr = find_mutable(w, (clr).id);\
      if (mclr) {\
         red = mclr->r;\
         green = mclr->g;\
         blue = mclr->b;\
         alpha = mclr->a;\
         }\
      else { /* mutable not found, use {clr}... should this be a fail? */\
         red = (clr).r;\
         green = (clr).g;\
         blue = (clr).b;\
         alpha = (clr).a;\
         }\
      }\
   else {\
      red = (clr).r;\
      green = (clr).g;\
      blue = (clr).b;\
      alpha = (clr).a;\
      }\
   } while(0)

/*
 * Exactly like GetColorUS(), but returns unsigned char (UC)
 */
#define GetColorUC(w, clr, red, green, blue, alpha) do {\
   if ((clr).id < 0) { /* have a mutable */\
      struct color *mclr = find_mutable(w, (clr).id);\
      if (mclr) {\
         red = USToUC(mclr->r);\
         green = USToUC(mclr->g);\
         blue = USToUC(mclr->b);\
         alpha = USToUC(mclr->a);\
         }\
      else { /* mutable not found, use {clr}... should this be a fail? */\
         red = (clr).r;\
         green = (clr).g;\
         blue = (clr).b;\
         alpha = (clr).a;\
         }\
      }\
   else {\
      red = USToUC((clr).r);\
      green = USToUC((clr).g);\
      blue = USToUC((clr).b);\
      alpha = USToUC((clr).a);\
      }\
   } while(0)

/*
 * For copying a {struct color} to another
 */
#define CopyColor(dest, src) do {\
   strcpy((dest).name, (src).name);\
   (dest).r = (src).r;\
   (dest).g = (src).g;\
   (dest).b = (src).b;\
   (dest).a = (src).a;\
   (dest).id = (src).id;\
   } while(0)

/*
 * Comparing {struct color}. Returns 1 for match, 0 for different
 */
#define ColorEqual(clr1, clr2) (\
   ((clr1).r == (clr2).r && (clr1).g == (clr2).g &&\
    (clr1).b == (clr2).b && (clr1).a == (clr2).a)\
   || ((clr1).id && (clr2).id && (clr1).id == (clr2).id)\
   )

/*
 * Type conversion macros (for gamma correction)
 */

#define USToUC(ushort) (unsigned char)(ushort >> 8)
#define USToUC_V4(dest, src) do {\
   dest[0] = USToUC(src[0]);\
   dest[1] = USToUC(src[1]);\
   dest[2] = USToUC(src[2]);\
   dest[3] = USToUC(src[3]);\
   } while(0)

/* GLfloat is a C float */
#define GLFToUS(flt) (unsigned short)((flt)*65535)
#define USToGLF(ushort) (GLfloat)((ushort)/65535.0)
#define USToGLF_V4(dest, src) do {\
   dest[0] = USToGLF(src[0]);\
   dest[1] = USToGLF(src[1]);\
   dest[2] = USToGLF(src[2]);\
   dest[3] = USToGLF(src[3]);\
   } while(0)

#define GLFToUC(glf) (unsigned char) (255.0*(glf))
#define UCToGLF(uchar) (GLfloat) ((uchar)/255.0)

/*
 * For gamma encode/decode color operations.
 *
 * Unicon color values are in linear color units. All computer screens
 * convert from linear units to sRGB units by using the value gamma. Thus,
 * The Unicon color values (linear) are converted to sRGB space and given
 * to OpenGL (which has no notion of gamma correction, unless using ver. 4+).
 *
 * Encoding transforms from linear-to-sRGB space.
 * Decoding transforms from sRGB-to-linear space.
 * Assume that gamma has no effect on transparency (alpha).
 */
#define EncodeGamma(flt, gamma) pow(flt, 1/gamma)
#define DecodeGamma(flt, gamma) pow(flt, gamma)

/*
 * Specifically for gamma correction for pixmaps used in gl_strimage()
 * Takes an unsigned short, converts it to a GLfloat, applies gamma
 * correction, then converts the GLfloat to unsigned char.
 */
#define EncodeGammaUSToUC(ushort, gamma) \
   (unsigned char)(GLFToUC(EncodeGamma(USToGLF(ushort),gamma)))
#define DecodeGammaUSToUC(ushort, gamma) \
   (unsigned char)(GLFToUC(DecodeGamma(USToGLF(ushort),gamma)))

#define EncodeGammaUS(ushort, gamma) \
   (unsigned short)(GLFToUS(EncodeGamma(USToGLF(ushort),gamma)))
#define EncodeGammaUS_V4(dest, src, gamma) do {\
   dest[0] = EncodeGammaUS(src[0], gamma);\
   dest[1] = EncodeGammaUS(src[1], gamma);\
   dest[2] = EncodeGammaUS(src[2], gamma);\
   dest[3] = src[3];\
   } while(0)

#define EncodeGammaUSToUC_V4(dest, src, gamma) do {\
   dest[0] = EncodeGammaUS(src[0], gamma) >> 8;\
   dest[1] = EncodeGammaUS(src[1], gamma) >> 8;\
   dest[2] = EncodeGammaUS(src[2], gamma) >> 8;\
   dest[3] = src[3] >> 8;\
   } while(0)

/*
 * Decodes gamma correction in the form of (unsigned short). Converts
 * to a float to perform correction and converts back to (unsigned
 * short).
 */
#define DecodeGammaUS(ushort, gamma) \
   (unsigned short) GLFToUS(DecodeGamma(USToGLF(ushort), gamma))

/* Same as above but for unsigned char */
#define DecodeGammaUC(uchar, gamma) \
   (unsigned char) GLFToUC(DecodeGamma(UCToGLF(uchar), gamma))

#define EncodeGamma_V4(dest, src, gamma) do {\
   dest[0] = EncodeGamma(src[0], gamma);\
   dest[1] = EncodeGamma(src[1], gamma);\
   dest[2] = EncodeGamma(src[2], gamma);\
   dest[3] = src[3];\
   } while(0)

#define DecodeGamma_V4(dest, src, gamma) do {\
   dest[0] = DecodeGamma(src[0], gamma);\
   dest[1] = DecodeGamma(src[1], gamma);\
   dest[2] = DecodeGamma(src[2], gamma);\
   dest[3] = src[3];\
   } while(0)


/*
 * Sets the color specified by {color} to sRGB space with gamma as the
 * "foreground" (current OpenGL) color.
 * {color} must be an array of unsigned short of size 4.
 */
#define SetColorState(color, gamma) do {\
   GLfloat norm[4], normg[4];\
   USToGLF_V4(norm, color);\
   EncodeGamma_V4(normg, norm, gamma);\
   glColor4fv(normg);\
   } while(0)

/* Let's avoid magic numbers */
#define FG 1
#define BG 0

/*
 * Gets a context color (fg or bg) depending on the reverse attribute
 */
#define GetContextColorUS(w, is_fg, r, g, b, a) do {\
   wcp wcr = &((w)->window->wcrender);\
   if (wcr->reverse) {\
      if (is_fg)\
         GetColorUS(w, wcr->glbg, r, g, b, a);\
      else\
         GetColorUS(w, wcr->glfg, r, g, b, a);\
      }\
   else {\
      if (is_fg)\
         GetColorUS(w, wcr->glfg, r, g, b, a);\
      else\
         GetColorUS(w, wcr->glbg, r, g, b, a);\
      }\
   } while(0)

#define GetContextColorUC(w, is_fg, r, g, b, a) do {\
   wcp wcr = &((w)->window->wcrender);\
   if (wcr->reverse) {\
      if (is_fg)\
         GetColorUC(w, wcr->glbg, r, g, b, a);\
      else\
         GetColorUC(w, wcr->glfg, r, g, b, a);\
      }\
   else {\
      if (is_fg)\
         GetColorUC(w, wcr->glfg, r, g, b, a);\
      else\
         GetColorUC(w, wcr->glbg, r, g, b, a);\
      }\
   } while(0)

/*
 * This macro sets the OpenGL color state based on {w}'s render context's
 * reverse and gamma attributes. {Drawop} is specified. {is_fg} specifies
 * whether the render context's fg or bg color is the desired drawing
 * color.
 */
#define SetDrawopColorState(w, drawop, is_fg) do {\
   wsp ws = (w)->window;\
   wcp wcr = &(ws->wcrender);\
   unsigned short color[4];\
\
   if (is_fg)\
      GetContextColorUS(w, FG, color[0], color[1], color[2], color[3]);\
   else\
      GetContextColorUS(w, BG, color[0], color[1], color[2], color[3]);\
\
   /* set fg to (fg ^ bg) */\
   if (drawop == GL2D_DRAWOP_REVERSE) {\
      unsigned short bg[4];\
      if (is_fg)\
         GetContextColorUS(w, BG, bg[0], bg[1], bg[2], bg[3]);\
      else\
         GetContextColorUS(w, FG, bg[0], bg[1], bg[2], bg[3]);\
\
      /* calculate xor */\
      color[0] = color[0] ^ bg[0];\
      color[1] = color[1] ^ bg[1];\
      color[2] = color[2] ^ bg[2];\
      color[3] = 65535; /* transparency is disabled for "xor" */\
      }\
   SetColorState(color, wcr->gamma);\
   } while(0)

/*
 * Clear screen to either the fg or bg color.
 * Accounts for gamma and reverse.
 */
#define ClearScreenToColor(w, is_fg) do {\
   unsigned short clr[4];\
   GLfloat norm[4], normg[4];\
   GetContextColorUS(w,is_fg,clr[0],clr[1],clr[2],clr[3]);\
   USToGLF_V4(norm, clr);\
   EncodeGamma_V4(normg, norm, (w)->window->wcrender.gamma);\
   glDepthRange(0,1.0);\
   glClearColor(normg[0], normg[1], normg[2], normg[3]);\
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\
   } while(0)

/*
 * Rendering macros
 */

/*
 * The RenderRealarray*() family of macros are for rendering geometric
 * primitives
 */

/*
 * RenderRealarray(double *v, int n)
 * Renders (v) which is an array of 2d coordinates of size (n).
 */
#ifdef GL2D_DRAWARRAYS
#define RenderRealarray(v, n) do {\
   glEnableClientState(GL_VERTEX_ARRAY);\
   glVertexPointer(2, GL_DOUBLE, 0, (void *) &(v)[1]);\
   glDrawArrays((v)[0], 0, (n-1)/2);\
   glDisableClientState(GL_VERTEX_ARRAY);\
   } while(0)
#else /* GL2D_DRAWARRAYS */
#define RenderRealarray(v, n) do {\
   int i;\
   glBegin(v[0]);\
   for (i = 1; i < n; i+=2)\
      glVertex2d((GLdouble)v[i], (GLdouble)v[i+1]);\
   glEnd();\
   } while(0)
#endif /* GL2D_DRAWARRAYS */

#define RenderRealarrayFillstyle(w, v, n, stencil_mask) do {\
   switch ((w)->window->wcrender.fillstyle) {\
      case GL2D_FILL_SOLID:\
         SetStencilFunc(w, stencil_mask);\
         RenderRealarray(v, n);\
         break;\
      case GL2D_FILL_MASKED:\
         SetStencilFunc(w, stencil_mask | GL2D_PATT_BIT);\
         RenderRealarray(v, n);\
         break;\
      case GL2D_FILL_TEXTURED:\
         SetStencilFunc(w, stencil_mask);\
         SetDrawopColorState(w, wcr->drawop, BG);\
         RenderRealarray(v, n);\
         SetStencilFunc(w, stencil_mask | GL2D_PATT_BIT);\
         SetDrawopColorState(w, wcr->drawop, FG);\
         RenderRealarray(v, n);\
         break;\
      default:\
         return Failed;\
         break;\
      }\
   DefaultStencilFunc(w);\
   } while(0)

#define RenderRealarrayLinestyle(w, v, n, vseg, nseg) do {\
   int linestyle = (w)->window->wcrender.linestyle;\
   if (linestyle == GL2D_LINE_SOLID) {\
      RenderRealarray(v, n);\
      }\
   else {\
      if (linestyle == GL2D_LINE_STRIPED) {\
         int drawop = (w)->window->wcrender.drawop;\
         SetDrawopColorState(w, drawop, BG);\
         RenderRealarray(v, n); \
         SetDrawopColorState(w, drawop, FG);\
         }\
      RenderRealarray(vseg, nseg);\
      }\
   } while(0)



/*
 * For the following *Render*Rect() macros:
 * (x1, y1) specifies the top left corner and (x2, y2) specifies the bottom
 * right corner. The rectangles are rendered to be front facing
 * (counterclockwise).
 * These macros are used for rendering image primitives
 */
#define _RenderFilledRect(wx1, wy1, wx2, wy2, near) do {\
   glBegin(GL_TRIANGLE_FAN);\
   glVertex3d((GLdouble)wx1,(GLdouble)wy1,(GLdouble)near);\
   glVertex3d((GLdouble)wx1,(GLdouble)wy2,(GLdouble)near);\
   glVertex3d((GLdouble)wx2,(GLdouble)wy2,(GLdouble)near);\
   glVertex3d((GLdouble)wx2,(GLdouble)wy1,(GLdouble)near);\
   glEnd();\
   } while(0)

#define RenderFilledRect(x, y, wd, ht, near) do {\
   double wx1, wy1, wx2, wy2;\
   wx1 = GLWORLDCOORD_X(w, x);\
   wy1 = GLWORLDCOORD_Y(w, y);\
   wx2 = GLWORLDCOORD_X(w, x+wd);\
   wy2 = GLWORLDCOORD_Y(w, y+ht);\
   _RenderFilledRect(wx1, wy1, wx2, wy2, near);\
   } while(0)

#define _RenderTexturedRect(w, x, y, wd, ht, texwd, texht, near) do {\
   double wx1, wy1, wx2, wy2;\
   float tx1, ty1, tx2, ty2;\
\
   tx1 = ty2 = 0.0;\
   tx2 = (float)wd/(float)texwd;\
   ty1 = (float)ht/(float)texht;\
   wx1 = GLWORLDCOORD_X(w, x);\
   wy1 = GLWORLDCOORD_Y(w, y);\
   wx2 = GLWORLDCOORD_X(w, x+wd);\
   wy2 = GLWORLDCOORD_Y(w, y+ht);\
\
   glBegin(GL_TRIANGLE_FAN);\
   glTexCoord2f(tx1,ty1); glVertex3d(wx1,wy1,near);\
   glTexCoord2f(tx1,ty2); glVertex3d(wx1,wy2,near);\
   glTexCoord2f(tx2,ty2); glVertex3d(wx2,wy2,near);\
   glTexCoord2f(tx2,ty1); glVertex3d(wx2,wy1,near);\
   glEnd();\
   } while(0)

#define RenderTexturedRect(w, x, y, wd, ht, texwd, texht, near) do {\
   glEnable(GL_TEXTURE_2D);\
   glDisable(GL_TEXTURE_GEN_S);\
   glDisable(GL_TEXTURE_GEN_T);\
   _RenderTexturedRect(w,x,y,wd,ht,texwd,texht,near);\
   glEnable(GL_TEXTURE_GEN_S);\
   glEnable(GL_TEXTURE_GEN_T);\
   glDisable(GL_TEXTURE_2D);\
   } while(0)


#define FILL_BG 1
#define TRANSP_BG 0
#define RenderTexturedBitmapRect(w, x, y, wd, ht, texwd, texht, near, fillbg)\
   do {\
   double wx1, wy1, wx2, wy2;\
   float tx1, ty1, tx2, ty2;\
\
   tx1 = ty2 = 0.0;\
   tx2 = (float)wd/(float)texwd;\
   ty1 = (float)ht/(float)texht;\
   wx1 = GLWORLDCOORD_X(w, x);\
   wy1 = GLWORLDCOORD_Y(w, y);\
   wx2 = GLWORLDCOORD_X(w, x+wd);\
   wy2 = GLWORLDCOORD_Y(w, y+ht);\
\
   if (fillbg) {\
      SetDrawopColorState(w, wcr->drawop, BG);\
      _RenderFilledRect(wx1, wy1, wx2, wy2, near);\
      SetDrawopColorState(w, wcr->drawop, FG);\
      }\
\
   glEnable(GL_TEXTURE_2D);\
   glDisable(GL_TEXTURE_GEN_S);\
   glDisable(GL_TEXTURE_GEN_T);\
\
   /* Apply pattern to stencil buffer by using texture and alpha test*/\
   glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);\
   glDepthMask(GL_FALSE);\
   EnableStencilWrite(GL2D_DRAW_BIT,0,GL_REPLACE);\
\
   /* first pass - render texture to stencil buffer */\
   glBegin(GL_TRIANGLE_FAN);\
   glTexCoord2f(tx1,ty1); glVertex3d(wx1,wy1,near);\
   glTexCoord2f(tx1,ty2); glVertex3d(wx1,wy2,near);\
   glTexCoord2f(tx2,ty2); glVertex3d(wx2,wy2,near);\
   glTexCoord2f(tx2,ty1); glVertex3d(wx2,wy1,near);\
   glEnd();\
\
   /* disable stencil writing */\
   DisableStencilWrite();\
   glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);\
   glDepthMask(GL_TRUE);\
\
   glEnable(GL_TEXTURE_GEN_S);\
   glEnable(GL_TEXTURE_GEN_T);\
   glDisable(GL_TEXTURE_2D);\
\
   /* second pass using stencil buffer */\
   SetStencilFunc(w, GL2D_DRAW_BIT);\
   _RenderFilledRect(wx1, wy1, wx2, wy2, near);\
   DefaultStencilFunc(w);\
   } while(0)

#define InitTexture2d(texptr) do {\
   glGenTextures(1, texptr);\
/*glprintf("generated texid %u\n",*texptr);*/\
   UGLBindTexture(GL_TEXTURE_2D, *texptr);\
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\
   glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\
   } while(0)

/*
 * Structures
 */

/*
 * For OpenGL, colors need not be allocated. Colors are defined with
 * RGBA values only. Use clamped doubles (0.0 - 1.0) for RGBA since
 * they are more representative to how colors are interpreted by machines.
 *
 * Negative (id) values indicate a mutable color, otherwise not mutable.
 */

/*
 * Get font size values in terms of pixels (px). Returns integer value.
 * These macros should only be used on a face whose size has been
 * initialized.
 *
 * ascender and descender are in 26.6 fixed point units... or not.
 * may be in ems
 *
 * As a design note, why don't we just unify these font macros
 * by using the ascent, descent, maxwidth, and height fields in
 * struct _wfont?
 */
#if HAVE_LIBFREETYPE
#define FT_ASCENT_I64(face) (int)((face)->size->metrics.ascender)
#define FT_DESCENT_I64(face) (int)((face)->size->metrics.descender)
#define FT_FWIDTH_I64(face) (int)((face)->size->metrics.max_advance)
#define FT_FHEIGHT_I64(face) (int)((face)->size->metrics.ascender -\
   (face)->size->metrics.descender)

#define FT_ASCENT(face) (int)((face)->size->metrics.ascender >> 6)
#define FT_DESCENT(face) (int)((face)->size->metrics.descender >> 6)
#define FT_FWIDTH(face) (int)((face)->size->metrics.max_advance >> 6)
#define FT_FHEIGHT(face) \
   (int)(((face)->size->metrics.ascender-(face)->size->metrics.descender) >> 6)
#else                                   /* HAVE_LIBFREETYPE */
/* placeholders for MSWin and OSX until implemented */
#define FT_ASCENT(face) 1
#define FT_DESCENT(face) 1
#define FT_FWIDTH(face) 1
#define FT_FHEIGHT(face) 1
#endif                                  /* HAVE_LIBFREETYPE */

/*
 * Macors check for {wc->font->face} for legacy 3D subwindow support.
 */
#if HAVE_LIBFREETYPE

#define GL_ASCENT(w) \
   ((w)->context->font->face ? FT_ASCENT((w)->context->font->face) : 0)
#define GL_DESCENT(w) \
   ((w)->context->font->face ? FT_DESCENT((w)->context->font->face) : 0)
#define GL_FWIDTH(w) \
   ((w)->context->font->face ? FT_FWIDTH((w)->context->font->face) : 0)
#define GL_FHEIGHT(w) \
   ((w)->context->font->face ? FT_FHEIGHT((w)->context->font->face) : 0)

#else                                   /* HAVE_LIBFREETYPE */

#define GL_ASCENT(w) ((w)->context->font->ascent)
#define GL_DESCENT(w) ((w)->context->font->descent)
/* Once this implementation gets ported to Windows, unify maxwidth/charwidth */
#ifdef XWindows
#define GL_FWIDTH(w) ((w)->context->font->maxwidth)
#endif                                  /* XWindows */
#ifdef MSWindows
#define GL_FWIDTH(w) ((w)->context->font->charwidth)
#endif                                  /* MSWindows */
#define GL_FHEIGHT(w) ((w)->context->font->height)

#endif                                  /* HAVE_LIBFREETYPE */

#define GL_LEADING(w) ((w)->context->leading)

#if HAVE_LIBFREETYPE

#define GL_ROWTOY(w,row) \
   ((w)->context->font->face ? ((row-1) * GL_LEADING(w) + GL_ASCENT(w)) : 0)
#define GL_COLTOX(w,col) \
   ((w)->context->font->face ? ((col-1) * GL_FWIDTH(w)) : 0)
#define GL_YTOROW(w,y) \
   ((w)->context->font->face ? \
   ((y>0) ? ((y)/GL_LEADING(w)+1) : ((y)/GL_LEADING(w))) : 0)
#define GL_XTOCOL(w,x) \
   ((w)->context->font->face ? (!GL_FWIDTH(w) ? (x) : ((x) / GL_FWIDTH(w))) : 0)
#define GL_MAXDESCENDER(w) ((w)->context->font->face ? GL_DESCENT(w) : 0)

#else                                   /* HAVE_LIBFREETYPE */

#define GL_ROWTOY(w,row) \
   ((w)->context->font ? ((row-1) * GL_LEADING(w) + GL_ASCENT(w)) : 0)
#define GL_COLTOX(w,col) \
   ((w)->context->font ? ((col-1) * GL_FWIDTH(w)) : 0)
#define GL_YTOROW(w,y) \
   ((w)->context->font ? \
   ((y>0) ? ((y)/GL_LEADING(w)+1) : ((y)/GL_LEADING(w))) : 0)
#define GL_XTOCOL(w,x) \
   ((w)->context->font ? (!GL_FWIDTH(w) ? (x) : ((x) / GL_FWIDTH(w))) : 0)
#define GL_MAXDESCENDER(w) ((w)->context->font ? GL_DESCENT(w) : 0)

#endif                                  /* HAVE_LIBFREETYPE */

/*
 * compute text pixel width
 */
#define GL_TEXTWIDTH(w, s, len) drawstringhelper(w, 0, 0, 0, s, len, 0, 0)

/****************************************   end ../h/../h/../h/opengl.h   */
#else                                   /* HAVE_LIBGL */


/****************************************  from ../h/../h/../h/direct3d.h:  */

/*
 * Direct 3D port of the 3D facilities. Not implemented yet.
 */

/*
 * Redefinitions of various OpenGL integer scalar values.
 * Using these names, portable code can function without OpenGL.
 * If OpenGL is present, they are defined as OpenGL-native, see opengl.h
 * On other platforms, they may be a simple integer enumeration or may be
 * redefined to values native to that platform.
 */

#define U3D_POINTS         1
#define U3D_LINES          2
#define U3D_LINE_STRIP     3
#define U3D_LINE_LOOP      4
#define U3D_TRIANGLES      5
#define U3D_TRIANGLE_FAN   6
#define U3D_TRIANGLE_STRIP 7
#define U3D_QUADS          8
#define U3D_QUAD_STRIP     9
#define U3D_POLYGON       10

#define U3D_REPLACE      100
#define U3D_BLEND        101
#define U3D_MODULATE     102

#define GLfloat float
#define GLubyte unsigned char
#define GLuint unsigned int


/****************************************   end ../h/../h/../h/direct3d.h   */
#endif                                  /* HAVE_LIBGL */

/*
 * # of POLL_INTERVAL intervals for determining OpenGL 2D graphics refresh rate
 * (see pollevent())
 */
#define FLUSH_POLL_INTERVAL 10

#define REDRAW_CUBE             0x010
#define REDRAW_CYLINDER         0x020
#define REDRAW_DISK             0x030
#define REDRAW_LINE             0x040
#define REDRAW_POINT            0x050
#define REDRAW_POLYGON          0x060
#define REDRAW_SEGMENT          0x070
#define REDRAW_SPHERE           0x080
#define REDRAW_TORUS            0x090
#define REDRAW_FG               0x0A0
#define REDRAW_FILLPOLYGON      0x0B0
#define REDRAW_IDENTITY         0x0C0
#define REDRAW_MATRIXMODE       0x0D0
#define REDRAW_POPMATRIX        0x0E0
#define REDRAW_PUSHMATRIX       0x0F0
#define REDRAW_ROTATE           0x100
#define REDRAW_SCALE            0x110
#define REDRAW_TEXTURE          0x120
#define REDRAW_TEXCOORD         0x130
#define REDRAW_TRANSLATE        0x140
#define REDRAW_DIM              0x150
#define REDRAW_LINEWIDTH        0x160
#define REDRAW_TEXMODE          0x170
#define REDRAW_FONT3D           0x180
#define REDRAW_DRAWSTRING3D     0x190
#define REDRAW_MARK             0x1A0
#define REDRAW_ENDMARK          0x1B0
#define REDRAW_MESHMODE         0x1C0
#define REDRAW_PICK             0x1D0
#define REDRAW_MULTMATRIX       0x1E0
#define REDRAW_NORMALS          0x1F0
#define REDRAW_NORMODE          0x200
#define REDRAW_SLICES           0x210
#define REDRAW_RINGS            0x220

/* aliases for better comprehension */
#define GL3D_CUBE       REDRAW_CUBE
#define GL3D_CYLINDER   REDRAW_CYLINDER
#define GL3D_DISK       REDRAW_DISK
#define GL3D_SPHERE     REDRAW_SPHERE
#define GL3D_TORUS      REDRAW_TORUS
#define GL3D_IDENTITY   REDRAW_IDENTITY
#define GL3D_MATRIXMODE REDRAW_MATRIXMODE
#define GL3D_POPMATRIX  REDRAW_POPMATRIX
#define GL3D_PUSHMATRIX REDRAW_PUSHMATRIX
#define GL3D_ROTATE     REDRAW_ROTATE
#define GL3D_SCALE      REDRAW_SCALE
#define GL3D_TEXTURE    REDRAW_TEXTURE
#define GL3D_TRANSLATE  REDRAW_TRANSLATE
#define GL3D_FONT       REDRAW_FONT3D
#define GL3D_DRAWSTRING REDRAW_DRAWSTRING3D
#define GL3D_MARK       REDRAW_MARK
#define GL3D_ENDMARK    REDRAW_ENDMARK
#define GL3D_MESHMODE   REDRAW_MESHMODE

#endif                                  /* Graphics3D */

#ifndef MAXXOBJS
   #define MAXXOBJS 256
#endif                                  /* MAXXOBJS */

#ifndef DMAXCOLORS
   #define DMAXCOLORS 256
#endif                                  /* DMAXCOLORS */

#ifndef MAXCOLORNAME
   #define MAXCOLORNAME 40
#endif                                  /* MAXCOLORNAME */

#ifndef MAXFONTWORD
   #define MAXFONTWORD 40
#endif                                  /* MAXFONTWORD */

#define DEFAULTFONTSIZE 14

#define FONTATT_SPACING         0x01000000
#define FONTFLAG_MONO           0x00000001
#define FONTFLAG_PROPORTIONAL   0x00000002

#define FONTATT_SERIF           0x02000000
#define FONTFLAG_SANS           0x00000004
#define FONTFLAG_SERIF          0x00000008

#define FONTATT_SLANT           0x04000000
#define FONTFLAG_ROMAN          0x00000010
#define FONTFLAG_ITALIC         0x00000020
#define FONTFLAG_OBLIQUE        0x00000040

#define FONTATT_WEIGHT          0x08000000
#define FONTFLAG_LIGHT          0x00000100
#define FONTFLAG_MEDIUM         0x00000200
#define FONTFLAG_DEMI           0x00000400
#define FONTFLAG_BOLD           0x00000800

#define FONTATT_WIDTH           0x10000000
#define FONTFLAG_CONDENSED      0x00001000
#define FONTFLAG_NARROW         0x00002000
#define FONTFLAG_NORMAL         0x00004000
#define FONTFLAG_WIDE           0x00008000
#define FONTFLAG_EXTENDED       0x00010000

#define FONTATT_CHARSET         0x20000000
#define FONTFLAG_LATIN1         0x00020000
#define FONTFLAG_LATIN2         0x00040000
#define FONTFLAG_CYRILLIC       0x00080000
#define FONTFLAG_ARABIC         0x00100000
#define FONTFLAG_GREEK          0x00200000
#define FONTFLAG_HEBREW         0x00400000
#define FONTFLAG_LATIN6         0x00800000

#define FONT_OUTLINE            0x00000001
#define FONT_POLYGON            0x00000002
#define FONT_TEXTURE            0x00000003
#define FONT_BITMAP             0x00000004
#define FONT_PIXMAP             0x00000005
#define FONT_EXTRUDE            0x00000006

/*
 * EVENT HANDLING
 *
 * Each window keeps an associated queue of events waiting to be
 * processed.  The queue consists of <eventcode,x,y> triples,
 * where eventcodes are strings for normal keyboard events, and
 * integers for mouse and special keystroke events.
 *
 * The main queue is an icon list.  In addition, there is a queue of
 * old keystrokes maintained for cooked mode operations, maintained
 * in a little circular array of chars.
 */
#define EQ_MOD_CONTROL (1L<<16L)
#define EQ_MOD_META    (1L<<17L)
#define EQ_MOD_SHIFT   (1L<<18L)

#define EVQUESUB(w,i) *evquesub(w,i)
#define EQUEUELEN 256

/*
 * mode bits for the Icon window context (as opposed to X context)
 */

#define ISINITIAL(w)    ((w)->window->bits & 1)
#define ISINITIALW(ws)   ((ws)->bits & 1)
#define ISCURSORON(w)   ((w)->window->bits & 2)
#define ISCURSORONW(ws) ((ws->bits) & 2)
/* bit 4 is available */
#define ISREVERSE(w)    ((w)->context->bits & 8)
#define ISXORREVERSE(w) ((w)->context->bits & 16)
#define ISXORREVERSEW(w) ((w)->bits & 16)
#define ISCLOSED(w)     ((w)->window->bits & 64)
#define ISRESIZABLE(w)  ((w)->window->bits & 128)
#define ISEXPOSED(w)    ((w)->window->bits & 256)
#define ISCEOLON(w)     ((w)->window->bits & 512)
#define ISECHOON(w)     ((w)->window->bits & 1024)

#define SETCURSORON(w)  ((w)->window->bits |= 2)
/* bit 4 is available */
#define SETREVERSE(w)   ((w)->context->bits |= 8)
#define SETXORREVERSE(w) ((w)->context->bits |= 16)
#define SETCLOSED(w)    ((w)->window->bits |= 64)
#define SETRESIZABLE(w) ((w)->window->bits |= 128)
#define SETEXPOSED(w)   ((w)->window->bits |= 256)
#define SETCEOLON(w)    ((w)->window->bits |= 512)
#define SETECHOON(w)    ((w)->window->bits |= 1024)

#define CLRCURSORON(w)  ((w)->window->bits &= ~2)
/* bit 4 is available */
#define CLRREVERSE(w)   ((w)->context->bits &= ~8)
#define CLRXORREVERSE(w) ((w)->context->bits &= ~16)
#define CLRCLOSED(w)    ((w)->window->bits &= ~64)
#define CLRRESIZABLE(w) ((w)->window->bits &= ~128)
#define CLREXPOSED(w)   ((w)->window->bits &= ~256)
#define CLRCEOLON(w)    ((w)->window->bits &= ~512)
#define CLRECHOON(w)    ((w)->window->bits &= ~1024)

#ifdef XWindows
#define ISZOMBIE(w)     ((w)->window->bits & 1)
#define SETZOMBIE(w)    ((w)->window->bits |= 1)
#define CLRZOMBIE(w)    ((w)->window->bits &= ~1)
#endif                                  /* XWindows */

#ifdef MSWindows
#define ISTOBEHIDDEN(ws)  ((ws)->bits & 4096)
#define SETTOBEHIDDEN(ws)  ((ws)->bits |= 4096)
#define CLRTOBEHIDDEN(ws)  ((ws)->bits &= ~4096)
#endif                                  /* MSWindows */

#define ISTITLEBAR(ws) ((ws)->bits & 8192)
#define SETTITLEBAR(ws) ((ws)->bits |= 8192)
#define CLRTITLEBAR(ws) ((ws)->bits &= ~8192)


/*
 * Window Resources
 * Icon "Resources" are a layer on top of the window system resources,
 * provided in order to facilitate resource sharing and minimize the
 * number of calls to the window system.  Resources are reference counted.
 * These data structures are simple sets of pointers
 * into internal window system structures.
 */



/*
 * Fonts are allocated within displays.
 */
typedef struct _wfont {
  int           refcount;
  int           serial;                 /* serial # */
  struct _wfont *previous, *next;
  char          type;
  int           size;
  void          *fonts;
#ifdef XWindows
  char        * name;                   /* name for WAttrib and fontsearch */
  int           ascent;                 /* font dimensions */
  int           descent;
  int           height;
  int           maxwidth;               /* max width of one char */
#ifdef HAVE_XFT
  XftFont     * fsp;
#else                                   /* HAVE_XFT */
  XFontStruct * fsp;                    /* X font pointer */
#endif                                  /* HAVE_XFT */
#endif                                  /* XWindows */
#ifdef MSWindows
  char        * name;                   /* name for WAttrib and fontsearch */
  HFONT         font;
  LONG          ascent;
  LONG          descent;
  LONG          charwidth;
  LONG          height;
#endif                                  /* MSWindows */
} wfont, *wfp;

/*
 * These structures and definitions are used for colors and images.
 */
typedef struct {
   long red, green, blue;               /* color components, linear 0 - 65535*/
   } LinearColor;

struct palentry {                       /* entry for one palette member */
   LinearColor clr;                     /* RGB value of color */
   char used;                           /* nonzero if char is used */
   char valid;                          /* nonzero if entry is valid & opaque */
   char transpt;                        /* nonzero if char is transparent */
   };

/*
 * Color formats to be used with imgdata
 */
#define UCOLOR_RGB   1
#define UCOLOR_BGR   2

struct imgdata {                        /* image loaded from a file */
   int width, height;                   /* image dimensions */
   int format;
   int is_bottom_up;
   struct palentry *paltbl;             /* pointer to palette table */
   unsigned char *data;                 /* pointer to image data */
   };

struct imgmem {
   int x, y, width, height;
#ifdef XWindows
   XImage *im;
#endif                                  /* XWindows */
#ifdef MSWindows
   COLORREF *crp;
#endif                                  /* MSWindows */
   };

#define TCH1 '~'                        /* usual transparent character */
#define TCH2 0377                       /* alternate transparent character */
#define PCH1 ' '                        /* punctuation character */
#define PCH2 ','                        /* punctuation character */


/*
 * Texture management requires that we be able to lookup and reuse
 * existing textures, as well as support dynamic window-based textures.
 */
#ifdef Graphics3D

#define INITTEXTURENUM 64

typedef struct _wtexture {
   int          refcount;
   int          serial;                 /* serial # */

   int width, height;
   struct _wbinding *w;

  struct _wtexture *previous, *next;

   int          textype;        /* 1 = file, 2 = window (descrip), 3 = string*/
   struct descrip d;
   struct {                     /* if type = 1, we store file attributes */
      int           size;
      int          timestamp;
      } fattr;

#if HAVE_LIBGL
   GLubyte *tex;
   GLuint texName;                      /* GL texture name*/
#endif

   } wtexture, *wtp;
#endif                                  /* Graphics3D */


/*
 * Displays are maintained in a global list in rwinrsc.r.
 */
typedef struct _wdisplay {
  int           refcount;
  int           serial;   /* serial # */

#ifdef MSWindows
  char          name[MAXDISPLAYNAME];
#endif                                  /* MSWindows*/

#ifdef XWindows
  char          name[MAXDISPLAYNAME];
  Display *     display;
  GC            icongc;
  Colormap      cmap;
#ifdef HAVE_XFT
  XFontStruct   *xfont;
#endif                                  /* HAVE_XFT */
#ifdef Graphics3D
  XVisualInfo   *vis;
#endif                                  /* Graphics3D */
  Cursor        cursors[NUMCURSORSYMS];
  int           numColors;            /* allocated color info */
  int           sizColors;            /* # elements of alloc. color array */
  struct wcolor *colors;
  int           screen;
  int           numFonts;
  wfp           fonts;
  int           buckets[16384];       /* hash table for quicker lookups */
#endif                                  /* XWindows */
#ifdef Graphics3D
  int           ntextures;            /* # textures actually used */
  int           nalced;               /* number allocated */
  wtp           stex;
  int           maxstex;
#endif                                  /* Graphics3D */
  double        gamma;
  struct _wdisplay *previous, *next;
} *wdp;

/*
 * "Context" comprises the graphics context, and the font (i.e. text context).
 * Foreground and background colors (pointers into the display color table)
 * are stored here to reduce the number of window system queries.
 * Contexts are allocated out of a global array in rwinrsrc.c.
 */
typedef struct _wcontext {
  int           refcount;
  int           serial;                 /* serial # */
  struct _wcontext *previous, *next;
  int           clipx, clipy, clipw, cliph;
  char          *patternname;
  wfp           font;
  int           dx, dy;
  int           fillstyle;
  int           drawop;
  int           rgbmode;                /* 0=auto, 1=24, 2=48, 3=norm */
  double        gamma;                  /* gamma correction value */
  int           bits;                   /* context bits */

  wdp           display;
#ifdef XWindows
  GC            gc;                        /* X graphics context */
  int           fg, bg;
  int           linestyle;
  int           linewidth;
  int           leading;                /* inter-line leading */
#endif                                  /* XWindows */
#ifdef MSWindows
  LOGPEN        pen;
  LOGPEN        bgpen;
  LOGBRUSH      brush;
  LOGBRUSH      bgbrush;
  HRGN          cliprgn;
  HBITMAP       pattern;
  SysColor      fg, bg;
  char          *fgname, *bgname;
  int           leading, bkmode;
#endif                                  /* MSWindows*/

#ifdef Graphics3D

#if HAVE_LIBGL
#ifdef XWindows
  GLXContext    ctx;                    /* context for "gl" windows */
#endif                                  /* XWindows */
#ifdef MSWindows
  HGLRC         ctx;
#endif                                  /* MSWindows */
#endif                                  /* HAVE_LIBGL */

  int           dim;                    /* # of coordinates per vertex */
  int           is_3D;                  /* flag for 3D windows */
  char          buffermode;             /* 3D buffering flag */
  char          meshmode;               /* fillpolygon mesh mode */

  int           slices;                 /* slices and rings for level of */
  int           rings;                  /* detail sphere etal to be drawn */

/* selection parameters   */
  int           selectionenabled;       /* selection is enabled */
  int           selectionrendermode;    /* selection code should be executed */
  int           selectionavailablename; /* what int code to use for OpenGL name  */
  char **       selectionnamelist;      /* all of the current used names  */
  int           selectionnamecount;     /* how many - used so far   */
  int           selectionnamelistsize;  /* current available size  */
  int           app_use_selection3D;    /* the application uses 3D selection */

  double        eyeupx, eyeupy, eyeupz;    /* eye up vector */
  double        eyedirx, eyediry, eyedirz; /* eye direction vector */
  double        eyeposx, eyeposy, eyeposz; /* eye position */

  double        fov;                    /* field of view angle */

  struct b_realarray  *normals;         /* vertex normals data */

  int           normode;                /* normals on, off or auto */
  int           numnormals;             /* # of normals used */

  int           autogen;  /* flag to automatically generate texture coordinate */
  int           texmode;                /* textures on or off */
  int           numtexcoords;           /* # of texture coordinates used */
  struct b_realarray  *texcoords;       /* texture coordinates */

  int           curtexture;             /* subscript of current texture */
#endif                                  /* Graphics3D */
} wcontext, *wcp;

/*
 * Native facilities include the following child controls (windows) that
 * persist on the canvas and intercept various events.
 */
#ifdef MSWindows
#define CHILD_BUTTON 0
#define CHILD_SCROLLBAR 1
#define CHILD_EDIT 2
typedef struct childcontrol {
   int  type;                           /* what kind of control? */
   HWND win;                            /* child window handle */
   HFONT font;
   char *id;                            /* child window string id */
} childcontrol;
#endif                                  /* MSWindows */

/*
 *
 */

#define REAL_WSTATE     1
#define SUBWIN_WSTATE   2
#define TEXTURE_WSTATE  4

#define CHILD_WIN2D      1
#define CHILD_WIN3D      2
#define CHILD_WINTEXTURE 3

#define TEXTURE_RECORD   1
#define TEXTURE_WINDOW   2

/*
 * This is the "canvas": it is also called a window state.
 * "Window state" includes the actual X window and references to a large
 * number of resources allocated on a per-window basis.  Windows are
 * allocated out of a global array in rwinrsrc.c.  Windows remember the
 * first WMAXCOLORS colors they allocate, and deallocate them on clearscreen.
 */
typedef struct _wstate {
  int           refcount;               /* reference count */
  int           serial;                 /* serial # */
  struct _wstate *previous, *next;

#ifdef Graphics3D
  int type;
  int texindex;
#endif                                  /* Graphics3D */

  int           inputmask;              /* user input mask */
  int           pixheight;              /* backing pixmap height, in pixels */
  int           pixwidth;               /* pixmap width, in pixels */
  char          *windowlabel;           /* window label */
  char          *iconimage;             /* icon pixmap file name */
  char          *iconlabel;             /* icon label */
  struct imgdata initimage;             /* initial image data */
  struct imgdata initicon;              /* initial icon image data */
  int           y, x;                   /* current cursor location, in pixels*/
  int           pointery,pointerx;      /* current mouse location, in pixels */
  int           posy, posx;             /* desired upper lefthand corner */
  int           real_posx, real_posy;   /* real (canvas=normal) position */
  unsigned int  height;                 /* window height, in pixels */
  unsigned int  width;                  /* window width, in pixels */
  unsigned int  minheight;              /* minimum window height, in pixels */
  unsigned int  minwidth;               /* minimum window width, in pixels */
  int           bits;                   /* window bits */
  int           theCursor;              /* index into cursor table */
  word          timestamp;              /* last event time stamp */
  char          eventQueue[EQUEUELEN];  /* queue of cooked-mode keystrokes */
  int           eQfront, eQback;
  char          *cursorname;
  struct descrip filep, listp;          /* icon values for this window */
  struct wbind_list *children;
  struct _wbinding *parent;
  wdp                display;
#ifdef XWindows
  Window        win;                    /* X window */
  Pixmap        pix;                    /* current screen state */
  Pixmap        initialPix;             /* an initial image to display */
  Window        iconwin;                /* icon window */
  Pixmap        iconpix;                /* icon pixmap */
  Visual        *vis;
#ifdef HAVE_XFT
  XftDraw       *winDraw,*pixDraw;
#endif                                  /* HAVE_XFT */
  int           normalx, normaly;       /* pos to remember when maximized */
  int           normalw, normalh;       /* size to remember when maximized */
  int           numColors;              /* allocated (used) color info */
  int           sizColors;              /* malloced size of theColors */
  short         *theColors;             /* indices into display color table */
  int           numiColors;             /* allocated color info for the icon */
  int           siziColors;             /* malloced size of iconColors */
  short         *iconColors;            /* indices into display color table */
  char *selectiondata;
  int           iconic;                 /* window state; icon, window or root*/
  int           iconx, icony;           /* location of icon */
  unsigned int  iconw, iconh;           /* width and height of icon */
  long          wmhintflags;            /* window manager hints */
#endif                                  /* XWindows */
#ifdef MSWindows
  HWND          win;                    /* client window */
  HWND          iconwin;                /* client window when iconic */
  HBITMAP       pix;                    /* backing bitmap */
  HBITMAP       iconpix;                /* backing bitmap */
  HBITMAP       initialPix;             /* backing bitmap */
  HBITMAP       theOldPix;
  int           hasCaret;
  HCURSOR       curcursor;
  HCURSOR       savedcursor;
  HMENU         menuBar;
  int           nmMapElems;
  char **       menuMap;
  HWND          focusChild;
  int           nChildren;
  childcontrol *child;
#endif                                  /* MSWindows */
#ifdef Graphics3D
  int            is_3D;        /* flag for 3D windows */
  struct descrip funclist;    /* descriptor to hold list of 3d functions */
#endif                                  /* Graphics3D */
  int            no;          /* new field added for child windows */
} wstate, *wsp;

/*
 * Icon window file variables are actually pointers to "bindings"
 * of a window and a context.  They are allocated out of a global
 * array in rwinrsrc.c.  There is one binding per Icon window value.
 */
typedef struct _wbinding {
  int refcount;
  int serial;
  struct _wbinding *previous, *next;
  wcp context;
  wsp window;
} wbinding, *wbp;

struct wbind_list {
  struct _wbinding *child;
  struct wbind_list *next;
};

/*
 * Gamma Correction value to compensate for nonlinear monitor color response
 */
#ifndef GammaCorrection
#define GammaCorrection 2.5
#endif                                  /* GammaCorrection */

/*
 * Attributes
 */

#define A_ASCENT        1
#define A_BG            2
#define A_CANVAS        3
#define A_CEOL          4
#define A_CLIPH         5
#define A_CLIPW         6
#define A_CLIPX         7
#define A_CLIPY         8
#define A_COL           9
#define A_COLUMNS       10
#define A_CURSOR        11
#define A_DEPTH         12
#define A_DESCENT       13
#define A_DISPLAY       14
#define A_DISPLAYHEIGHT 15
#define A_DISPLAYWIDTH  16
#define A_DRAWOP        17
#define A_DX            18
#define A_DY            19
#define A_ECHO          20
#define A_FG            21
#define A_FHEIGHT       22
#define A_FILLSTYLE     23
#define A_FONT          24
#define A_FWIDTH        25
#define A_GAMMA         26
#define A_GEOMETRY      27
#define A_HEIGHT        28
#define A_ICONIC        29
#define A_ICONIMAGE     30
#define A_ICONLABEL     31
#define A_ICONPOS       32
#define A_IMAGE         33
#define A_INPUTMASK     34
#define A_LABEL         35
#define A_LEADING       36
#define A_LINES         37
#define A_LINESTYLE     38
#define A_LINEWIDTH     39
#define A_PATTERN       40
#define A_POINTERCOL    41
#define A_POINTERROW    42
#define A_POINTERX      43
#define A_POINTERY      44
#define A_POINTER       45
#define A_POS           46
#define A_POSX          47
#define A_POSY          48
#define A_RESIZE        49
#define A_REVERSE       50
#define A_RGBMODE       51
#define A_ROW           52
#define A_ROWS          53
#define A_SIZE          54
#define A_VISUAL        55
#define A_WIDTH         56
#define A_WINDOWLABEL   57
#define A_X             58
#define A_Y             59
#define A_SELECTION     60

/* 3D attributes */
#define A_DIM           61
#define A_EYE           62
#define A_EYEPOS        63
#define A_EYEDIR        64
#define A_EYEUP         65
#define A_LIGHT         66
#define A_LIGHT0        67
#define A_LIGHT1        68
#define A_LIGHT2        69
#define A_LIGHT3        70
#define A_LIGHT4        71
#define A_LIGHT5        72
#define A_LIGHT6        73
#define A_LIGHT7        74
#define A_TEXTURE       75
#define A_TEXMODE       76
#define A_TEXCOORD      77

#define A_TITLEBAR      78
#define A_BUFFERMODE    79
#define A_MESHMODE      80
#define A_SLICES        81
#define A_RINGS         82
#define A_PICK          83
#define A_NORMODE       84
#define A_FOV           85
#define A_GLVERSION     86
#define A_GLVENDOR      87
#define A_GLRENDERER    88

#define NUMATTRIBS      88

#define XICONSLEEP      20 /* milliseconds */

/****************************************   end ../h/../h/graphics.h   */
#endif                                  /* Graphics */

#ifdef Audio


/****************************************  from ../h/../h/audio.h:  */

/*
 * audio.h - audio structure used in Unicon's audio interface
 */

 struct AudioFile{
        int doneflag;
        char* fname;
        };

typedef struct AudioFile AudioStruct;
typedef struct AudioFile * AudioPtr;

/****************************************   end ../h/../h/audio.h   */
#endif                                  /* Audio */

#ifdef PosixFns


/****************************************  from ../h/../h/posix.h:  */


/*
 * posix.h - includes for posix interface
 */

/*
 * Copyright 1997 Shamim Mohamed.
 *
 * Modification and redistribution is permitted as long as this (and any
 * other) copyright notices are kept intact.
 */

#if UNIX
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <dirent.h>
#include <unistd.h>
#include <utime.h>
#include <sys/resource.h>

#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pwd.h>
#include <grp.h>
#endif                                  /* UNIX */


#ifdef NT

#include <string.h>   /* _stricmp (fxposix.ri getpw), strlen in String() etc. */
#include<ws2tcpip.h>

#include <sys/timeb.h>
#include <sys/locking.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/utime.h>
#include <fcntl.h>
#include <io.h>
#include <time.h>
#include <process.h>
#define NAME_MAX FILENAME_MAX
#ifdef PATH_MAX
#undef PATH_MAX
#endif                                          /* PATH_MAX */
#define PATH_MAX FILENAME_MAX
#define MAXHOSTNAMELEN          256
#else                                   /* NT */
#ifndef NAME_MAX
#define NAME_MAX _POSIX_NAME_MAX
#endif                                  /* not defined NAME_MAX */
#define SOCKET int
#endif                                  /* NT */

#if defined(SUN) || defined(HP) || defined(IRIS4D)
#include <sys/file.h>

extern int sys_nerr;
extern char *sys_errlist[];

#ifndef UX10
#ifndef NAME_MAX
#define NAME_MAX 1024
#endif                                  /* NAME_MAX */
#endif


#ifdef SYSV
#define bcopy(a, b, n) memcopy(b, a, n)
#endif
#endif                                  /* SUN || HP */

#ifdef HP
#define FASYNC O_SYNC
#endif

#if defined(BSD) || defined(HP) || defined(BSD_4_4_LITE)
#include <sys/param.h>
#endif

#if (defined(BSD) || defined(BSD_4_4_LITE)) && !defined(MacOS)
#define Setpgrp() setpgrp(0, 0)
#else
#define Setpgrp() setpgrp()
#endif

extern stringint signalnames[];

#ifdef IRIS4D
#include <limits.h>
#include <sys/param.h>
#endif                                  /* IRIS4D */

#ifdef NT
extern WORD wVersionRequested;
extern WSADATA wsaData;
extern int werr;
extern int WINSOCK_INITIAL;
#endif                                  /* NT */

/****************************************   end ../h/../h/posix.h   */
#endif                                  /* PosixFns */

#if COMPILER
#ifdef NT
/* 
 * Declare flock (which is defined in fxposix.ri, just before it is used).
 * It's needed here because rtt splits fxposix.ri into several C files 
 * when producing code for iconc, which separates the definition from its use.
 */
int flock(int fd, int operation);
#endif                                  /* NT */
#endif                                  /* COMPILER */


#ifdef Messaging


/****************************************  from ../h/../h/messagin.h:  */

/*
 * messaging.h - includes for Internet protocol support
 */

/**********************************************************************\
*       (c) Copyright 2000 by Steve Lumos.  All rights reserved.       *
\**********************************************************************/

#include <tp.h>
#include <setjmp.h>

/* State transition macros */
#define MFIN(mfile, s)    (mfile->state & s)
#define MFSTATE(mfile, s) (mfile->state = s)
#define MFENTER(mfile, s) (mfile->state |= s)
#define MFLEAVE(mfile, s) (mfile->state &= ~(s))

/* Header fields that we know about */
enum {
  H_CONTENT_TYPE = 1,
  H_FROM,
  H_HOST,
  H_LOCATION,
  H_TO,
  H_USER_AGENT
};
#define NUMHEADERS 5

/* Where runerrs for Messaging start */
#define MRUNERRMIN 1200
#define MRUNERRMAX 1250

/****************************************   end ../h/../h/messagin.h   */
#endif                                  /* Messaging */



/****************************************  from ../h/../h/rexterns.h:  */

/*
 * External declarations for the run-time system.
 */

/*
 * External declarations common to the compiler and interpreter.
 */

extern TRuntime_Status rt_status;
extern struct b_proc *op_tbl;   /* operators available for string invocation */
extern int op_tbl_sz;           /* number of operators in op_tbl */
extern int debug_info;          /* flag: debugging information is available */
extern int err_conv;            /* flag: error conversion is supported */
extern int dodump;              /* termination dump */
extern int line_info;           /* flag: line information is available */
extern char *file_name;         /* source file for current execution point */
#ifndef MultiProgram
extern int line_num;            /* line number for current execution point */
#endif                                  /* MultiProgram */

extern unsigned char allchars[];/* array for making one-character strings */
extern char *blkname[];         /* print names for block types. */
extern char *currend;           /* current end of memory region */
extern dptr *quallist;          /* start of qualifier list */
extern int bsizes[];            /* sizes of blocks */
extern int firstd[];            /* offset (words) of first descrip. */
extern uword segsize[];         /* size of hash bucket segment */

extern struct b_coexpr *stklist;/* base of co-expression stack list */
extern struct b_cset blankcs;   /* ' ' */
extern struct b_cset lparcs;    /* '(' */
extern struct b_cset rparcs;    /* ')' */
extern struct b_cset k_digits;  /* &digits */
extern struct b_cset k_lcase;   /* &lcase */
extern struct b_cset k_ucase;   /* &ucase */
extern struct b_cset k_letters; /* &letters */
extern struct b_cset k_ascii;   /* &ascii */
extern struct b_cset k_cset;    /* &cset */
extern struct descrip blank;    /* blank */
extern struct descrip emptystr; /* empty string */

extern struct descrip kywd_dmp; /* descriptor for &dump */
extern struct descrip nullptr;  /* descriptor with null block pointer */
extern struct descrip lcase;    /* lowercase string */
extern struct descrip letr;     /* letter "r" */

#ifndef Concurrent
extern struct descrip maps2;    /* second argument to map() */
extern struct descrip maps3;    /* third argument to map() */
#endif /* Concurrent */

extern struct descrip nulldesc; /* null value */
extern struct descrip onedesc;  /* one */
extern struct descrip ucase;    /* uppercase string */
extern struct descrip zerodesc; /* zero */

extern word mstksize;           /* size of main stack in words */
extern word stksize;            /* size of co-expression stacks in words */
extern word qualsize;           /* size of string qualifier list */
extern word memcushion;         /* memory region cushion factor */
extern word memgrowth;          /* memory region growth factor */
#ifdef DescripAmpAllocated
extern struct descrip stattotal;/* cumulative total of all static allocations */
extern int blktotalIncrFlag;
#else                                   /* DescripAmpAllocated */
extern uword stattotal;         /* cumulative total of all static allocations */
#endif                                  /* DescripAmpAllocated */
                                /* N.B. not currently set */

#ifdef HAVE_LIBPTHREAD
extern pthread_rwlock_t __environ_lock;
#endif                                  /*HAVE_LIBPTHREAD && !SUN */

#ifndef Concurrent
extern struct tend_desc *tend;  /* chain of tended descriptors */
#endif                                  /* Concurrent */

extern int num_cpu_cores;

#ifdef Concurrent
extern pthread_mutex_t **mutexes;
extern word nmutexes;
extern word maxmutexes;

extern pthread_mutexattr_t rmtx_attr;

extern pthread_t GCthread;
extern int thread_call;
extern int NARthreads;

extern pthread_cond_t **condvars;
extern word* condvarsmtxs;
extern word ncondvars;
extern word maxcondvars;

extern int is_concurrent;
extern struct threadstate *global_curtstate;

#ifndef HAVE_KEYWORD__THREAD
   extern pthread_key_t tstate_key;
#endif

#if ConcurrentCOMPILER
extern struct region *Public_stringregion;
extern struct region *Public_blockregion;

extern word mutexid_stringtotal;
extern word mutexid_blocktotal;
extern word mutexid_coll;
extern word list_ser;
extern word intern_list_ser;
/*
 * Fake out a possible fail, to trick iconc.
 */
extern int improbable;
#endif                                   /* ConcurrentCOMPILER */

#endif                                  /* Concurrent */

/*
 * Externals that are conditional on features.
 */

#ifdef ISQL
   extern HENV ISQLEnv;
   extern struct ISQLFile *isqlfiles;
#endif

#ifdef FncTrace
   extern struct descrip kywd_ftrc;     /* descriptor for &ftrace */
#endif                                  /* FncTrace */

#if defined(Polling) && !defined(Concurrent)
   extern int pollctr;
#endif                                  /* Polling && !Concurrent */

extern char typech[];
extern word oldsum;
extern struct descrip csetdesc;         /* cset descriptor */
extern struct descrip eventdesc;        /* event descriptor */
extern struct b_iproc mt_llist;
extern struct descrip rzerodesc;        /* real descriptor */
extern struct b_real realzero;          /* real zero block */

#ifdef DosFncs
   extern char *zptr;
#endif                                  /* DosFncs */

#if EBCDIC == 2
   extern char ToEBCDIC[], FromEBCDIC[]; /* ASCII<->EBCDIC maps */
#endif                                  /* EBCDIC == 2 */

   extern struct region rootstring;
   extern struct region rootblock;

/*
 * Externals conditional on MultiProgram: multi loaded programs.
 */
#ifndef MultiProgram
   extern struct region *curstring;
   extern struct region *curblock;
#if !ConcurrentCOMPILER
   extern dptr glbl_argp;               /* argument pointer */
   extern struct descrip value_tmp;     /* list argument to Op_Apply */
   extern struct descrip k_current;     /* &current */
   extern struct descrip k_errortext;   /* &errortext */
   extern int have_errval;              /* &errorvalue has a legal value */
   extern int k_errornumber;            /* value of &errornumber */
   extern int t_errornumber;            /* tentative k_errornumber value */
   extern int t_have_val;               /* tentative have_errval flag */
   extern struct descrip k_errorvalue;  /* value of &errorvalue */
   extern int k_level;                  /* &level */
   extern struct descrip k_subject;     /* &subject */
   extern struct descrip kywd_pos;      /* descriptor for &pos */
#ifdef PatternType
   extern int k_patindex;               /* index for pattern element */
#endif                         /* Pattern Type */
   extern struct descrip kywd_ran;      /* descriptor for &random */
   extern struct descrip t_errorvalue;  /* tentative k_errorvalue value */

#ifdef DescripAmpAllocated
   extern struct descrip blktotal;      /* cumul total of all block allocs */
   extern struct descrip strtotal;      /* cumul total of all string allocs */
#else                                   /* DescripAmpAllocated */
   extern uword blktotal;               /* cumul total of all block allocs */
   extern uword strtotal;               /* cumul total of all string allocs */
#endif                                  /* DescripAmpAllocated */
#endif                                  /* ConcurrentCOMPILER */
   extern struct b_file k_errout;       /* value of &errout */
   extern struct b_file k_input;        /* value of &input */
   extern struct b_file k_output;       /* value of &output */
   extern struct descrip kywd_err;      /* &error */
   extern struct descrip kywd_prog;     /* descriptor for &prog */
   extern struct descrip kywd_trc;      /* descriptor for &trace */
   extern struct descrip k_eventcode;   /* &eventcode */
   extern struct descrip k_eventsource; /* &eventsource */
   extern struct descrip k_eventvalue;  /* &eventvalue */
   extern struct descrip k_main;        /* value of &main */

   extern word coll_tot;                /* total number of collections */
   extern word coll_stat;               /* collections from static reqests */
   extern word coll_str;                /* collections from string requests */
   extern word coll_blk;                /* collections from block requests */
   extern dptr globals;                 /* start of global variables */
   extern dptr eglobals;                /* end of global variables */
   extern dptr gnames;                  /* start of global variable names */
   extern dptr egnames;                 /* end of global variable names */
   extern dptr estatics;                /* end of static variables */

   extern int n_globals;                /* number of global variables */
   extern int n_statics;                /* number of static variables */
   extern struct b_coexpr *mainhead;    /* &main */

   extern int longest_dr;
   extern struct b_proc_list **dr_arrays;

#ifdef PosixFns
extern struct descrip amperErrno;
#endif                                  /* PosixFns */
#endif                                  /* MultiProgram */

#ifdef Concurrent
   #ifdef HAVE_KEYWORD__THREAD
   /*
    * HAVE_KEYWORD__THREAD should be detected by autoconf (and isn't yet).
    */
   extern __thread struct threadstate roottstate;
   extern __thread struct threadstate *curtstate;
   #else                                        /* HAVE_KEYWORD__THREAD */
   extern struct threadstate roottstate;
   #endif                                       /* HAVE_KEYWORD__THREAD */
#else                                   /* Concurrent */
   extern struct threadstate roottstate;
   extern struct threadstate *curtstate;
#endif                                  /* Concurrent */

/*
 * Externals that differ between compiler and interpreter.
 */
#if !COMPILER
   /*
    * External declarations for the interpreter.
    */
#ifndef Concurrent
   extern struct pf_marker *pfp;                /* Procedure frame pointer */
   extern struct ef_marker *efp;                /* Expression frame pointer */
   extern struct gf_marker *gfp;                /* Generator frame pointer */
   extern inst ipc;                     /* Interpreter program counter */
   extern inst oldipc;                    /* the previous ipc, fix returned line zero */
   extern word *sp;             /* Stack pointer */
   extern int ilevel;
   extern word *stack;                  /* interpreter stack base */
   extern word *stackend;               /* end of evaluation stack */
#endif                                  /* !Concurrent */
#endif                                  /* !COMPILER */

#if !COMPILER || ConcurrentCOMPILER
   extern struct pstrnm pntab[];
   extern int pnsize;

/*probably Thread Safe*/
   #ifdef ExecImages
      extern int dumped;                /* the interpreter has been dumped */
   #endif                               /* ExecImages */
#endif                                  /* !COMPILER || ConcurrentCOMPILER */

   #if defined(MultiProgram)
      extern struct progstate *curpstate;
      extern struct progstate rootpstate;
   #endif                                       /* MultiProgram */


#if !COMPILER
   #ifdef MultiProgram
      extern int noMTevents;            /* no MT events during GC */
   #ifdef Concurrent
      extern pthread_mutex_t mutex_noMTevents;
   #endif                                       /* Concurrent */

   #else                                /* MultiProgram */
      extern char *code;                /* start of icode */
      extern char *ecode;               /* end of icode */
      extern char *endcode;             /* end of icode? */
      extern struct ipc_line *ilines;   /* start of line # table */
      extern struct ipc_line *elines;   /* end of line # table */
      extern struct ipc_fname *filenms; /* start of file name table */
      extern struct ipc_fname *efilenms;/* end of file name table */
      extern dptr statics;              /* start of static variables */
      extern char *strcons;             /* start of the string constants */
      extern dptr fnames;               /* field names */
      extern dptr efnames;              /* end of field names */
      extern word *records;
      extern int *ftabp;                /* field table pointer */
      #ifdef FieldTableCompression
         extern word ftabwidth, foffwidth;
         extern unsigned char *ftabcp;
         extern short *ftabsp;
      #endif                            /* FieldTableCompression */
      extern dptr xargp;
      extern word xnargs;
      extern dptr field_argp;

      extern word lastop;
   #endif                               /* MultiProgram */

      extern struct b_proc *stubrec;

#else                                   /* !COMPILER */

#if ConcurrentCOMPILER
   extern pthread_mutex_t mutex_noMTevents;
#endif                                  /* ConcurrentCOMPILER */
   extern struct descrip statics[];     /* array of static variables */
   extern struct b_proc *builtins[];    /* pointers to builtin functions */
   extern int noerrbuf;                 /* error buffering */
#if !ConcurrentCOMPILER
   extern struct p_frame *pfp;          /* procedure frame pointer */
#endif                                  /* ConcurrentCOMPILER */
   extern struct descrip trashcan;      /* dummy descriptor, never read */
   extern int largeints;                /* flag: large integers supported */

#endif                                  /* COMPILER */

extern stringint attribs[], drawops[];

/*
 * graphics
 */
#ifdef Graphics

   extern wbp wbndngs;
   extern wcp wcntxts;
   extern wsp wstates;
   extern int GraphicsLeft, GraphicsUp, GraphicsRight, GraphicsDown;
   extern int GraphicsHome, GraphicsPrior, GraphicsNext, GraphicsEnd;
   extern int win_highwater, canvas_serial, context_serial;
   extern clock_t starttime;            /* start time in milliseconds */

   #ifndef MultiProgram
      extern struct descrip kywd_xwin[];
      extern struct descrip lastEventWin;
      extern int lastEvFWidth, lastEvLeading, lastEvAscent;
      extern struct descrip amperCol;
      extern struct descrip amperRow;
      extern struct descrip amperX;
      extern struct descrip amperY;
      extern struct descrip amperInterval;
      extern uword xmod_control, xmod_shift, xmod_meta;
   #endif                               /* MultiProgram */

   #ifdef XWindows
      extern struct _wdisplay * wdsplys;
      extern stringint cursorsyms[];
   #endif                               /* XWindows */

   #ifdef MSWindows
      extern HINSTANCE mswinInstance;
      extern int ncmdShow;
   #endif                               /* MSWindows */

   extern unsigned long ConsoleFlags;
   #ifdef ConsoleWindow
      extern FILE *ConsoleBinding;
      extern char ConsoleStringBuf[];
      extern char *ConsoleStringBufPtr;
   #endif                               /* ConsoleWindow */

#ifdef Graphics3D
   extern struct descrip gl_torus;
   extern struct descrip gl_cube;
   extern struct descrip gl_sphere;
   extern struct descrip gl_cylinder;
   extern struct descrip gl_disk;
   extern struct descrip gl_rotate;
   extern struct descrip gl_translate;
   extern struct descrip gl_scale;
   extern struct descrip gl_popmatrix;
   extern struct descrip gl_pushmatrix;
   extern struct descrip gl_identity;
   extern struct descrip gl_matrixmode;
   extern struct descrip gl_texture;
   extern stringint redraw3Dnames[];
   #ifndef MultiProgram
         extern struct descrip amperPick;
   #endif                               /* MultiProgram */

extern wfont gfont;
extern wfont *start_font, *end_font, *curr_font;

#endif                                  /* Graphics3D */

#endif                                  /* Graphics */

#ifdef PosixFns
extern struct descrip posix_lock, posix_timeval, posix_stat, posix_message,
  posix_passwd, posix_group, posix_servent, posix_hostent, posix_rusage;
extern dptr timeval_constr;
#endif                                  /* PosixFns */

#ifdef Messaging
extern int M_open_timeout;
#endif                                  /* Messaging */

/* patchable globals */
extern char patchpath[];
extern char uniroot[];

extern char *lognam;
extern FILE *flog;

#ifdef PatternType
extern struct b_pelem EOP;
#endif                                  /* PatternType */

#if NT
extern struct  b_cons *LstTmpFiles;
#endif                                  /* NT */

#ifdef Audio
extern int isPlaying;
#endif                                  /* Audio */

#ifdef VerifyHeap
extern long vrfy;
extern long vrfyOpCtrl;
extern void vrfyLog(const char *fmt, ...);
extern void vrfy_Live_Table(struct b_table *b);
#endif                  /* VerifyHeap */

#ifdef DEVELOPMODE
extern void dbgUFL();
extern void dbgUtrace();
extern int dbgbrkpoint();
#endif                  /* DEVELOPMODE */

/****************************************   end ../h/../h/rexterns.h   */


/****************************************  from ../h/../h/rproto.h:  */

/*
 * Prototypes for run-time functions.
 */

/*
 * Prototypes common to the compiler and interpreter.
 */
void            EVInit          (void);
int             activate        (dptr val, struct b_coexpr *ncp, dptr result);
word            add             (word a,word b,int *over_flowp);
void            addmem  (struct b_set *ps,struct b_selem *pe, union block **pl);
struct astkblk  *alcactiv       (void);
#ifdef MultiProgram
struct b_cset   *alccset_0      (void);
struct b_cset   *alccset_1      (void);
#undef alcfile
struct b_file   *alcfile        (FILE *fd,int status,dptr name);
#define alcfile (curpstate->Alcfile)
struct b_file   *alcfile_1      (FILE *fd,int status,dptr name);
union block     *alchash_0      (int tcode);
union block     *alchash_1      (int tcode);
struct b_slots  *alcsegment_0   (word nslots);
struct b_slots  *alcsegment_1   (word nslots);
#undef alclist_raw
struct b_list   *alclist_raw    (uword size, uword nslots);
#define alclist_raw (curpstate->Alclist_raw)
struct b_list   *alclist_raw_1  (uword size, uword nslots);
struct b_list   *alclist_0      (uword size, uword nslots);
struct b_list   *alclist_1      (uword size, uword nslots);
struct b_lelem  *alclstb_0      (uword nslots,uword first,uword nused);
struct b_lelem  *alclstb_1      (uword nslots,uword first,uword nused);
#undef alcreal
struct b_real   *alcreal        (double val);
#define alcreal (curpstate->Alcreal)
struct b_real   *alcreal_1      (double val);
struct b_selem  *alcselem_0     (dptr mbr,uword hn);
struct b_selem  *alcselem_1     (dptr mbr,uword hn);
#undef alcstr
char            *alcstr (char   *s,word slen);
#define alcstr (curpstate->Alcstr)
char            *alcstr_1       (char   *s,word slen);
struct b_telem  *alctelem_0     (void);
struct b_telem  *alctelem_1     (void);
struct b_tvtbl  *alctvtbl_0     (dptr tbl,dptr ref,uword hashnum);
struct b_tvtbl  *alctvtbl_1     (dptr tbl,dptr ref,uword hashnum);
struct b_tvmonitored  *alctvmonitored   (dptr tv, word ipc_in);
void assign_event_functions(struct progstate *p, struct descrip cs);
int invaluemask(struct progstate *p, int evcode, struct descrip *val);
#ifdef PatternType
struct b_pattern        *alcpattern_0 (word size);
struct b_pattern        *alcpattern_1 (word size);
#if COMPILER
struct b_pelem  *alcpelem_0     (word);
struct b_pelem  *alcpelem_1     (word);
#else                                   /* COMPILER */
struct b_pelem  *alcpelem_0     (word, word *);
struct b_pelem  *alcpelem_1     (word, word *);
#endif                                  /* COMPILER */
#endif                                  /* PatternType */
#else                                   /* MultiProgram */
struct b_cset   *alccset        (void);
struct b_file   *alcfile        (FILE *fd,int status,dptr name);
union block     *alchash        (int tcode);
struct b_slots  *alcsegment     (word nslots);
struct b_list   *alclist_raw    (uword size, uword nslots);
struct b_list   *alclist        (uword size, uword nslots);
struct b_lelem  *alclstb        (uword nslots,uword first,uword nused);
struct b_real   *alcreal        (double val);
struct b_selem  *alcselem       (dptr mbr,uword hn);
char            *alcstr         (char   *s,word slen);
struct b_telem  *alctelem       (void);
struct b_tvtbl  *alctvtbl       (dptr tbl,dptr ref,uword hashnum);
#ifdef PatternType
struct b_pattern        *alcpattern     (word size);
#if COMPILER
struct b_pelem  *alcpelem(word pattern_code);
#else                                   /* COMPILER */
struct b_pelem  *alcpelem(word pattern_code, word *origin_ipc);
#endif                                  /* COMPILER */
#endif                                  /* PatternType */
#endif                                  /* MultiProgram */
#ifdef Arrays
struct b_list   *alclisthdr     (uword size, union block *bptr);
#endif                                  /* Arrays */

char            *alc_strerror   (int);
void             set_errortext  (int i);
void             set_syserrortext(int ern);
#if HAVE_LIBZ
void             set_gzerrortext(gzFile f);
#endif                                  /* HAVE_LIBZ */

struct b_cons   *alccons        (union block *);

int             anycmp          (dptr dp1,dptr dp2);
int             anycmpBase      (dptr dp1,dptr dp2,int sortType);
#ifdef Arrays
int             arraytolist     (struct descrip *arr);
int             cplist2realarray(dptr dp, dptr dp2, word i, word j,
                                 word skipcopyelements);
#endif                                  /* Arrays */
int             bfunc           (void);
struct b_proc   *bi_strprc      (dptr s, C_integer arity);
#if __clang__ || __GNUC__
/* Stop clang and gcc from warning "control may reach end of non-void function" when calling this function */
void            c_exit          (int i)  __attribute__ ((noreturn,nothrow));
#else
void            c_exit          (int i);
#endif /* __clang__ */
int             c_get           (struct b_list *hp, struct descrip *res);
void            c_put           (struct descrip *l, struct descrip *val);
int             c_inserttable   (union block **pbp, int n, dptr x);
int             c_insertset     (union block **pps, dptr pd);
int             CmdParamToArgv  (char *s, char ***avp, int dequote);
int             cnv_c_dbl       (dptr s, double *d);
int             cnv_c_int       (dptr s, C_integer *d);
int             cnv_c_str       (dptr s, dptr d);
#ifdef MultiProgram
int             cnv_cset_0      (dptr s, dptr d);
int             cnv_cset_1      (dptr s, dptr d);
#else
int             cnv_cset        (dptr s, dptr d);
#endif                                  /* MultiProgram */
int             cnv_ec_int      (dptr s, C_integer *d);
int             cnv_eint        (dptr s, dptr d);
int             cnv_list        (dptr s, dptr d);
#ifdef MultiProgram
#undef cnv_int
int             cnv_int         (dptr s, dptr d);
#define cnv_int (curpstate->Cnvint)
int             cnv_int_1       (dptr s, dptr d);
#undef cnv_real
int             cnv_real        (dptr s, dptr d);
#define cnv_real (curpstate->Cnvreal)
int             cnv_real_1      (dptr s, dptr d);
#undef cnv_str
int             cnv_str (dptr s, dptr d);
#define cnv_str (curpstate->Cnvstr)
int             cnv_str_1       (dptr s, dptr d);
int             cnv_tcset_0     (struct b_cset *cbuf, dptr s, dptr d);
int             cnv_tcset_1     (struct b_cset *cbuf, dptr s, dptr d);
int             cnv_tstr_0      (char *sbuf, dptr s, dptr d);
int             cnv_tstr_1      (char *sbuf, dptr s, dptr d);
#else                                   /* MultiProgram */
int             cnv_int         (dptr s, dptr d);
int             cnv_real        (dptr s, dptr d);
int             cnv_str         (dptr s, dptr d);
int             cnv_tcset       (struct b_cset *cbuf, dptr s, dptr d);
int             cnv_tstr        (char *sbuf, dptr s, dptr d);
#endif                                  /* MultiProgram */
#ifdef PatternType
struct b_pelem * Alternate(struct b_pelem * L,struct b_pelem * R);
struct b_pelem * Arbno_Simple(struct b_pelem *pe);
struct b_pelem *Bracket(struct b_pelem *E,struct b_pelem * P,
                            struct b_pelem * A);
#ifdef MultiProgram
int             cnv_pattern_0(dptr s, dptr p);
int             cnv_pattern_1(dptr s, dptr p);
#else                                   /* MultiProgram */
int             cnv_pattern(dptr s, dptr p);
#endif                                  /* MultiProgram */
struct b_pelem *Concat          (struct b_pelem * L, struct b_pelem *R, int Incr );
struct b_pelem *Copy            (struct b_pelem * P);

union block *pattern_make(int stck_size, struct b_pelem * pnext,
                          int pattern_code, int index, struct descrip param);
union block *pelem_make(struct b_pelem * pnext, int pattern_code,
                        int index, struct descrip param);

dptr            bi_pat          (int what);
int             arg_image       (struct descrip arg, int pcode, int type,
                                   dptr result);
int             construct_image (dptr left, dptr s, dptr r, dptr result);

struct b_pattern * breakx_make(struct b_pelem * B);
int pattern_image(union block *pe, int prev_index, dptr result,
                  int peCount, int pe_index, int stop_index);
#endif                                  /* PatternType */
int             co_chng         (struct b_coexpr *ncp, struct descrip *valloc,
                                   struct descrip *rsltloc,
                                   int swtch_typ, int first);
void            co_init         (struct b_coexpr *sblkp);
void            coacttrace      (struct b_coexpr *ccp,struct b_coexpr *ncp);
void            cofailtrace     (struct b_coexpr *ccp,struct b_coexpr *ncp);
void            corettrace      (struct b_coexpr *ccp,struct b_coexpr *ncp);
int             coswitch        (word *old, word *new, int first);
int             cphash          (dptr dp1, dptr dp2, word n, int tcode);
#ifdef MultiProgram
int             cplist_0        (dptr dp1,dptr dp2,word i,word j);
int             cplist_1        (dptr dp1,dptr dp2,word i,word j);
#ifdef Arrays
int             cprealarray_0   (dptr dp1,dptr dp2,word i,word j);
int             cpintarray_0    (dptr dp1,dptr dp2,word i,word j);
int             cprealarray_1   (dptr dp1,dptr dp2,word i,word j);
int             cpintarray_1    (dptr dp1,dptr dp2,word i,word j);
struct descrip listtoarray(dptr l);
#endif                                  /* Arrays */
int             cpset_0         (dptr dp1,dptr dp2,word size);
int             cpset_1         (dptr dp1,dptr dp2,word size);
int             cptable_0       (dptr dp1,dptr dp2,word size);
int             cptable_1       (dptr dp1,dptr dp2,word size);
void            EVStrAlc_0      (word n);
void            EVStrAlc_1      (word n);
#else                                   /* MultiProgram */
int             cplist          (dptr dp1,dptr dp2,word i,word j);
int             cpset           (dptr dp1,dptr dp2,word size);
int             cptable         (dptr dp1,dptr dp2,word size);
#ifdef Arrays
int             cprealarray     (dptr dp1,dptr dp2,word i,word j);
int             cpintarray      (dptr dp1,dptr dp2,word i,word j);
struct descrip listtoarray(dptr l);
#endif                                  /* Arrays */
#endif                                  /* MultiProgram */
void            cpslots         (dptr dp1,dptr slotptr,word i, word j);
int             csetcmp         (unsigned int *cs1,unsigned int *cs2);
int             cssize          (dptr dp);
word            cvpos           (word pos, word len);
void            datainit        (void);
#ifdef MultiProgram
void            deallocate_0    (union block *bp);
void            deallocate_1    (union block *bp);
#else                                   /* MultiProgram */
void            deallocate      (union block *bp);
#endif                                  /* MultiProgram */
int             def_c_dbl       (dptr s, double df, double * d);
int             def_c_int       (dptr s, C_integer df, C_integer * d);
int             def_c_str       (dptr s, char * df, dptr d);
int             def_cset        (dptr s, struct b_cset * df, dptr d);
int             def_ec_int      (dptr s, C_integer df, C_integer * d);
int             def_eint        (dptr s, C_integer df, dptr d);
int             def_int         (dptr s, C_integer df, dptr d);
int             def_real        (dptr s, double df, dptr d);
int             def_str         (dptr s, dptr df, dptr d);
int             def_tcset (struct b_cset *cbuf,dptr s,struct b_cset *df,dptr d);
int             def_tstr        (char *sbuf, dptr s, dptr df, dptr d);
word            div3            (word a,word b, int *over_flowp);
int             doasgn          (dptr dp1,dptr dp2);
int             doimage         (int c,int q);
int             dp_pnmcmp       (struct pstrnm *pne,dptr dp);
void            drunerr         (int n, double v);
void            dumpact         (struct b_coexpr *ce);
struct b_proc * dynrecord       (dptr s, dptr fields, int n);
void            env_int (char *name,word *variable,int non_neg, uword limit);
int             equiv           (dptr dp1,dptr dp2);
int             err             (void);
void            err_msg         (int n, dptr v);
void            error           (char *s1, char *s2);
#if __clang__ || __GNUC__
/* Stop clang and gcc from warning "control may reach end of non-void function" when calling this function */
void            fatalerr        (int n,dptr v) __attribute__ ((noreturn,nothrow));
#else
void            fatalerr        (int n,dptr v);
#endif /* __clang__ || __GNUC__ */
int             findcol         (word *ipc_in);
char            *findfile       (word *ipc_in);
#ifdef MultiProgram
char            *findfile_p     (word *ipc_in, struct progstate *);
#endif                                  /* MultiProgram */
int             findipc         (int line);
word            * findoldipc    (struct b_coexpr *ce, int level);
int             findline        (word *ipc_in);
#ifdef MultiProgram
int             findline_p      (word *ipc_in, struct progstate *);
#endif                                  /* MultiProgram */
int             findloc         (word *ipc_in);
int             findsyntax      (word *ipc_in);
int             fldlookup       (struct b_record *rec, const char * const fld);
void            fpetrap         (void);

int             getenv_r        (const char *name, char *buf, size_t len);
int             getvar          (char *s,dptr vp);

int             getkeyword      (char *s, dptr vp);

int             get_CCompiler   (char *s);
int             get_num_cpu_cores();
uword           hash            (dptr dp);
union block     **hchain        (union block *pb,uword hn);
union block     *hgfirst        (union block *bp, struct hgstate *state);
union block     *hgnext         (union block*b,struct hgstate*s,union block *e);
int             hitsyntax       (word *ipc_in);
union block     *hmake          (int tcode,word nslots,word nelem);
void            icon_init       (char *name, int *argcp, char *argv[]);
void            iconhost        (char *hostname);
int             idelay          (int n);
#ifdef MultiProgram
#ifdef TSTATARG
int             interp_0        (int fsig,dptr cargp, struct threadstate *curtstate);
int             interp_1        (int fsig,dptr cargp, struct threadstate *curtstate);
#else                                    /* TSTATARG */
int             interp_0        (int fsig,dptr cargp);
int             interp_1        (int fsig,dptr cargp);
#endif                                   /* TSTATARG */
#else                                   /* MultiProgram */
int             interp          (int fsig,dptr cargp);
#endif                                  /* MultiProgram */
#ifdef PatternType
#ifdef MultiProgram
int             internal_match_0(char * pat_sub, int Length, int Pat_S,
                                 struct descrip op, struct b_pelem * pattern,
                                 int *Start, int *Stop, int initial_cursor,
                                 int Anchored_Mode);
int             internal_match_1(char * pat_sub, int Length, int Pat_S,
                                 struct descrip op, struct b_pelem * pattern,
                                 int *Start, int *Stop, int initial_cursor,
                                 int Anchored_Mode);
#else                                   /* MultiProgram */
int             internal_match  (char * pat_sub, int Length, int Pat_S,
                                 struct descrip op, struct b_pelem * pattern,
                                 int *Start, int *Stop, int initial_cursor,
                                 int Anchored_Mode);
#endif                                  /* MultiProgram */
#endif                                  /* PatternType */
void            inttrap         (void);
void            irunerr         (int n, C_integer v);
int             iselect         (int fd, int t);
int             is_in_a_block_region(char *block);
int             Kascii          (dptr cargp);
int             Kcset           (dptr cargp);
int             Kdigits         (dptr cargp);
int             Klcase          (dptr cargp);
int             Kletters        (dptr cargp);
int             Kucase          (dptr cargp);
int             lexcmp          (dptr dp1,dptr dp2);
word            longread        (char *s,int width, word len,FILE *fname);
#if HAVE_LIBZ
word            gzlongread      (char *s,int width, word len,FILE *fd);
#endif                                  /* HAVE_LIBZ */
#ifdef FAttrib
#if UNIX
char *  make_mode               (mode_t st_mode);
#endif                                  /* UNIX */
#if MSDOS
char *  make_mode               (unsigned short st_mode);
#ifndef NTGCC
int     strcasecmp              (char *s1, char *s2);
int     strncasecmp             (char *s1, char *s2, int n);
#endif                                  /* NTGCC */
#endif                                  /* MSDOS */
#endif                                  /* FAttrib */
union block     **memb          (union block *pb,dptr x,uword hn, int *res);
void            mksubs          (dptr var,dptr val,word i,word j, dptr result);
word            mod3            (word a,word b, int *over_flowp);
word            mul             (word a,word b, int *over_flowp);
word            neg             (word a, int *over_flowp);
void            new_context     (int fsig, dptr cargp); /* w/o CoExpr: a stub*/
int             numcmp          (dptr dp1,dptr dp2,dptr dp3);
void            openlog         (char *p);
void            outimage        (FILE *f,dptr dp,int noimage);
#ifdef PatternType

union block     *pattern_make_pelem     (int stck_size, struct b_pelem * pe);
#endif                                  /* PatternType */
struct b_coexpr *popact         (struct b_coexpr *ce);
#if NT
unsigned long long int memorysize(int);
unsigned long long int physicalmemorysize();
#else                           /* NT */
unsigned long memorysize(int);
unsigned long physicalmemorysize();
#endif                          /* NT */
word            prescan         (dptr d);
int             pstrnmcmp       (struct pstrnm *a,struct pstrnm *b);
#ifdef PseudoPty
void ptclose(struct ptstruct *ptStruct);
struct ptstruct *ptopen(char *command);
int ptgetstrt(char *buffer, const int bufsiz, struct ptstruct *ptStruct,
              unsigned long waittime, int longread);
int ptgetstr(char *buffer, const int bufsiz, struct ptstruct *ptStruct,
             struct timeval *timeout);
int ptlongread(char *buffer, const int nelem, struct ptstruct *ptStruct);
int ptputstr(struct ptstruct *ptStruct, char *buffer, int bufsize);
int ptputc(char c, struct ptstruct *ptStruct);
int ptflush(struct ptstruct *ptStruct);
#ifdef MSWindows
struct b_list *findactivepty(struct b_list *lps);
#endif                                  /* MSWindows */

/*
 * System pty prototypes missing from standard includes due to XOPEN_SOURCE
 * issues, resulting in compiler warnings, at least on Linux. Of course,
 * just providing our own prototypes for library functions may cause problems
 * on other platforms; we may need to fix this or put it under an ifdef.
 */
int grantpt(int);
int unlockpt(int);
int posix_openpt(int);
int ptsname_r(int, char *, size_t);
#endif                                  /* PseudoPty */
int             pushact         (struct b_coexpr *ce, struct b_coexpr *actvtr);
int             putstr          (FILE *f,dptr d);
char            *qsearch        (char *key, char *base, int nel, int width,
                                   int (*cmp)());
int             qtos            (dptr dp,char *sbuf);
int              radix          (int sign, register int r, register char *s,
                                 register char *end_s, union numeric *result);
#ifdef PatternType
struct b_pelem  *ResolvePattern (struct b_pattern *pat);
#endif                                  /* PatternType */
#ifdef MultiProgram
char            *reserve_0      (int region, word nbytes);
char            *reserve_1      (int region, word nbytes);
#else                                   /* MultiProgram */
char            *reserve        (int region, word nbytes);
#endif                                  /* MultiProgram */
void            retderef                (dptr valp, word *low, word *high);
#if !NT
void rusage2rec(struct rusage *usg, struct descrip *dp, struct b_record **rp);
#endif                                  /* NT */
void            segvtrap        (void);
void            stkdump         (int);
word            sub             (word a,word b, int *over_flowp);
#if __clang__ || __GNUC__
/* Stop clang and gcc from warning "control may reach end of non-void function" when calling this function */
void            syserr          (char *s) __attribute__ ((noreturn,nothrow));
#else
void            syserr          (char *s);
#endif /* __clang__ || __GNUC__ */
struct b_coexpr *topact         (struct b_coexpr *ce);
void            xmfree          (void);
#ifdef MultiProgram
   void resolve                 (struct progstate *pstate);
   struct progstate *findicode  (word *opnd);
   struct b_coexpr *loadicode   (char *name, struct b_file *theInput,
      struct b_file *theOutput, struct b_file *theError,
      C_integer bs, C_integer ss, C_integer stk);
   void actparent (int eventcode);
   void mmrefresh               (void);
   int mt_activate   (dptr tvalp, dptr rslt, struct b_coexpr *ncp);
   struct progstate *findprogramforblock(union block *p);
   void EVVariable(dptr dx, int eventcode);
#else                                   /* MultiProgram */
   void resolve                 (void);
#endif                                  /* MultiProgram */

#ifdef ExternalFunctions
   dptr extcall                 (dptr x, int nargs, int *signal);
#endif                                  /* ExternalFunctions */

#ifdef LargeInts
#ifdef MultiProgram
   struct b_bignum *alcbignum_0 (word n);
   struct b_bignum *alcbignum_1 (word n);
#else                                   /* MultiProgram */
   struct b_bignum *alcbignum   (word n);
#endif                                  /* MultiProgram */
   word         bigradix        (int sign, int r, char *s, char *x,
                                                   union numeric *result);
int             bigtoreal       (dptr da, double *result);
   int          realtobig       (dptr da, dptr dx);
   int          bigtos          (dptr da, dptr dx);
   void         bigprint        (FILE *f, dptr da);
   int          cpbignum        (dptr da, dptr db);
   int          bigadd          (dptr da, dptr db, dptr dx);
   int          bigsub          (dptr da, dptr db, dptr dx);
   int          bigmul          (dptr da, dptr db, dptr dx);
   int          bigdiv          (dptr da, dptr db, dptr dx);
   int          bigmod          (dptr da, dptr db, dptr dx);
   int          bigneg          (dptr da, dptr dx);
   int          bigpow          (dptr da, dptr db, dptr dx);
   int          bigpowri        (double a, dptr db, dptr drslt);
   int          bigand          (dptr da, dptr db, dptr dx);
   int          bigor           (dptr da, dptr db, dptr dx);
   int          bigxor          (dptr da, dptr db, dptr dx);
   int          bigshift        (dptr da, dptr db, dptr dx);
   word         bigcmp          (dptr da, dptr db);
   int          bigrand         (dptr da, dptr dx);
#endif                                  /* LargeInts */

   int dup2(int h1, int h2);

void checkpollevent();
void detectRedirection();

int checkOpenConsole( FILE *w, char *s );

#ifdef MSWindows
   #ifdef FAttrib
      #if MSDOS
         char *make_mode(unsigned short st_mode);
         #ifndef NTGCC
         int strcasecmp(char *s1, char *s2);
         int strncasecmp(char *s1, char *s2, int n);
         #endif                         /* NTGCC */
      #endif                            /* MSDOS */
   #endif                               /* FAttrib */
#endif                                  /* MSWindows */

#if defined(Graphics) || defined(PosixFns)
   struct b_list *findactivewindow(struct b_list *);
   char *si_i2s         (siptr sip, int i);
   int  si_s2i          (siptr sip, char *s);
#endif                                  /* Graphics || PosixFns */

#ifdef Graphics
   /*
    * portable graphics routines in rwindow.r and rwinrsc.r
    */
   wcp  alc_context     (wbp w);
   wbp  alc_wbinding    (void);
   wsp  alc_winstate    (void);
   int  atobool         (char *s);
   void c_push          (dptr l,dptr val);  /* in fstruct.r */
   int  docircles       (wbp w, int argc, dptr argv, int fill);
   void drawCurve       (wbp w, XPoint *p, int n);
   char *evquesub       (wbp w, int i);
   void genCurve        (wbp w, XPoint *p, int n, void (*h)());
   void genCurve(wbp w, XPoint *p, int n, void (*helper)        (wbp, XPoint [], int));
   void curveLister     (wbp w, XPoint *thepoints, int n);
   wsp  getactivewindow (void);
   int  getpattern      (wbp w, char *answer);
   char *getselection   (wbp w, char *buf);
   void gotorc          (wbp w,int r,int c);
   void gotoxy          (wbp w, int x, int y);
   struct palentry *palsetup(int p);
   int  palnum          (dptr d);
   int  parsecolor      (wbp w, char *s, long *r, long *g, long *b, long *a);
   int  parsefont       (char *s, char *fam, int *sty, int *sz, int *tp);
   int  parsegeometry   (char *buf, SHORT *x, SHORT *y, SHORT *w, SHORT *h);
   int  parsepattern    (char *s, int len, int *w, int *nbits, C_integer *bits);
   void qevent          (wsp ws, dptr e, int x, int y, uword t, long f);

   int readBMP          (char *filename, int p, struct imgdata *imd);
   int readGIF          (char *fname, int p, struct imgdata *d);

   int readImage        (char *filename, int p, struct imgdata *imd);
   int writeImage       (wbp w, char *filename, int x, int y, int width, int height);
   int  rectargs        (wbp w, int argc, dptr argv, int i,
                           word *px, word *py, word *pw, word *ph);
   char *rgbkey         (int p, double r, double g, double b);

   int  setrgbmode      (wbp w, char *s);
   int  setselection    (wbp w, dptr val);
   int  setsize         (wbp w, char *s);
   int  ulcmp           (pointer p1, pointer p2);
   int  wattrib         (wbp w, char *s, long len, dptr answer, char *abuf);
   int  wgetche         (wbp w, dptr res);
   int  wgetchne        (wbp w, dptr res);
   int  wgetevent       (wbp w, dptr res, int t);
   int  wgetstrg        (char *s, long maxlen, FILE *f);
   void wgoto           (wbp w, int row, int col);
   int  wlongread       (char *s, int elsize, int nelem, FILE *f);
   void wputstr         (wbp w, char *s, int len);
   int  writeGIF        (wbp w, char *filename,
                          int x, int y, int width, int height);
   int  writeBMP        (wbp w, char *filename,
                          int x, int y, int width, int height);
   int  xyrowcol        (dptr dx);

   /*
    * graphics implementation routines supplied for each platform
    * (excluding those defined as macros for X-windows)
    */
   int  SetPattern      (wbp w, char *name, int len);
   int  SetPatternBits  (wbp w, int width, C_integer *bits, int nbits);
   int  allowresize     (wbp w, int on);
   int  blimage         (wbp w, int x, int y, int wd, int h,
                          int ch, unsigned char *s, word len);
   char child_window_stuff(wbp w, wbp wp, int child_window);
   char child_window_generic(wbp w, wbp wp, int child_window);
   wcp  clone_context   (wbp w);
   int  copyArea        (wbp w,wbp w2,int x,int y,int wd,int h,int x2,int y2);
   int  do_config       (wbp w, int status);
   int  dumpimage       (wbp w, char *filename, unsigned int x, unsigned int y,
                           unsigned int width, unsigned int height);
   void eraseArea       (wbp w, int x, int y, int width, int height);
   void fillrectangles  (wbp w, XRectangle *recs, int nrecs);
   void free_binding    (wbp w);
   void free_context    (wcp wc);
   void free_mutable    (wbp w, int mute_index);
   int  free_window     (wsp ws);
   void freecolor       (wbp w, char *s);
   char *get_mutable_name (wbp w, int mute_index);
   void getbg           (wbp w, char *answer);
   void getcanvas       (wbp w, char *s);
   int  getdefault      (wbp w, char *prog, char *opt, char *answer);
   void getdisplay      (wbp w, char *answer);
   void getdrawop       (wbp w, char *answer);
   void getfg           (wbp w, char *answer);
   void getfntnam       (wbp w, char *answer);
   void geticonic       (wbp w, char *answer);
   int  geticonpos      (wbp w, char *s);
   int  getimstr        (wbp w, int x, int y, int width, int hgt,
                          struct palentry ptbl[DMAXCOLORS], unsigned char *data);
   int  getimstr24      (wbp w, int xx, int yy, int width, int hgt,
                          unsigned char *d);
   void getlinestyle    (wbp w, char *answer);
   int  getpixel_init   (wbp w, struct imgmem *imem);
   int  getpixel_term   (wbp w, struct imgmem *imem);
   int  getpixel        (wbp w,int x,int y,long *rv,char *s,struct imgmem *im);
   void getpointername  (wbp w, char *answer);
   int  getpos          (wbp w);
   int  getvisual       (wbp w, char *answer);
   int  isetbg          (wbp w, int bg);
   int  isetfg          (wbp w, int fg);
   void linkfiletowindow(wbp w, struct b_file *fl);
   int  lowerWindow     (wbp w);
   int  mutable_color   (wbp w, dptr argv, int ac, int *retval);
   char my_wmap         (wbp w);
   int  nativecolor     (wbp w, char *s, long *r, long *g, long *b);

   /* Exclude those functions defined as macros */
   int pollevent        (void);
#ifndef MSWindows
      void wflush       (wbp w);
#endif

   int  query_pointer   (wbp w, XPoint *pp);
   int  query_rootpointer (XPoint *pp);
   int  raiseWindow     (wbp w);
   int  readimage       (wbp w, char *filename, int x, int y, int *status);
   int  rebind          (wbp w, wbp w2);
   int  set_mutable     (wbp w, int i, char *s);
   int  setbg           (wbp w, char *s);
   int  setcanvas       (wbp w, char *s);
   void setclip         (wbp w);
   int  setcursor       (wbp w, int on);
   int  setdisplay      (wbp w, char *s);
   int  setdrawop       (wbp w, char *val);
   int  setfg           (wbp w, char *s);
   int  setfillstyle    (wbp w, char *s);
   int  setfont         (wbp w, char **s);
   int  setgamma        (wbp w, double gamma);
   int  setgeometry     (wbp w, char *geo);
   int  setheight       (wbp w, SHORT new_height);
   int  seticonicstate  (wbp w, char *s);
   int  seticonlabel    (wbp w, char *val);
   int  seticonpos      (wbp w, char *s);
   int  setimage        (wbp w, char *val);
   int  setinputmask    (wbp w, char *val);
   int  setleading      (wbp w, int i);
   int  setlinestyle    (wbp w, char *s);
   int  setlinewidth    (wbp w, LONG linewid);
   int  setpointer      (wbp w, char *val);
   int  setwidth        (wbp w, SHORT new_width);
   int  setwindowlabel  (wbp w, char *val);
   int  strimage        (wbp w, int x, int y, int width, int height,
                           struct palentry *e, unsigned char *s,
                           word len, int on_icon);
   void toggle_fgbg     (wbp w);
   int  walert          (wbp w, int volume);
   void warpPointer     (wbp w, int x, int y);
   int  wclose          (wbp w);
#ifndef MSWindows
   void wflush          (wbp w);
#endif
   int  wgetq           (wbp w, dptr res, int t);
   FILE *wopen          (char *nm, struct b_list *hp, dptr attr, int n, int *e, int is_3d);
#ifdef Graphics3D
   FILE *wopengl        (char *nm, struct b_list *hp, dptr attr, int n,int *e);
#endif                                  /* Graphics3D */

   int  wputc           (int ci, wbp w);
#if HAVE_LIBPNG
   int writePNG(wbp w, char *filename, int x, int y, int width, int height);
#endif                                  /* HAVE_LIBJPEG */
#if HAVE_LIBJPEG
   int writeJPEG(wbp w, char *filename, int x, int y, int width, int height);
#endif                                  /* HAVE_LIBJPEG */
   void wsync           (wbp w);
   void xdis            (wbp w, char *s, int n);

   #ifdef ConsoleWindow
      FILE* OpenConsole         (void);
      int   Consolefprintf      (FILE *file, const char *format, ...);
      int   Consoleputc         (int c, FILE *file);
      int   Consolefflush       (FILE *file);
   #endif                               /* ConsoleWindow */

   #ifdef XWindows
      /*
       * Implementation routines specific to X-Windows
       */
      void      unsetclip               (wbp w);
      void      moveWindow              (wbp w, int x, int y);
      int       moveResizeWindow        (wbp w, int x, int y, int wd, int h);
      int       resetfg                 (wbp w);
      int       setfgrgb                (wbp w, int r, int g, int b);
      int       setbgrgb                (wbp w, int r, int g, int b);

      XColor    xcolor                  (wbp w, LinearColor clr);
      LinearColor lcolor                (wbp w, XColor color);
      int       pixmap_open             (wbp w, dptr attribs, int argc);
      int       pixmap_init             (wbp w);
      int       remap                   (wbp w, int x, int y);
      int       seticonimage            (wbp w, dptr dp);
      void      makeIcon                (wbp w, int x, int y);
      int       translate_key_event     (XKeyEvent *k1, char *s, KeySym *k2);
      int       handle_misc             (wdp display, wbp w);
      wdp       alc_display             (char *s);
      void      free_display            (wdp wd);
      wfp       alc_font                (wbp w, char **s);
      wfp       tryfont                 (wbp w, char *s);
      wclrp     alc_rgb                 (wbp w, char *s, unsigned int r,
                                           unsigned int g, unsigned int b,
                                           int is_iconcolor);
      wclrp     alc_rgb2                (wbp w, char *s, unsigned int r,
                                           unsigned int g, unsigned int b);
      wclrp     alc_rgbTrueColor        (wbp w,unsigned long r,
                                           unsigned long g, unsigned long b);
      int       alc_centry              (wdp wd);
      wclrp     alc_color               (wbp w, char *s);
      void      copy_colors             (wbp w1, wbp w2);
      void      free_xcolor             (wbp w, unsigned long c);
      void      free_xcolors            (wbp w, int extent);
      int       go_virtual              (wbp w);
      int       resizePixmap            (wbp w, int width, int height);
      void      wflushall               (void);
      void      postcursor              (wbp);
      void      scrubcursor             (wbp);
      void      mkfont                  (char *s, char is_3D);
#ifdef HAVE_XFT
      void      drawstrng               (wbp w, int x, int y, char *str, int slen);
#endif                                  /* HAVE_XFT */

   #endif                               /* XWindows */

   int setglXVisual(wdp wd);

   #ifdef Graphics3D
      int init_3dcanvas(wbp  w);
      void apply_texmodechange(wbp w);
      int add_3dfont(char *fname, int fsize, char ftype);
      int c_traverse(struct b_list *hp, struct descrip * res, int position);
      int cpp_drawstring3d(double x, double y, double z, char *s, char *f,
                           int t, int size, void *tfont);
      void cube(double length, double x, double y, double z, int gen);
      void cylinder(double radius1, double radius2, double height,
                double x,  double y, double z, int slices, int rings, int gen);
      void disk(double radius1, double radius2, double angle1, double angle2,
                double x, double y, double z, int slices, int rings, int gen);
      int drawpoly(wbp w, double* v, int num, int type, int dim);
      int drawstrng3d(wbp w, double x, double y, double z, char *s);
      int fileimage(wbp w, char* filename);
      int getlight(int light, char* buf);
      int getmaterials(char* buf);
      void getmeshmode(wbp w, char *answer);
      int gettexcoords(wbp w, char *buf);
      void gettexmode(wbp w, char *abuf, dptr answer);
      int gettexture(wbp w, dptr dp);
      int imagestr(wbp w, char* str);
      int init_3dcontext(wcp wc);
#ifdef HAVE_LIBGL
      int init_texnames(wcp wc);
#endif
      int copy_3dcontext(wcp wc, wcp rv);
      void makecurrent(wbp w);
      int make_enough_texture_space(wdp wc);
      int popmatrix();
      int pushmatrix();
      int pushmatrix_rd(wbp w, dptr f);
      int redraw3D(wbp w);
      int release_3d_resources(wbp w);
      int rotate(wbp w, dptr argv, int i, dptr f);
      int scale(wbp w, dptr argv, int i, dptr f);
      int section_length(wbp w);
      int setdim(wbp w, char* s);
      int seteye(wbp w, char *s);
      int seteyedir(wbp w, char *s);
      int seteyepos(wbp w, char *s);
      int seteyeup(wbp w, char *s);
      int setfov(wbp w, char* s);
      int setlight(wbp w, char* s, int light);
      int setlinewidth3D(wbp w, LONG linewid);
      int setmaterials(wbp w, char* s);
      int setmatrixmode(char *s);
      int setmeshmode(wbp w, char* s);
      int setnormode(wbp w, char* s);
      int setrings(wbp w, char *s);
      int setselectionmode(wbp w, char* s);
      int setslices(wbp w, char *s);
      int settexcoords(wbp w, char* s);
      int settexmode(wbp w, char* s);
      int settexture(wbp w, char* str, int len, struct descrip *f, int curtex,
                     int is_init);
      void sphere(double radius, double x, double y, double z,
                  int slices, int rings, int gen);
      wfp srch_3dfont(char *fname, int fsize, char ftype);
      int TexDrawLine(wbp w, int texhandle, int x1, int y1, int x2, int y2);
      int TexDrawRect(wbp w, int texhandle, int x, int y, int width, int height);
      int TexFillRect(wbp w, int texhandle, int x, int y, int width, int height,
                     int isfg);
      int TexDrawPoint(wbp w, int texhandle, int x, int y);
      int TexReadImage(wbp w, int texhandle, int x, int y,struct imgdata *imd);
      int TexCopyArea(wbp w, wbp w2, int texhandle, int x, int y, int width,
                      int height, int xt, int yt, int width2, int height2);
      int copyareaTexToTex(wbp w, int texhandle, int dest_texhandle,
                     int x, int y, int width, int height, int xt, int yt);
      int texwindow2D(wbp w, wbp w2d);
      int texwindow3D(wbp w1, wbp w2);
      void torus(double radius1, double radius2, double x,double y, double z,
                 int slices, int rings, int gen);
      int translate(wbp w, dptr argv, int i, dptr f);
      int traversefunctionlist(wbp w);
      int create3Dlisthdr(dptr dp, char *strname, word size);

      int identitymatrix();
      int setautogen(wbp w, int i);
      int create3Dcontext(wbp w);
      void initializeviewport(int w, int h);
      int destroycontext(wbp w);
      int copytextures(wcp wc1, wcp wc2);
      void swapbuffers(wbp w, int flush);
      void erasetocolor(int r,int g,int b);
      void bindtexture(wbp w, int texturehandle);
      void applyAutomaticTextureCoords(int enable);
      void applymatrix(wbp w, double a[]);
      int create_display_list(wbp w, int size);
   #endif                                  /* Graphics3D */

   #ifdef MSWindows
      wdp       alc_display     (char *s);
      /*
       * Implementation routines specific to MS Windows
       */
      int playmedia             (wbp w, char *s);
      char *nativecolordialog   (wbp w,long r,long g, long b,char *s);
      int nativefontdialog      (wbp w, char *buf, int flags, int fheight,char*colr);
      char *nativeselectdialog  (wbp w,struct b_list *,char *s);
      char *nativefiledialog    (wbp w, char *s1, char *s2, char *s3,
                                 char *s4, int i, int j, int k);
      HFONT mkfont              (char *s, char is_3D);
      int sysTextWidth          (wbp w, char *s, int n);
      int sysFontHeight         (wbp w);
      int mswinsystem           (char *s);
      void UpdateCursorPos      (wsp ws, wcp wc);
      LRESULT_CALLBACK WndProc  (HWND, UINT, WPARAM, LPARAM);
      HDC CreateWinDC           (wbp);
      HDC CreatePixDC           (wbp, HDC);
      HBITMAP loadimage (wbp wb, char *filename, unsigned int *width,
                        unsigned int *height, int atorigin, int *status);
      void wfreersc();
      int getdepth(wbp w);
      HBITMAP CreateBitmapFromData(char *data);
      int resizePixmap(wbp w, int width, int height);
      int textWidth(wbp w, char *s, int n);
      int       seticonimage            (wbp w, dptr dp);
      int devicecaps(wbp w, int i);
      void fillarcs(wbp wb, XArc *arcs, int narcs);
      void drawarcs(wbp wb, XArc *arcs, int narcs);
      void drawlines(wbinding *wb, XPoint *points, int npoints);
      void drawpoints(wbinding *wb, XPoint *points, int npoints);
      void drawrectangles(wbp wb, XRectangle *recs, int nrecs);
      void fillpolygon(wbp w, XPoint *pts, int npts);
      void drawsegments(wbinding *wb, XSegment *segs, int nsegs);
      void drawstrng(wbinding *wb, int x, int y, char *s, int slen);
      void unsetclip(wbp w);

      void makebutton(wsp ws, childcontrol *cc, char *s);
      void makescrollbar(wsp ws, childcontrol *cc, char *s, int i1, int i2);
      int nativemenubar(wbp w, int total, int argc, dptr argv, int warg, dptr d);
      void makeeditregion(wbp w, childcontrol *cc, char *s);
      void cleareditregion(childcontrol *cc);
      void copyeditregion(childcontrol *cc);
      void cuteditregion(childcontrol *cc);
      void pasteeditregion(childcontrol *cc);
      int undoeditregion(childcontrol *cc);
      int modifiededitregion(childcontrol *cc);
      int setmodifiededitregion(childcontrol *cc, int i);
      void geteditregion(childcontrol *cc, dptr d);
      void seteditregion(childcontrol *cc, char *s2);
      void movechild(childcontrol *cc,
                     C_integer x, C_integer y, C_integer width, C_integer height);
      int setchildfont(childcontrol *cc, char *fontname);
      void setfocusonchild(wsp ws, childcontrol *cc, int width, int height);
      void setchildselection(wsp ws, childcontrol *cc, int x, int y);
      void getchildselection(wsp ws, childcontrol *cc, word *x, word *y);
      int sysScrollWidth();

      void waitkey(FILE *w);


      /* defined in src/common */
      int pathOpenHandle(char *fname, char *mode);
      void closelog();

#endif                          /* MSWindows */

#endif                                  /* Graphics */


#ifdef Audio
int StartAudioThread(char filename[]);
void StopAudioThread(int index);
int AudioMixer(char * cmd);
void audio_exit();
struct AudioFile * StartMP3Thread(char filename[]);
struct AudioFile * StartWAVThread(char filename[]);
struct AudioFile * StartOggVorbisThread(char filename[]);
#endif                                  /* Audio */

/*
 * Prototypes for the run-time system.
 */

struct b_external *alcextrnl    (int n);
#ifdef MultiProgram
struct b_record *alcrecd_0      (int nflds,union block *recptr);
struct b_record *alcrecd_1      (int nflds,union block *recptr);
struct b_tvsubs *alcsubs_0      (word len,word pos,dptr var);
struct b_tvsubs *alcsubs_1      (word len,word pos,dptr var);
#else                                   /* MultiProgram */
struct b_record *alcrecd        (int nflds,union block *recptr);
struct b_tvsubs *alcsubs        (word len,word pos,dptr var);
#endif                                  /* MultiProgram */
int     bfunc           (void);
dptr    calliconproc    (struct descrip proc, dptr args, int nargs);
long    ckadd           (long i, long j);
long    ckmul           (long i, long j);
long    cksub           (long i, long j);
void    cmd_line        (int argc, char **argv, dptr rslt);
struct b_coexpr *create (continuation fnc,struct b_proc *p,int ntmp,int wksz);
int     collect         (int region);
#ifdef CoClean
void coclean(struct b_coexpr *cp);
#endif
void    cotrace         (struct b_coexpr *ccp, struct b_coexpr *ncp,
                           int swtch_typ, dptr valloc);
#ifdef MultiProgram
void    deref_0         (dptr dp1, dptr dp2);
void    deref_1         (dptr dp1, dptr dp2);
#else                                   /* MultiProgram */
void    deref           (dptr dp1, dptr dp2);
#endif                                  /* MultiProgram */
void    envset          (void);
int     eq              (dptr dp1,dptr dp2);
int     fixtrap         (void);
int     get_name        (dptr dp1, dptr dp2);
int     getch           (void);
int     getche          (void);
double  getdbl          (dptr dp);
int     getimage        (dptr dp1, dptr dp2);
int     getstrg         (char *buf, int maxi, struct b_file *fbp);
void    hgrow           (union block *bp);
void    hshrink         (union block *bp);
C_integer iipow         (C_integer n1, C_integer n2, int *over_flowp);
void    init            (char *name, int *argcp, char *argv[], int trc_init);
int     kbhit           (void);
int     nthcmp          (dptr d1,dptr d2);
void    nxttab          (C_integer *col, dptr *tablst, dptr endlst,
                           C_integer *last, C_integer *interval);
int     order           (dptr dp, int sortType);
int     pathFind        (char target[], char buf[], int n);
int     printable       (int c);
int     ripow           (double r, C_integer n, dptr rslt);
void    rtos            (double n,dptr dp,char *s);
int     sig_rsm         (void);
struct b_proc *strprc   (dptr s, C_integer arity);
int     subs_asgn       (dptr dest, const dptr src);
int     tvmonitored_asgn(dptr dest, const dptr src);
int     trcmp3          (struct dpair *dp1,struct dpair *dp2);
int     trefcmp         (dptr d1,dptr d2);
int     tvalcmp         (dptr d1,dptr d2);
int     tvcmp4          (struct dpair *dp1,struct dpair *dp2);
int     tvtbl_asgn      (dptr dest, const dptr src);
void    varargs         (dptr argp, int nargs, dptr rslt);

#ifdef MultiProgram
   struct b_coexpr *alccoexp (long icodesize, long stacksize);
#else                                   /* MultiProgram */
   struct b_coexpr *alccoexp (void);
#endif                                  /* MultiProgram */

dptr rec_structinate(dptr dp, char *name, int nfields, char *a[]);

#ifdef Messaging
struct MFile* Mopen(URI* puri, dptr attr, int nattr, int shortreq, int status);
int Mclose(struct MFile* mf);
int Mpop_delete(struct MFile* mf, unsigned int msgnum);
void Mstartreading(struct MFile* mf);
#endif                                  /* Messaging */

#ifdef PosixFns
#if NT
FILE *mstmpfile();
void closetmpfiles();
int is_internal(char *s);
int StartupWinSocket(void);
void stat2rec                   (struct _stat *st, dptr dp, struct b_record **rp);
dptr make_pwd_nt                (char *name, C_integer uid, C_integer gid, dptr result);
#else                                   /* NT */
void stat2rec                   (struct stat *st, dptr dp, struct b_record **rp);
dptr make_pwd                   (struct passwd *pw, dptr result);
dptr make_group                 (struct group *pw, dptr result);
#endif                                  /* NT */

dptr rec_structor               (char *s);
dptr rec_structor3d             (char *type);
int sock_connect                (char *s, int udp, int timeout, int af_fam);
int sock_getstrg                (char *buf, int maxi, dptr file);
int getmodefd                   (int fd, char *mode);
int getmodenam                  (char *path, char *mode);
int get_uid                     (char *name);
int get_gid                     (char *name);
#if !NT
dptr make_pwd                   (struct passwd *pw, dptr result);
dptr make_group                 (struct group *pw, dptr result);
#endif                                  /* NT */

dptr make_host                  (struct hostent *pw, dptr result);

dptr make_host_from_addrinfo(char *name, struct addrinfo *inforesult, dptr result);
struct addrinfo *uni_getaddrinfo(char* addr, char* p, int is_udp, int family);
void            set_gaierrortext(int i);

dptr make_serv                  (struct servent *pw, dptr result);
int sock_listen                 (char *s, int udp, int af_fam);
int sock_name                   (int sock, char* addr, char* addrbuf, int bufsize);
int sock_me                     (int sock, char* addrbuf, int bufsize);
int sock_send                   (char* addr, char* msg, int msglen, int af_fam);
int sock_recv                   (int f, struct b_record **rp);
int sock_write                  (int f, char *s, int n);
struct descrip register_sig     (int sig, struct descrip handler);
void signal_dispatcher          (int sig);
int get_fd                      (struct descrip, unsigned int errmask);
dptr u_read                     (dptr f, int n, int fstatus, dptr d);
void dup_fds                    (dptr d_stdin, dptr d_stdout, dptr d_stderr);
int set_if_selectable           (struct descrip *f, fd_set *fdsp, int *n);
void post_if_ready              (dptr ldp, dptr f, fd_set *fdsp);
#endif                                  /* PosixFns */

#if COMPILER

   struct b_refresh *alcrefresh (int na, int nl, int nt, int wk_sz);
   int  apply                   (dptr, dptr, dptr, continuation);
   void atrace                  (void);
   void ctrace                  (void);
   void dynrec_start_set        (word);
   void failtrace               (void);
   void initalloc               (void);
   int  invoke                  (int n, dptr args, dptr rslt, continuation c);
   void rtrace                  (void);
   void strace                  (void);
   void tracebk                 (struct p_frame *lcl_pfp, dptr argp, FILE *fd);
   int  xdisp                   (struct p_frame *fp, dptr dp, int n, FILE *f);

#else                                   /* COMPILER */

#ifdef MultiProgram
   struct b_refresh *alcrefresh_0(word *e, int nl, int nt);
   struct b_refresh *alcrefresh_1(word *e, int nl, int nt);
#else                                   /* MultiProgram */
   struct b_refresh *alcrefresh (word *e, int nl, int nt);
#endif                                  /* MultiProgram */
   void atrace                  (dptr dp);
   void ctrace                  (dptr dp, int nargs, dptr arg);
   void failtrace               (dptr dp);
   int  invoke                  (int nargs, dptr *cargs, int *n);
   void rtrace                  (dptr dp, dptr rval);
   void strace                  (dptr dp, dptr rval);
   void tracebk                 (struct pf_marker *lcl_pfp, dptr argp, FILE *fd);
   int  xdisp                   (struct pf_marker *fp, dptr dp, int n, FILE *f);

   #define Fargs dptr cargp
   int  Obscan                  (int nargs, Fargs);
   int  Ocreate                 (word *entryp, Fargs);
   int  Oescan                  (int nargs, Fargs);
   int  Ofield                  (int nargs, Fargs);
   int  Omkrec                  (int nargs, Fargs);
   int  Olimit                  (int nargs, Fargs);
   int  Ollist                  (int nargs, Fargs);

   #ifdef MultiProgram
      void      initalloc       (word codesize, struct progstate *p);
   #else                                /* MultiProgram */
      void      initalloc       (word codesize);
   #endif                               /* MultiProgram */

#endif                                  /* COMPILER */

/* dynamic records */
struct b_proc *dynrecord(dptr s, dptr fields, int n);

#ifdef ISQL
FILE   *isql_open (char *, dptr, dptr, dptr);
int     dbclose(struct ISQLFile *);
int     dbfetch(struct ISQLFile *, dptr);
void    odbcerror               (struct ISQLFile *fp, int errornum);
void    qalloc                  (struct ISQLFile *f, long n); /* query space alloc */
#endif                                  /* ISQL */

#ifdef DebugHeap
void heaperr(char *msg, union block *p, int t);
#endif                                  /* DebugHeap */

#ifdef LoadFunc
int makefunc    (dptr d, char *name, int (*func)());
#endif                                  /* LoadFunc */

#ifdef Arrays
struct b_intarray *alcintarray(uword n);
struct b_realarray *alcrealarray(uword n);
#endif                                  /* Arrays */

#ifdef PthreadCoswitch
void makesem(struct b_coexpr *cp);
void *nctramp(void *arg);
void handle_thread_error(int val, int func, char* msg);
#endif                                  /* PthreadCoswitch */

void init_threadstate(struct threadstate *ts);

#ifdef Concurrent
#ifndef HAVE_KEYWORD__THREAD
struct threadstate *get_tstate();
#endif                                  /* HAVE_KEYWORD__THREAD */
void thread_control(int action);
void clean_threads();
void init_threads();
int msg_receive( dptr dccp, dptr dncp, dptr msg, int timeout);
int msg_send( dptr dccp, dptr dncp, dptr msg, int timeout);
word get_mutex( pthread_mutexattr_t *mattr);
word get_cv(word mtx);
#if COMPILER
void init_threadheap(struct threadstate *ts, word blksiz, word strsiz);
#else                                   /* COMPILER */
void init_threadheap(struct threadstate *ts, word blksiz, word strsiz,
                        struct progstate *newp);
#endif                                  /* COMPILER */
int alcce_queues(struct b_coexpr *ep);
struct region *swap2publicheap(struct region * curr_private,
                               struct region * curr_public,
                               struct region ** p_public);
#endif                                  /* Concurrent */

struct region *newregion(word nbytes,word stdsize);


#ifdef MultiProgram
void init_sighandlers(struct progstate *pstate);
#else                                   /* MultiProgram */
void init_sighandlers();
#endif                                  /* MultiProgram */

#if UNIX && defined(HAVE_WORKING_VFORK)
void push_filepid(int pid, FILE *fp, word status);
#endif                            /* UNIX && defined(HAVE_WORKING_VFORK */

#ifdef DescripAmpAllocated
int bigaddi      (dptr da, word i, dptr dx);
int bigsubi      (dptr da, word i, dptr dx);
int checkTypeInt (dptr da1, dptr da2, word n );
#endif                                  /* DescripAmpAllocated */

char * getenv_var(const char *name);

#if HAVE_LIBSSL
#define TLS_SERVER 1
#define TLS_CLIENT 2
#define DTLS_SERVER 3
#define DTLS_CLIENT 4

SSL_CTX* create_ssl_context(dptr attr, int n, int type);
int set_ssl_connection_errortext(SSL *ssl, int err);
void set_ssl_context_errortext(int err, char* errtext);
void set_errortext_with_val(int i, char* errval);
#endif                                  /* HAVE_LIBSSL */

#ifdef GenericBSD
/* in common/save.c */
int wrtexec(int ef);
#endif                                  /* GenericBSD */
/****************************************   end ../h/../h/rproto.h   */

#ifdef _UCRT    /* Building on Windows using the Universal C Runtime */
#include <io.h>


/****************************************  from ../h/../h/filepat.h:  */

#ifndef FILEPAT_H
#define FILEPAT_H
/*
 * Typedefs and macros for filename wildcard expansion on some systems.
 *  The definitions provided here are:
 *
 *    typedef ... FINDFILE_T;
 *    // Current state of the filename wildcard expansion
 *
 *    int FINDFIRST ( char *pattern, FINDFILE_T *pfd );
 *    // Initializes *pfd and returns 1 if a file is found that matches the
 *    // pattern, 0 otherwise
 *
 *    int FINDNEXT ( FINDFILE_T *pfd );
 *    // Assuming that the last FINDFIRST/FINDNEXT call was successful,
 *    // updates *pfd and returns whether another match can be made.
 *
 *    char *FILENAME ( FINDFILE_T *pfd );
 *    // Assuming that the last FINDFIRST/FINDNEXT call was successful,
 *    // returns pointer to last found file name.
 *
 *    void FINDCLOSE ( FINDFILE_T *pfd );
 *    // Does any cleanup required after doing filenaame wildcard expansion.
 *
 * Also, the macro WildCards will be defined to be 1 if there is file
 * pattern matching is supported, 0 otherwise.  If !WildCards, then a
 * default set of typedef/macros will be provided that will return only one
 * match, the original pattern.
 */


#if WildCards

#if NT

#include <io.h>

typedef struct _FINDFILE_TAG {
   intptr_t             handle;
   struct _finddata_t   fileinfo;
   } FINDDATA_T;

#define FINDFIRST(pattern, pfd) \
   ( ( (pfd)->handle = _findfirst ( (pattern), &(pfd)->fileinfo ) ) != -1L )
#define FINDNEXT(pfd) ( _findnext ( (pfd)->handle, &(pfd)->fileinfo ) != -1 )
#define FILENAME(pfd)   ( (pfd)->fileinfo.name )
#define FINDCLOSE(pfd)  _findclose( (pfd)->handle )

#endif                                  /* NT */

#if MICROSOFT

#include <dos.h>

typedef struct _find_t FINDDATA_T;

#define FINDFIRST(pattern, pfd) (!_dos_findfirst ((pattern), _A_NORMAL, (pfd)))
#define FINDNEXT(pfd)   ( !_dos_findnext ( (pfd) ) )
#define FILENAME(pfd)   ( (pfd)->name )
#define FINDCLOSE(pfd)  ( (void) 0 )

#endif                                  /* MICROSOFT */

#if PORT
Deliberate Syntax Error                 /* Give it some thought */
#endif                                  /* PORT */
#else                                   /* WildCards */
typedef struct _NotWild { char *name; } FINDDATA_T;
#define FINDFIRST(pattern, pfd) ((pfd)->name = (pattern))
#define FINDNEXT(pfd)   ( 0 )
#define FILENAME(pfd)   ( (pfd)->name )
#define FINDCLOSE(pfd)  ( (void) 0 )

#endif                                  /* WildCards */
#endif

/****************************************   end ../h/../h/filepat.h   */
#endif                                  /* _UCRT */


#endif                                  /* RT_DOT_H */

/****************************************   end ../h/rt.h   */
