7¤0ìÒä?¨2ê0333333333u0‰ˆHr¶È/½IŠ�«µòŒº¶-¥�ÄÖ­qÚÄE¤nãð~RÚÔ`ñT�^³ ŒÇãyD(�ç€À”š,‡i”1ŒRcŒ!„ €‘€  ô´¨© t
C                   
  void proc(gs_client_color *, const gs_color_space *)
#define cs_restrict_color(pcc, pcs)\
  ((pcs)->type->restrict_color(pcc, pcs))
        cs_proc_restrict_color((*restrict_color));

    /* Return the concrete color space underlying this one. */
    /* (Not defined for Pattern spaces.) */

#define cs_proc_concrete_space(proc)\
  const gs_color_space *proc(const gs_color_space *,\
                                const gs_gstate *)
#define cs_concrete_space(pcs, pgs)\
  (*(pcs)->type->concrete_space)(pcs, pgs)
        cs_proc_concrete_space((*concrete_space));

    /*
     * Reduce a color to a concrete color.  A concrete color is one
     * that the device can handle directly (possibly with halftoning):
     * a DeviceGray/RGB/CMYK/Pixel color, or a Separation or DeviceN
     * color that does not use the alternate space.
     * (Not defined for Pattern spaces.)
     */

#define cs_proc_concretize_color(proc)\
  int proc(const gs_client_color *, const gs_color_space *,\
    frac *, const gs_gstate *, gx_dezeof uint */
#define fill_adjust_known       (1<<10)
#define ctm_known               (1<<11)
#define dash_known              (1<<12)
#define clip_path_known         (1<<13)
#define STROKE_ALL_KNOWN        ((1<<14)-1)
#define color_space_known       (1<<14)
/*#define all_known             ((1<<15)-1) */

/* Define the drawing color types for distinguishing different */
/* fill/stroke command variations. */
typedef enum {
    cmd_dc_type_pure = 0,
    cmd_dc_type_ht = 1,
    cmd_dc_type_color = 2
} cmd_dc_type;

/* This is usd for cmd_opv_ext_put_drawing_color so that we know if it
   is assocated with a tile or not and for fill or stroke color */
typedef enum {
    devn_not_tile_fill = 0x00,
    devn_not_tile_stroke = 0x01,
    devn_tile0 = 0x02,
    devn_tile1 = 0x03
} dc_devn_cl_type;
/*
 * Further extended command set. This code always occupies a byte, which
 * is the second byte of a command whose first byte is cmd_opv_extend.
 */
typedef enum {
    cmd_opv_ext_put_params           = 0x00, /* serialized paadd_partial_arc_notes(gx_path *, fixed, fixed, fixed, fixed, double, segment_notes),
    gx_path_add_path(gx_path *, gx_path *),
    gx_path_close_subpath_notes(gx_path *, segment_notes),
          /* We have to remove the 'subpath' from the following name */
          /* to keep it unique in the first 23 characters. */
    gx_path_pop_close_notes(gx_path *, segment_notes);

/* Access path state flags */
byte gx_path_get_state_flags(gx_path *ppath);
void gx_path_set_state_flags(gx_path *ppath, byte flags);
bool gx_path_is_drawing(gx_path *ppath);

/*
 * The last argument to gx_path_add_partial_arc is a fraction for computing
 * the curve parameters.  Here is the correct value for quarter-circles.
 * (stroke uses this to draw round caps and joins.)
 */
#define quarter_arc_fraction 0.55228474983079334
/*
 * Backward-compatible constructors that don't take a notes argument.
 */
#define gx_path_add_line(ppath, x, y)\
  gx_path_add_line_notes(ppath, x, y, sn_none)
#define gx_path_add_lines(ppath, pts, count)\
  gxcache_s {
    uint msize, mmax;		/* # of cached font/matrix pairs */
    cached_fm_pair *mdata;
    uint used;			/* list of used pairs in the touch order. */
    uint free;			/* list of free pairs. */
    uint unused;		/* index of the first unused pair. */
} fm_pair_cache;

/* ------ Character cache entry ------- */

/* Define the allocation chunk type. */
typedef gx_bits_cache_chunk char_cache_chunk;

/*
 * This is a subclass of the entry in a general bitmap cache.
 * The character cache contains both used and free blocks.
 * All blocks have a common header; free blocks have ONLY the header.
 */
typedef gx_cached_bits_head cached_char_head;

#define cc_head_is_free(cch) cb_head_is_free(cch)
#define cc_head_set_free(cch) cb_head_set_free(cch)
/*
 * Define the cache entry for an individual character.
 * The bits, if any, immediately follow the structure;
 * characters with only xfont definitions may not have bits.
 * An entry is 'real' if it is not free and if pair != 0.
 * We maintain the invariant that at lenum_t *penum);
int gs_cmap_enum_next_range(gs_cmap_ranges_enum_t *penum);

/*
 * Initialize the enumeration of the lookups, and enumerate the next
 * the next lookup or entry.  which = 0 for defined characters,
 * which = 1 for notdef.  next_xxx returns 0 if OK, 1 if finished,
 * <0 if error.  The intended usage is:
 *
 *	for (gs_cmap_lookups_enum_init(pcmap, which, &lenum);
 *	     (code = gs_cmap_enum_next_lookup(&lenum)) == 0; ) {
 *	    while ((code = gs_cmap_enum_next_entry(&lenum)) == 0) {
 *		...
 *	    }
 *	    if (code < 0) <<error>>
 *	}
 *	if (code < 0) <<error>>
 *
 * Note that next_lookup sets (at least) penum->entry.
 *	key_size, key_is_range, value_type, font_index
 * whereas next_entry sets penum->entry.
 *	key[0][*], key[1][*], value
 * Clients must not modify any members of the enumerator.
 * The bytes of the value string may be allocated locally (in the enumerator
 * itself) and not survive from one call to the next.
 */
void gs_cmap_lookups_enum_init(const gs_cmap_t *pcmap, int which,
     CMap: it does not need to know
 * anything about how the CMap is stored.  Rather, it is meant to be used by
 * the client who constructs the CMap, who decides how stored
 * CODE_VALUE_GLYPH values correspond to printable glyph names.  The same
 * glyph_name procedure can, in principle, be used with multiple different
 * subclasses of gs_cmap_t.
 */

#define GS_CMAP_COMMON\
    int CMapType;		/* must be first */\
    gs_id id;			/* internal ID (no relation to UID) */\
        /* End of entries common to all CMapTypes */\
    gs_const_string CMapName;\
    gs_cid_system_info_t *CIDSystemInfo; /* [num_fonts] */\
    int num_fonts;\
    float CMapVersion;\
    gs_uid uid;			/* XUID or nothing */\
    long UIDOffset;\
    int WMode;\
    bool from_Unicode;		/* if true, characters are Unicode */\
    bool ToUnicode;             /* if true, it is a ToUnicode CMap */\
    gs_glyph_name_proc_t glyph_name;  /* glyph name procedure for printing */\
    void *glyph_name_data;	/* closure data */\
    const gs_cmap_procs_
/* jconfig.h file for Independent JPEG Group code */

#ifndef gsjconf_INCLUDED
#  define gsjconf_INCLUDED

/*
 * We should have the following here:

#include "stdpre.h"

 * But because of the directory structure used to build the IJG library, we
 * actually concatenate stdpre.h on the front of this file instead to
 * construct the jconfig.h file used for the compilation.
 */

#include "arch.h"

#ifdef GS_HIDE_INTERNAL_JPEG
/* The first list is culled from NEED_SHORT_EXTERNAL_NAMES */
#define jpeg_std_error                gpeg_std_error
#define jpeg_CreateCompress           gpeg_CreateCompress
#define jpeg_CreateDecompress         gpeg_CreateDecompress
#define jpeg_destroy_compress         gpeg_destroy_compress
#define jpeg_destroy_decompress       gpeg_destroy_decompress
#define jpeg_stdio_dest               gpeg_stdio_dest
#define jpeg_stdio_src                gpeg_stdio_src
#define jpeg_mem_dest                 gpeg_mem_dest
#define jpeg_mem_src                  gpeg_mem_src
#define jpeg_set_defaults      sk.ccolor. */
#define color_set_null_pattern(pdc)\
 ((pdc)->mask.id = gx_no_bitmap_id,\
  (pdc)->mask.m_tile = 0,\
  (pdc)->colors.pattern.p_tile = 0,\
  (pdc)->type = gx_dc_type_pattern)

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * The remaining definitions are internal ones that are included in this
 * file only because C's abstraction mechanisms aren't strong enough to
 * allow us to keep them separate and still have in-line access to the
 * commonly used members.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/* Define opaque types for objects referenced by device colors. */

typedef struct gx_color_tile_s gx_color_tile;

/*
 * The device color in the graphics state is computed from client color
 * specifications, and kept current through changes in transfer function,
 * device, and (if relevant) halftone phase.
 * (gx_set_dev_color sets the device color if needed.)
 * For binary halftones (and eventually colored halftones as well),
 * the bitmaps are only cachege1(f) ((f) >= 1.0)
/* Test whether a floating point value fits in a given number of bits. */
#define f_fits_in_bits(f, n)\
  ((f) >= -2.0 * (1L << ((n) - 2)) && (f) < 2.0 * (1L << ((n) - 2)))
#define f_fits_in_ubits(f, n)\
  ((f) >= 0 && (f) < 4.0 * (1L << ((n) - 2)))

/*
 * Define a macro for computing log2(n), where n=1,2,4,...,128.
 * Because some compilers limit the total size of a statement,
 * this macro must only mention n once.  The macro should really
 * only be used with compile-time constant arguments, but it will work
 * even if n is an expression computed at run-time.
 */
#define small_exact_log2(n)\
 ((uint)(05637042010L >> ((((n) % 11) - 1) * 3)) & 7)

/*
 * The following doesn't give rise to a macro, but is used in several
 * places in Ghostscript.  We observe that if M = 2^n-1 and V < M^2,
 * then the quotient Q and remainder R can be computed as:
 *              Q = V / M = (V + (V >> n) + 1) >> n;
 *              R = V % M = (V + (V / M)) & M = V - (Q << n) + Q.
 */

#endif /* gxarith_INCL      bits_left = ss->bits_left

/* Store the state back in the stream. */
/* Put back any complete bytes into the input buffer. */
/* Free variables: pr, ss, p, bits, bits_left. */
#define hcd_store_state()\
        pr->ptr = p -= (bits_left >> 3),\
        ss->bits = bits >>= (bits_left & ~7),\
        ss->bits_left = bits_left &= 7

/* Macros to get blocks of bits from the input stream. */
/* Invariants: 0 <= bits_left <= bits_size; */
/* bits [bits_left-1..0] contain valid data. */

#define hcd_bits_available(n)\
  (bits_left >= (n) || rlimit - p > ((n) - bits_left - 1) >> 3)
/* For hcd_ensure_bits, n must not be greater than 8. */
#define HCD_ENSURE_BITS_ELSE(n)\
  if (bits_left >= n)\
    DO_NOTHING;\
  else HCD_MORE_BITS_ELSE
#define hcd_ensure_bits(n, outl)\
  BEGIN HCD_ENSURE_BITS_ELSE(n) goto outl; END

/* Load more bits into the buffer. */
#define HCD_MORE_BITS_1_ELSE\
  if (p < rlimit) {\
    int c = *++p;\
\
    if (ss->FirstBitLowOrder)\
      c = byte_reverse_bits[c];\
    bits = (bits << 8) + intf2(s,a1,a2) DO_NOTHING
#  define dbgprintf3(s,a1,a2,a3) DO_NOTHING
#  define dbgprintf4(s,a1,a2,a3,a4) DO_NOTHING
#  define dbgprintf5(s,a1,a2,a3,a4,a5) DO_NOTHING
#  define dbgprintf6(s,a1,a2,a3,a4,a5,a6) DO_NOTHING
#  define dbgprintf7(s,a1,a2,a3,a4,a5,a6,a7) DO_NOTHING
#  define dbgprintf8(s,a1,a2,a3,a4,a5,a6,a7,a8) DO_NOTHING
#  define dbgprintf9(s,a1,a2,a3,a4,a5,a6,a7,a8,a9) DO_NOTHING
#  define dbgprintf10(s,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10) DO_NOTHING
#  define dbgprintf11(s,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11) DO_NOTHING
#  define dbgprintf12(s,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12) DO_NOTHING
#endif

#ifdef DEBUG
#  define if_debug0m(c,m,s)\
    BEGIN if (gs_debug_c(c)) dmlprintf(m,s); END
#  define if_debug1m(c,m,s,a1)\
    BEGIN if (gs_debug_c(c)) dmlprintf1(m,s,a1); END
#  define if_debug2m(c,m,s,a1,a2)\
    BEGIN if (gs_debug_c(c)) dmlprintf2(m,s,a1,a2); END
#  define if_debug3m(c,m,s,a1,a2,a3)\
    BEGIN if (gs_debug_c(c)) dmlprintf3(m,s,a1,a2,a3); END
#  define if_debug4m(c,m,s,a1,a2,a3,a4)\
 = r->ptr;
    }
}

static inline void
stream_cursor_write_init(stream_cursor_write *w, const byte *buf, size_t length)
{
    if (buf != NULL) {
        /* starting pos for pointer is always one position back */
        w->ptr = (byte *)buf - 1;
        w->limit = (byte *)w->ptr + length;
    }
    else {
        w->ptr = gs_fake_sbuf - 1;
        w->limit = w->ptr;
    }
}
#ifdef __GNUC__
#  pragma GCC diagnostic pop
#endif

/*
 * Define the prototype for the procedures known to both the generic
 * stream code and the stream implementations.
 */

/* Initialize the stream state (after the client parameters are set). */
#define stream_proc_init(proc)\
  int proc(stream_state *)

/* Process a buffer.  See strimpl.h for details. */
#define stream_proc_process(proc)\
  int proc(stream_state *, stream_cursor_read *,\
    stream_cursor_write *, bool)

/* Release the stream state when closing. */
#define stream_proc_release(proc)\
  void proc(stream_state *)

/* Initialize the client parameters to default values. */
)
UNUSED(27)
UNUSED(28)
UNUSED(29)
UNUSED(30)
UNUSED(31)
UNUSED(32)
FLAG(ps_op_names,       '!', 0,   "Postscript operator names"),
FLAG(contexts_detail,   '"', 0,   "Contexts (detail)"),
FLAG(trace_errors,      '#', 0,   "Turn on tracing of error returns from operators"),
FLAG(memfill_obj,       '$', 0,   "Fill unused parts of object with identifiable garbage values"),
FLAG(ext_commands,      '%', 0,   "Externally processed commands"),
UNUSED('&')
FLAG(contexts,          '\'',0,   "Contexts (create/destroy)"),
UNUSED('(')
UNUSED(')')
FLAG(image,             '*', 0,   "Image and rasterop parameters"),
FLAG(min_stack,         '+', 0,   "Use minimum_size stack blocks"),
FLAG(no_path_banding,   ',', 0,   "Don't use path-based banding"),
UNUSED('-')
FLAG(small_mem_tables,  '.', 0,   "Use small-memory table sizes even on large-memory machines"),
FLAG(file_line,         '/', 0,   "Include file/line info on all trace output"),
FLAG(gc,                '0', 0,   "Garbage collection, minimal detail"),
FLAG(type1,      
 *    marking device renders into the output buffer of the
 *    gs_pdf14_device, which contains the results of prior rendering
 *    operations. Thus, overprint is significant to the marking
 *    device. The interaction of transparency and overprint are,
 *    however, more complex than can be captured by a simple
 *    compositor. The gs_pdf14_device and the corresponding device
 *    (will) implement overprint and overprint mode directly. These
 *    devices discard attempts to build an overprint compositor.
 *
 *  - The most essential exception involves colored tiling patterns.
 *    Both the color and color space may change multiple times
 *    during the rendering of a colored pattern. If a colored
 *    pattern is cached, an accurate implementation would require
 *    the cache to included compositor creation instructions.
 *    This is not possible in the current Ghostscript pattern
 *    cache (which has other problems independent of overprint).
 *    The best that can be done is to keep the overprx40A
#define TT_Err_Debug_OpCode             0x40B
#define TT_Err_ENDF_In_Exec_Stream      0x40C
#define TT_Err_Out_Of_CodeRanges        0x40D
#define TT_Err_Nested_DEFS              0x40E
#define TT_Err_Invalid_CodeRange        0x40F
#define TT_Err_Invalid_Displacement     0x410

  /* ------ internal failure error codes ----- */

  /* These error codes are produced when an incoherent */
  /* library state has been detected.  These reflect a */
  /* severe bug in the engine! (or a major overwrite   */
  /* of your application into the library's data).     */

#define TT_Err_Nested_Frame_Access      0x500
#define TT_Err_Invalid_Cache_List       0x501
#define TT_Err_Could_Not_Find_Context   0x502
#define TT_Err_Unlisted_Object          0x503

  /* ---- scan-line converter error codes ----- */

  /* These error codes are produced by the raster component.  */
  /* They indicate that an outline structure was incoherently */
  /* setup, or that you're trying to render an horribly       */
  /* complex glyph!       ror  TT_Close_Face( TT_Face  face );

  /* Get Font or Table Data */

  TT_Error  TT_Get_Font_Data( TT_Face  face,
                              long     tag,
                              long     offset,
                              void*    buffer,
                              long*    length );

  /* A simply macro to build table tags from ascii chars */
#  define MAKE_TT_TAG( _x1, _x2, _x3, _x4 ) \
            (_x1 << 24 | _x2 << 16 | _x3 << 8 | _x4)

  /* ----------------------- instance management -------------------- */

  /* Open a new font instance and returns an instance handle */
  /* for it in '*instance'.                                  */

  TT_Error  TT_New_Instance( TT_Face       face,
                             TT_Instance*  instance );

  /* Set device resolution for a given instance.  The values are      */
  /* given in dpi (Dots Per Inch).  Default is 96 in both directions. */

  /* NOTE:  y_resolution is currently ignored, and the library */
  /*        assumes square pixels.      */


/* Interface for device-specified CRDs */

#ifndef gscrdp_INCLUDED
#  define gscrdp_INCLUDED

#include "gscie.h"
#include "gsparam.h"
#include "gsdevice.h"

/*
 * A driver can provide any number of its own CRDs through (read-only)
 * device parameters whose values are slightly modified PostScript-style
 * dictionaries.  The driver doesn't need to concern itself with how the
 * parameters are encoded: it simply constructs a CRD and calls
 * param_write_cie_render1.
 *
 * Logically, the pcrd parameter for this procedure and the next one
 * should be declared as const gs_cie_render *, but the procedures may
 * cause certain cached (idempotent) values to be computed.
 */
int param_write_cie_render1(gs_param_list * plist, gs_param_name key,
                            gs_cie_render * pcrd,
                            gs_memory_t * mem);

/*
 * For internal use, we also provide an API that writes the CRD directly
 * into a parameter list, rather than as a named parameter in a larger
 * list.
 */
int param_put_nalize(gx_device_finalize);	/* public for subclasses */
/* We use vacuous enum/reloc procedures, rather than 0, so that */
/* gx_device can have subclasses. */
#define public_st_device()	/* in gsdevice.c */\
  gs_public_st_complex_only(st_device, gx_device, "gx_device",\
    0, device_enum_ptrs, device_reloc_ptrs, gx_device_finalize)
#define st_device_max_ptrs 2

/* Enumerate or relocate a pointer to a device. */
/* These take the containing space into account properly. */
gx_device *gx_device_enum_ptr(gx_device *);
gx_device *gx_device_reloc_ptr(gx_device *, gc_state_t *);

/* Define typedefs for some of the device procedures, because */
/* ansi2knr can't handle dev_proc_xxx((*xxx)) in a formal argument list. */
typedef dev_proc_map_rgb_color((*dev_proc_map_rgb_color_t));
typedef dev_proc_map_color_rgb((*dev_proc_map_color_rgb_t));

/*
 * A forwarding device forwards all non-display operations, and possibly
 * some imaging operations (possibly transformed in some way), to another
 * device called the "targetcolor(proc)\
  dev_t_proc_fill_rectangle_hl_color(proc, gx_device)

/*
  Include a color space into the output.
  This function is used to include DefaultGray, DefaultRGB,
  DefaultCMYK into PDF, PS, EPS output.
  Low level devices should ignore this call.
*/

#define dev_t_proc_include_color_space(proc, dev_t)\
  int proc(dev_t *dev, gs_color_space *cspace, const byte *res_name, int name_length)
#define dev_proc_include_color_space(proc)\
  dev_t_proc_include_color_space(proc, gx_device)

                /* Shading support. */

typedef struct gs_fill_attributes_s {
      const gs_fixed_rect *clip;
      bool swap_axes;
      const gx_device_halftone *ht; /* Reserved for possible use in future. */
      gs_logical_operation_t lop; /* Reserved for possible use in future. */
      fixed ystart, yend; /* Only for X-independent gradients. Base coordinates of the gradient. */
      patch_fill_state_t *pfs; /* For gx_fill_triangle_small. Clients must not change. */
} gs_fill_attributes;

/* Fill a linear color scanev, const gs_composite_t *pcte,\
    gs_gstate *pgs, gs_memory_t *memory, gx_device *cdev)
#define dev_proc_composite(proc)\
  dev_t_proc_composite(proc, gx_device)\

                /* Added in release 5.23 */

#define dev_t_proc_get_hardware_params(proc, dev_t)\
  int proc(dev_t *dev, gs_param_list *plist)
#define dev_proc_get_hardware_params(proc)\
  dev_t_proc_get_hardware_params(proc, gx_device)

                /* Added in release 5.24 */

     /* ... text_begin ... see gstext.h for definition */

                /* Added in release 6.61 (raph) */

/*
  This area of the transparency facilities is in flux.  Here is a proposal
  for extending the driver interface.
*/

/*
  Push the current transparency state (*ppts) onto the associated stack,
  and set *ppts to a new transparency state of the given dimension.  The
  transparency state may copy some or all of the gs_gstate, such as the
  current alpha and/or transparency mask values, and definitely copies the
  parameters.
*/
#define dev_t_proc_begin_trans_CINFO_OPMSUPPORTED_UNKNOWN /* opmsupported */, \
     0  /* process_cmps */ }

/*
 * The "has color" macro requires a slightly different definition
 * with the more general color models.
 */
#define gx_device_has_color(dev)                           \
   ( (dev)->color_info.num_components > 1 ||                \
     (dev)->color_info.gray_index == GX_CINFO_COMP_NO_INDEX )

/* parameter initialization macros for backwards compatibility */

/*
 * These macros are needed to define values for fields added when
 * DeviceN compatibility was added.  Previously the graphics
 * library and the much of the device code examined the number of
 * components and assume that 1 --> DeviceGray, 3-->DeviceRGB,
 * and 4--> DeviceCMYK.  Since the old device code does not
 * specify a color model, these macros make the same assumption.
 * This assumption is incorrect for a DeviceN device and thus
 * the following macros should not be used.  The previously
 * defined macros should be used for new devices.
 */

#define dci_std_cmreplicated_raster);

/* Replicate a bitmap vertically in place. */
void bits_replicate_vertically(byte * data, uint height, uint raster,
    uint replicated_height);

/* Find the bounding box of a bitmap. */
void bits_bounding_box(const byte * data, uint height, uint raster,
    gs_int_rect * pbox);

/* Compress an oversampled image, possibly in place. */
/* The width and height must be multiples of the respective scale factors. */
/* The source must be an aligned bitmap, as usual. */
void bits_compress_scaled(const byte * src, int srcx, uint width,
    uint height, uint sraster, byte * dest, uint draster,
    const gs_log2_scale_point * plog2_scale, int log2_out_bits);

/* Extract a plane from a pixmap. */
typedef struct bits_plane_s {
    union bpd_ {        /* Bit planes must be aligned. */
        byte *write;
        const byte *read;
    } data;
    int raster;
    int depth;
    int x;                      /* starting x */
} bits_plane_t;
int bits_extract_plane(const bits_plane_t *dest /*write*/,
    c<< SAMPLE_BOUND_SHIFT((*value), 32)) |
                    ((uint64_t)((*sptr)[4]) << 24) |
                    ((uint64_t)((*sptr)[5]) << 16) |
                    ((uint64_t)((*sptr)[6]) << 8) |
                    (uint64_t)((*sptr)[7]);
            break;
        default:
            return -1;
    }
    *sbit += sbpv;
    *sptr += *sbit >> 3;
    *sbit &= 7;
    return 0;
}

/* Store a value and increment the pointer. */
static int inline sample_store_next8(uint value, byte **dptr, int *dbit, int dbpv, byte *dbbyte)
{
    switch (dbpv >> 2 ) {
        case 0:
            if ( (*dbit += dbpv) == 8 ) {
               *(*dptr)++ = *dbbyte | (byte)value;
               *dbbyte = 0;
               *dbit = 0;
            }
            else
                *dbbyte |= (byte)(value << (8 - *dbit));
            break;
        case 1:
            if ( *dbit ^= 4 )
                *dbbyte = (byte)(value << 4);
            else
                *(*dptr)++ = *dbbyte | ((byte)value);
            break;
        case 2:
  pstype is used only for checking (in DEBUG configurations).
 */
void *gs_resize_struct_array(gs_memory_t *mem, void *obj, size_t num_elements,
                             gs_memory_type_ptr_t pstype,
                             client_name_t cname);

/* Register a structure root.  This just calls gs_register_root. */
int gs_register_struct_root(gs_memory_t *mem, gs_gc_root_t **root,
                            void **pp, client_name_t cname);

/* Define no-op freeing procedures for use by enable_free. */
gs_memory_proc_free_object(gs_ignore_free_object);
gs_memory_proc_free_string(gs_ignore_free_string);

/* Define a no-op consolidation procedure. */
gs_memory_proc_consolidate_free(gs_ignore_consolidate_free);

/*
 * Allocate a structure using a "raw memory" allocator.  Note that this does
 * not retain the identity of the structure.  Note also that it returns a
 * void *, and does not take the type of the returned pointer as a
 * parameter.
 */
void *gs_raw_alloc_struct_immovable(gs_memory_t * rmem,
      includes space used for
     * allocated data, space available for allocation, and overhead.
     */
    size_t allocated;
    /* Set by -K for non-gc memory, max memory to use. */
    size_t limit;
    /*
     * "Used" space is the amount of space used by allocated data
     * plus overhead.
     */
    size_t used;
    size_t max_used;
    /* used when wrapping if underlying allocator must be thread safe */
    bool is_thread_safe;
} gs_memory_status_t;

                /*
                 * Allocate bytes.  The bytes are always aligned maximally
                 * if the processor requires alignment.
                 *
                 * Note that the object memory level can allocate bytes as
                 * either movable or immovable: raw memory blocks are
                 * always immovable.
                 */

#define gs_memory_t_proc_alloc_bytes(proc, mem_t)\
  byte *proc(mem_t *mem, size_t nbytes, client_name_t cname)

#define gs_alloc_bytes_immovable(mem, nbytes, cname)\
  ((mem)->procs.alloc_br_threads_requested */\
        0,              /* saved_pages_list */\
        { 0 }           /* save_procs_while_delaying_erasepage */
#define prn_device_body_rest_(print_page)\
  prn_device_body_rest2_(print_page, gx_default_print_page_copies, -1)
#define prn_device_body_copies_rest_(print_page_copies)\
  prn_device_body_rest2_(gx_print_page_single_copy, print_page_copies, -1)

/* The Sun cc compiler won't allow \ within a macro argument list. */
/* This accounts for the short parameter names here and below. */
#define prn_device_margins_body(dtype, init, dname, w10, h10, xdpi, ydpi, lo, to, lm, bm, rm, tm, ncomp, depth, mg, mc, dg, dc, print_page)\
        std_device_full_body_type(dtype, init, dname, &st_device_printer,\
          (int)((float)(w10) * (xdpi) / 10 + 0.5),\
          (int)((float)(h10) * (ydpi) / 10 + 0.5),\
          xdpi, ydpi,\
          ncomp, depth, mg, mc, dg, dc,\
          (float)(-(lo) * (xdpi)), (float)(-(to) * (ydpi)),\
          (float)((lm) * 72.0), (float)((bm) * 72.0),\
      */
  typedef void  (*TSet_CVT_Function)( EXEC_OPS  Int         index,
                                                TT_F26Dot6  value );

  /* subglyph transformation record */
  struct  _TTransform
  {
    TT_Fixed    xx, xy; /* transformation */
    TT_Fixed    yx, yy; /*     matrix     */
    TT_F26Dot6  ox, oy; /*    offsets     */
  };

  typedef struct _TTransform  TTransform;
  typedef TTransform         *PTransform;

  /* subglyph loading record.  Used to load composite components */
  struct  _TSubglyph_Record
  {
    Int          index;        /* subglyph index           */
    Bool         is_scaled;    /* is the subglyph scaled?  */
    Bool         is_hinted;    /* should it be hinted?     */
    Bool         preserve_pps; /* preserve phantom points? */

    Long         file_offset;

    TT_BBox      bbox;

    TGlyph_Zone  zone;

    Int          arg1;  /* first argument  */
    Int          arg2;  /* second argument */

    Int          element_flag;    /* current load element flag */

  /*  These tables are not precisely defined by the specs      */
  /*  but their structures is implied by the TrueType font     */
  /*  file layout.                                             */
  /*                                                           */
  /*************************************************************/

  /* Graphics State                            */
  /*                                           */
  /* The Graphics State (GS) is managed by the */
  /* instruction field, but does not come from */
  /* the font file.  Thus, we can use 'int's   */
  /* where needed.                             */

  struct  _TGraphicsState
  {
    Int            rp0;
    Int            rp1;
    Int            rp2;

    TT_UnitVector  dualVector;
    TT_UnitVector  projVector;
    TT_UnitVector  freeVector;

    Long           loop;
    TT_F26Dot6     minimum_distance;
    Int            round_state;

    Bool           auto_flip;
    TT_F26Dot6     control_value_cutin;
    TT_F26Dot6     single_width_TCH_T      do { T = *t++; } while (0 == 1)
#define MM_FETCH_T   do { T = _mm_loadu_su128((_m128i const *)t); t += 16; } while (0 == 1)
#else /* !defined(T_USED) || defined(T_CONST) */
#define FETCH_T
#define MM_FETCH_T
#endif /* !defined(T_USED) || defined(T_CONST) */

#ifndef MM_SETUP
#define MM_SETUP() do { } while (0 == 1)
#endif

static void TEMPLATE_NAME(rop_run_op *op, byte *d, int len)
{
#ifndef SPECIFIC_CODE
    rop_proc     proc = rop_proc_table[lop_rop(op->rop)];
#define SPECIFIC_CODE(OUT_, D_,S_,T_) OUT_ = proc(D_,S_,T_)
#endif /* !defined(SPECIFIC_CODE) */
#ifdef S_USED
#ifdef S_CONST
    byte         S = op->s.c;
#ifdef MM_SPECIFIC_CODE
    __m128i      MM_S = _mm_set1_epi8(S);
#endif
#else /* !defined(S_CONST) */
    const byte  *s = op->s.b.ptr;
#endif /* !defined(S_CONST) */
#ifdef S_1BIT
    int          sroll;
    const gx_color_index *scolors = op->scolors;
#endif /* S_1BIT */
#else /* !defined(S_USED) */
#define S 0
#undef S_CONST
#endif /* !defined(S_USED) */
#ifdef T_USED
#ifdef T_CONST
, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Id: sha2.h,v 1.1 2001/11/08 00:02:01 adg Exp adg $
 */

#ifndef __SHA2_H__
#define __SHA2_H__

#ifdef __cplusplus
extern "C" {
#endif

#include "std.h"
#include "stdint_.h"

#define SHA2_USE_INTTYPES_H

/*** SHA-256/384/512 Various Length Definitions ***********************/
#define SHA256_BLOCK_LENGTH		64
#define SHA256_DIGEST_LENGTH		32
#define SHA256_DIGEST_STRING_LENGTH	(SHA256_eric substitute for stdint.h */

#ifndef stdint__INCLUDED
#  define stdint__INCLUDED

/*
 * ensure our standard defines have been included
 */
#include "std.h"

/* Define some stdint.h types. The jbig2dec headers and ttf bytecode
 * interpreter require these and they're generally useful to have around
 * now that there's a standard.

 */

/* Some systems are guaranteed to have stdint.h
 * but don't use the autoconf detection
 */
#ifndef HAVE_STDINT_H
# if defined(__MACOS__) || (defined(__APPLE__) && defined(__MACH__))
#   define HAVE_STDINT_H
# endif
#endif

/* try a generic header first */
#if defined(HAVE_STDINT_H)
# include <stdint.h>
# define STDINT_TYPES_DEFINED
#elif defined(SYS_TYPES_HAS_STDINT_TYPES)
  /* std.h will have included sys/types.h */
# define STDINT_TYPES_DEFINED
#endif

/* try platform-specific defines */
#ifndef STDINT_TYPES_DEFINED
# if defined(__WIN32__) /* MSVC currently doesn't provide C99 headers */
   typedef signed char             int8_t;
   typedef short int               int16_tn better? Well, it's simpler for one thing - the
 * values stored in the structure are the obvious ones, without the strange
 * NdR one. Also, in the original we test R > dR, which takes as long as
 * doing R-=dR in the first place; in the new code we test R against 0, which
 * we get for free on most architectures.
 *
 * In architectures that use branches for alternation, the first (should)
 * compiles to something like (excuse the pseudo code):
 *
 *   Q += dQ
 *   if (R > dR)
 *      goto A
 *   R -= dR
 *   goto B
 * A:
 *   Q += 1
 *   R += NdR
 * B:
 *
 * So 7 'instructions', 5 on each possible route through the code, including
 * 1 branch regardless of the values.
 *
 * In the new form, it compiles to:
 *
 *   R -= dR
 *   if (R >= 0)     <- this instruction for free due to preceeding one
 *       goto A:
 *   R += N
 *   Q++
 * A:
 *   Q += dQ
 *
 * So 5 'instructions', 3 on the no step case, 5 on the step case, including
 * 1 branch on the no-step case.
 *
 * If the compiler is smart enough to use thent is the PostScript interpreter,
 *	    these codes are PostScript name indices, but the graphics
 *	    library doesn't know or rely on this.)  The graphics library
 *	    *does* assume that such codes denote the same names across
 *	    all fonts, and that they can be converted to a string name
 *	    by the font's glyph_name virtual procedure.
 *
 *	  - Codes >= gs_c_min_std_encoding_glyph (and < GS_MIN_CID_GLYPH)
 *	    represent names in a special space used for the 11 built-in
 *	    Encodings.  The API is defined in gscencs.h.  The only
 *	    procedures that generate or recognize such codes are the ones
 *	    declared in that file: clients must be careful not to mix
 *	    such codes with codes in the global space.
 *
 * Client code may assume that GS_NO_GLYPH < GS_MIN_CID_GLYPH (i.e., it is a
 * "name", not an integer), but should not make assumptions about whether
 * GS_NO_GLYPH is less than or greater than gs_c_min_std_encoding_glyph.
 */
typedef uint64_t gs_glyph;

#define GS_NO_GLYPH ((gs_glypinear_color_trapezoid);
dev_proc_fill_linear_color_triangle(gx_forward_fill_linear_color_triangle);
dev_proc_update_spot_equivalent_colors(gx_forward_update_spot_equivalent_colors);
dev_proc_ret_devn_params(gx_forward_ret_devn_params);
dev_proc_fillpage(gx_forward_fillpage);
dev_proc_put_image(gx_forward_put_image);
dev_proc_copy_planes(gx_forward_copy_planes);
dev_proc_composite(gx_forward_composite);
dev_proc_get_profile(gx_forward_get_profile);
dev_proc_set_graphics_type_tag(gx_forward_set_graphics_type_tag);
dev_proc_strip_copy_rop2(gx_forward_strip_copy_rop2);
dev_proc_strip_tile_rect_devn(gx_forward_strip_tile_rect_devn);
dev_proc_copy_alpha_hl_color(gx_forward_copy_alpha_hl_color);
dev_proc_transform_pixel_region(gx_forward_transform_pixel_region);
dev_proc_fill_stroke_path(gx_forward_fill_stroke_path);
dev_proc_lock_pattern(gx_forward_lock_pattern);
void gx_forward_device_initialize_procs(gx_device *dev);

/* ---------------- Implementation utilities ---------------- */
int gx_default_get_param(gx_devdname, stype, open_init_closed),\
        dci_std_color(depth),\
        std_device_part2_(w, h, xdpi, ydpi),\
        offset_margin_values(xoff, yoff, lm, bm, rm, tm),\
        std_device_part3_()

#define std_device_std_color_full_body(dtype, init, dname, w, h, xdpi, ydpi, depth, xoff, yoff, lm, bm, rm, tm)\
        std_device_std_color_full_body_type(dtype, init, dname, 0,\
            w, h, xdpi, ydpi, depth, xoff, yoff, lm, bm, rm, tm)

/* ---------------- Default implementations ---------------- */

/* Default implementations of optional procedures. */
/* Note that the default map_xxx_color routines assume white_on_black. */
dev_proc_open_device(gx_default_open_device);
dev_proc_get_initial_matrix(gx_default_get_initial_matrix);
dev_proc_get_initial_matrix(gx_upright_get_initial_matrix);
dev_proc_sync_output(gx_default_sync_output);
dev_proc_output_page(gx_default_output_page);
dev_proc_close_device(gx_default_close_device);
dev_proc_map_rgb_color(gx_default_w_b_map_rgb_color);
dev_proc_map_color_rgb(gxip, dev, pgs)\
  ((psh)->head.procs.fill_rectangle(psh, prect, prect_clip, dev, pgs))

/* Define the generic shading structures. */
typedef struct gs_shading_procs_s {
    shading_fill_rectangle_proc_t fill_rectangle;
} gs_shading_procs_t;
typedef struct gs_shading_head_s {
    gs_shading_type_t type;
    gs_shading_procs_t procs;
} gs_shading_head_t;

/* Define a generic shading, for use as the target type of pointers. */
struct gs_shading_s {
    gs_shading_head_t head;
    gs_shading_params_t params;
};
#define ShadingType(psh) ((psh)->head.type)
#define private_st_shading()	/* in gsshade.c */\
  gs_private_st_ptrs3(st_shading, gs_shading_t, "gs_shading_t",\
    shading_enum_ptrs, shading_reloc_ptrs,\
    params.ColorSpace, params.cie_joint_caches, params.Background)

/* Define Function-based shading. */
typedef struct gs_shading_Fb_params_s {
    gs_shading_params_common;
    float Domain[4];
    gs_matrix Matrix;
    gs_function_t *Function;
} gs_shading_Fb_params_t;

#define private_st_shading_Fb()	/* iix_add0_final(st_gs_font_cid_data,\
    gs_font_cid_data, "gs_font_cid_data",\
    font_cid_data_enum_ptrs, font_cid_data_reloc_ptrs,\
    gs_font_finalize, st_cid_system_info)
#define st_gs_font_cid_data_num_ptrs\
  st_cid_system_info_num_ptrs

/*
 * Define the structures for CIDFontType 0, 1, and 2 fonts.  In principle,
 * each of these should be in its own header file, but they're so small
 * that we include them here.
 */

/* CIDFontType 0 references an array of (partial) FontType 1 fonts. */

typedef struct gs_font_cid0_s gs_font_cid0;

#define MAX_FDBytes 4
typedef struct gs_font_cid0_data_s {
    gs_font_cid_data common;
    ulong CIDMapOffset;		/* optional, for standard glyph_data */
    gs_font_type1 **FDArray;
    uint FDArray_size;
    int FDBytes;		/* optional, for standard glyph_data */
    /*
     * The third argument of glyph_data may be NULL if only the font number
     * is wanted.
     */
    int (*glyph_data)(gs_font_base *, gs_glyph, gs_glyph_data_t *, int *);
    void *proc_data;
} gs_fonm_alloc(gs_memory_t *, gs_gstate *, client_name_t);

/* Release the contents of an enumerator. */
/* (This happens automatically if the enumeration finishes normally.) */
/* If the second argument is not NULL, also free the enumerator. */
void gs_show_enum_release(gs_show_enum *, gs_memory_t *);

int gs_show_use_glyph(gs_show_enum *, gs_glyph);

/* After setting up the enumeration, all the string-related routines */
/* work the same way.  The client calls gs_show_next until it returns */
/* a zero (successful completion) or negative (error) value. */
/* Other values indicate the following situations: */

        /* The client must render a character: obtain the code from */
        /* gs_show_current_char, do whatever is necessary, and then */
        /* call gs_show_next again. */
#define gs_show_render TEXT_PROCESS_RENDER

        /* The client has asked to intervene between characters (kshow). */
        /* Obtain the previous and next codes from gs_kshow_previous_char */
        /* and gs_kshow_next_char,ist.  However,
                 * finalization procedures may free such objects, and
                 * may allocate, free, and reference objects allocated
                 * in other ways, such as objects allocated with malloc
                 * by libraries.
                 */

#define struct_proc_finalize(proc)\
  void proc(const gs_memory_t *cmem, void /*obj_header_t*/ *ptr)

/*
 * A descriptor for an object (structure) type.
 */
typedef struct struct_shared_procs_s struct_shared_procs_t;

/*
 * Objects within the 'obj' allocator are currently limited to be uint's,
 * even though the interface allows for size_t's. This means that gc'd
 * allocations are never bigger than 4Gig. To change this, change the
 * following type, at the cost of more overhead for each object.
 */
typedef uint obj_size_t;

struct gs_memory_struct_type_s {
        obj_size_t ssize;
        struct_name_t sname;

        /* ------ Procedures shared among many structure types. ------ */
        /* Note that this pointer is usually 0. cedure tests for running out of input rather than for filling the
 * output: with this structure, exhausting the input always returns 0,
 * and discovering that the output buffer is full when attempting to store
 * more output always returns 1.
 *
 * Even this algorithm for handling end-of-buffer is not sufficient if an
 * EOD falls just after a buffer boundary, but the generic stream code
 * handles this case: the process procedures need only do what was just
 * described.
 */

/*
 * The set_defaults procedure in the template has a dual purpose: it sets
 * default values for all parameters that the client can set before calling
 * the init procedure, and it also must initialize all pointers in the
 * stream state to a value that will be valid for the garbage collector
 * (normally 0).  The latter implies that:
 *
 *	Any stream whose state includes additional pointers (beyond those
 *	in stream_state_common) must have a set_defaults procedure.
 */

/*
 * Note that all decoding filters that require an explicit "stdint_.h"
#include "gxfixed.h"
#include "gspath.h"
#include "gsmatrix.h"
#include "gxfont42.h"
#include "gxfont1.h"

#define T1_MAX_STEM_SNAPS 12
#define T1_MAX_ALIGNMENT_ZONES 6
#define T1_MAX_CONTOURS 10
#define T1_MAX_SUBGLYPHS 3
#define T1_MAX_POLES (100 + T1_MAX_CONTOURS) /* Must be grater than 8 for 'flex'. */
#define T1_MAX_HINTS 30

typedef fixed t1_glyph_space_coord; /* measured in original glyph space units */
typedef int32_t t1_hinter_space_coord; /* measured in internal outliner's space units */
typedef int32_t int19;

enum t1_hint_type
{   hstem, vstem, dot
};

enum t1_pole_type
{   offcurve, oncurve, closepath, moveto
};

enum t1_zone_type
{   topzone, botzone
};

enum t1_align_type
{   unaligned, weak, aligned, topzn, botzn
};

typedef struct {
    double xx, xy, yx, yy;
} double_matrix;

typedef struct {
    int19 xx, xy, yx, yy;
    int32_t denominator;
    unsigned int bitshift;
} fraction_matrix;

typedef struct t1_pole_s /* a pole of outline */
{   t1_glyph_space_coord gx,gy; /* source _below),
                     xri - xli, 1);
            if (code < 0)
                return code;
        }
        return loop_fill_trap_np(ll, &le, &re, y - fo->adjust_below, y1 - fo->adjust_below);
    } else if ((le.end.x >= le.start.x) && (re.end.x <= re.start.x)) {
        /* Bottom wider than top. */
        le.start.y = flp->start.y + fo->adjust_above;
        le.end.y   = flp->end.y + fo->adjust_above;
        re.start.y = alp->start.y + fo->adjust_above;
        re.end.y   = alp->end.y + fo->adjust_above;

        if (ADJUSTED_Y_SPANS_PIXEL(y)) {
            /* Strictly speaking the area we want to fill is a trapezoid sat
             * atop a rectangle. For some platforms, it would be cheaper to
             * just emit a single trap if we can get away with it. */
            int xli = fixed2int_var_pixround(flp->x_current - fo->adjust_left);
            int xri = fixed2int_var_pixround(alp->x_current + fo->adjust_right);

            if (TRY_TO_EXTEND_TRAP) {
                int newxl, newxr;

 DED
#  define gscspace_INCLUDED

#include "gsmemory.h"
#include "gsiparam.h"
#include "gsrefct.h"
#include "gsgstate.h"
#include "gsccolor.h"

/*
 * Previous versions had a complicated lifecycle discipline for
 * colorspaces. All that is now replaced with a simple allocation and
 * reference counting discipline. All colorspace objects are allocated
 * on the heap and reference counted. References to colorspace objects
 * are pointers. There is no stack allocation, inline allocation inside
 * structs, or copying of contents.
 */

/*
 * Here is the information associated with the various color space
 * structures.  Note that DevicePixel, DeviceN, and the ability to use
 * Separation or DeviceN spaces as the base space of an Indexed space
 * are LanguageLevel 3 additions.  Unfortunately, the terminology for the
 * different levels of generality is confusing and inconsistent for
 * historical reasons.
 *
 * For base spaces:
 *
 * Space        Space parameters                Color parameters
 * -----        ------pgs that references this cache, pgs->color_space->id =
     *    cspace_id and pgs->cie_render->id = render_id; hence the cache is
     *    valid with respect to that gstate.
     *
     * This invariant is maintained because the PostScript CRD-setting
     * operators, the library's CRD-setting procedure, and the library's
     * procedures for setting CIE color spaces all unshare the joint caches
     * and set status in the new copy to something other than COMPLETED.
     *
     * The only reason for id_status is that certain client code often
     * resets the CRD and/or color space and then sets it back to its
     * original value, and we want to detect that and not invalidate the
     * caches.  If it weren't for that, setcolorspace and setcolorrendering
     * could simply invalidate the caches.
     */

    gs_id cspace_id;
    gs_id render_id;
    cie_joint_caches_status_t id_status;
    cie_joint_caches_status_t status;
    rc_header rc;
    GX_CIE_REMAP_FINISH_PROC((*remap_finish));
    bool skipe caches[3];
    cie_interpolation_range_t interpolation_ranges[3];  /* indexed by output component */
} gx_cie_vector_cache3_t;

/* ------ Color space dictionaries ------ */

/* Elements common to all CIE color space dictionaries. */
struct gs_cie_common_s {
    int (*install_cspace)(gs_color_space *, gs_gstate *);
    void *client_data;
    gs_range3 RangeLMN;
    gs_cie_common_proc3 DecodeLMN;
    gs_matrix3 MatrixLMN;
    gs_cie_wb points;
    /* Following are computed when structure is initialized. */
    struct {
        gx_cie_scalar_cache DecodeLMN[3];
    } caches;
};

/* st_cie_common and st_cie_common_elements_t are exported for gsicc.c */
#define public_st_cie_common()     /* in gscscie.c */\
  gs_public_st_ptrs1(st_cie_common, gs_cie_common, "gs_cie_common",\
                      cie_common_enum_ptrs, cie_common_reloc_ptrs, client_data)

/* extern_st(st_cie_common); */ /* in gxcie.h */

#define gs_cie_common_elements\
        gs_cie_common common;		/* must be first */\
        rc_header rc
typedrtunately it seems to be necessary.
 */
#define CIE_RENDER_TABLE_INTERPOLATE

/* ------ Derived values ------ */

/* from CIE_LOG2_CACHE_SIZE */
#define gx_cie_log2_cache_size CIE_LOG2_CACHE_SIZE
#define gx_cie_cache_size (1 << gx_cie_log2_cache_size)

/* From CIE_FIXED_FRACTION_BITS 12 */
#ifndef CIE_FIXED_FRACTION_BITS
/* Take as many bits as we can without having to multiply in two pieces. */
#  define CIE_FIXED_FRACTION_BITS\
     ((ARCH_SIZEOF_LONG * 8 - gx_cie_log2_cache_size) / 2 - 1)
#endif

/* From CIE_RENDER_TABLE_INTERPOLATE */
#ifdef CIE_RENDER_TABLE_INTERPOLATE
#  define CIE_CACHE_INTERPOLATE
#endif

#define float_lshift(v, nb) ((v) * (1L << (nb)))
#define float_rshift(v, nb) ((v) * (1.0 / (1L << (nb))))

#ifdef CIE_CACHE_INTERPOLATE
/* We have to have room for both a cache index and the interpolation bits */
/* in a positive int (i.e., leaving 1 bit for the sign), plus a little slop. */
/* The values for interpolation are cie_cached_values by default. */
#  define _cie_interpolate_bits\
     minr spaces, stored here for easy access from */ 	\
        /* gx_concrete_space_CIE */ \
        gs_color_space *devicergb_cs;\
        gs_color_space *devicecmyk_cs;\
\
        /* Stores for cached values which correspond to whichever */\
        /* color isn't in force at the moment */\
        struct gx_cie_joint_caches_s *cie_joint_caches_alt;\
        gs_devicen_color_map          color_component_map_alt


/* Current colors (non-stroking, and stroking) */
typedef struct gs_gstate_color_s {
    gs_color_space *color_space; /* after substitution */
    gs_client_color *ccolor;
    gx_device_color *dev_color;
    bool effective_opm;
} gs_gstate_color;

/*
 * Enumerate the reference-counted pointers in a c.r. state.  Note that
 * effective_transfer doesn't contribute to the reference count: it points
 * either to the same objects as set_transfer, or to objects in a halftone
 * structure that someone else worries about.
 */
#define gs_cr_state_do_rc_ptrs(m)\
  m(halftone) \
  m(dev_ht[HT_OBJTYPE_DEFAULT]) \
  mrg12)
#define dlprintf12(str,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12)\
  (_dpl dprintf12(str, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12))

/* Print the program line # for debugging. */
#if __LINE__                    /* compiler provides it */
void dmprintf_file_and_line(const gs_memory_t *,const char *, int);
#  define _dmpl(M) dmprintf_file_and_line(M,__FILE__, __LINE__),
#else
void dmprintf_file_only(const gs_memory_t *,const char *);
#  define _dmpl(M) dmprintf_file_only(M,__FILE__),
#endif

#define dmflush(mem) errflush(mem)
#define dmputc(mem,chr) dmprintf1(mem,"%c", chr)
#define dmlputc(mem,chr) dmlprintf1(mem,"%c", chr)
#define dmputs(mem,str) dmprintf1(mem,"%s", str)
#define dmlputs(mem,str) dmlprintf1(mem,"%s", str)
#define dmprintf(mem,str)\
  dpfm(mem,str)
#define dmlprintf(mem,str)\
  (_dmpl(mem) dpfm(mem,str))
#define dmprintf1(mem,str,arg1)\
  dpfm(mem,str, arg1)
#define dmlprintf1(mem,str,arg1)\
  (_dmpl(mem) dmprintf1(mem,str, arg1))
#defitgraphics(gs_gstate *);
int gs_initgraphics_no_cspace(gs_gstate *);

bool gs_currentcpsimode(const gs_memory_t *);
void gs_setcpsimode(gs_memory_t *, bool);

int gs_getscanconverter(const gs_memory_t *);
void gs_setscanconverter(gs_gstate *, int);

/* Device control */
#include "gsdevice.h"

/* Line parameters and quality */
#include "gsline.h"

/* Color and gray */
#include "gscolor.h"

/* Halftone screen */
#include "gsht.h"
#include "gscsel.h"
int gs_setscreenphase(gs_gstate *, int, int, gs_color_select_t);
int gs_currentscreenphase(const gs_gstate *, gs_int_point *, gs_color_select_t);

#define gs_sethalftonephase(pgs, px, py)\
  gs_setscreenphase(pgs, px, py, gs_color_select_all)
#define gs_currenthalftonephase(pgs, ppt)\
  gs_currentscreenphase(pgs, ppt, 0)
int gx_gstate_setscreenphase(gs_gstate *, int, int, gs_color_select_t);

/* Miscellaneous */
int gs_setfilladjust(gs_gstate *, double, double);
int gs_currentfilladjust(const gs_gstate *, gs_point *);
void gs_setlimitclamp(gs_gstate *, bool);
bool g -45, 36,
  -42, 70, -15, 44, -74, 17, -13, -6, 9, 8, -43, 34, -60, -27, -11, -20,
  41, -11, -1, 63, -27, 37, 76, -38, 65, -3, -22, 8, 48, -7, -15, 10,
  -3, 104, -47, -8, -29, 50, -88, 90, -63, -56, 47, -36, -30, 62, -42, 81,
  -20, 35, 7, 13, 1, -19, 60, 3, -43, -32, -17, -29, 62, -11, 15, -44,
  -3, -6, 3, 67, -46, 49, 64, -46, 19, 30, -58, 45, 31, 5, 59, -57,
  32, -4, 57, -29, -1, 50, -1, -1, 0, -56, 42, -79, 43, -16, 18, -103,
  82, -41, -13, -74, 69, -85, 22, 24, 15, 13, -25, -33, -14, 1, 19, -9,
  -27, 1, -15, -10, -36, -53, 48, -38, -33, 37, -15, 11, 27, 38, 4, 46,
  -61, 57, 37, 4, 27, -4, 2, 37, -15, -56, 39, -3, 5, -39, 54, -19,
  -11, 31, 29, -14, 46, -41, 69, -42, 4, -42, 53, -36, 0, -4, 65, -30,
  20, 46, -25, 21, -67, 34, -36, 26, -4, 62, -46, -10, -38, 38, 31, 20,
  9, 4, -23, -7, 89, -54, 42, -46, 7, 2, -45, 71, -27, -36, -34, 25,
  57, -26, -23, -25, -34, -24, 18, 50, -55, 57, -32, 11, -48, 61, -110, 65,
  -43, -2, 0, -45, 7, -25, -12, -60, 44, -2, -12, -77, 18, -55, 54, -15,
  17, -69, 5,3, -56, -1,
  -45, 33, 8, -25, 47, 21, -20, -8, -36, 19, -38, 25, 64, -8, 49, -14,
  29, 59, -68, 6, 27, -24, 18, -27, 33, 35, 37, 4, -11, 45, 23, 1,
  9, 48, -22, 4, -27, 0, 53, -1, -8, -8, -12, -45, 37, 36, 3, 3,
  33, 31, -55, 57, -97, 31, 28, 36, 1, 60, -28, -22, 39, -11, -48, 27,
  -63, -10, -35, -21, 51, 50, 26, -57, -61, 44, -86, 48, 21, 14, -22, 30,
  -29, 17, -43, 7, -15, -14, -19, -12, -49, 38, -41, 90, -62, 43, -2, -66,
  27, -5, 9, 44, -15, -50, 45, 0, -64, 60, -66, 57, 11, 48, 17, -70,
  39, -94, 22, -72, -40, 71, -19, -10, 9, 43, -57, 52, -51, 5, 4, 85,
  -34, -35, 21, -19, -7, 20, -56, 24, -13, 22, -26, 64, -5, -36, -38, -25,
  -42, 33, -20, 2, 9, -15, 50, -41, -26, -50, 44, -18, 68, -19, 3, -76,
  39, -37, 52, -65, 21, 19, -12, 62, -15, -26, 39, 43, -6, 46, -72, 28,
  -2, 46, 3, -49, -44, -23, -21, -15, 12, -79, 72, -30, -17, 0, 38, -89,
  28, -15, -13, -10, -56, 72, -80, 26, -66, 59, -38, 0, -9, -4, -1, 9,
  -70, 59, -18, -11, -48, 28, 4, -3, 17, 16, -31, 3, -54, 40, -14, 54,
  23, -37, 29, 3 -12, -44, 75, -72, 58, -31, 55, -29, -16, -53, -15, -37, -43, 39,
  -9, 1, 36, -11, 18, -54, 86, -59, 47, 7, 12, -33, 42, 16, -55, 70,
  -1, -53, 64, -29, 18, 24, 15, -59, 61, 54, -36, -1, -13, 12, -69, 33,
  -24, -58, -37, 48, -8, -80, 60, -73, 68, 19, 38, 52, 2, 45, 25, 30,
  53, 35, -66, -2, -1, 34, -30, 0, 19, -9, 28, 14, 30, 19, -13, -95,
  57, -29, 32, -46, 30, 25, -6, 28, 9, -49, -23, 55, -65, -20, 66, -42,
  87, 56, -10, -11, 28, 11, 48, -48, -25, 0, 28, -34, 37, -19, 7, -34,
  -17, 34, 11, -78, 27, -79, 51, -64, -18, -9, -47, 7, -22, 47, 20, -32,
  26, -60, 82, -38, 53, -12, -18, -57, -65, -30, 18, 5, -13, 19, 69, -86,
  16, -26, -43, -40, -37, 38, -73, 57, -30, -13, -13, 17, -41, -37, -64, 97,
  -85, 80, -41, -56, -31, 44, -52, 10, -45, 39, 42, 2, -41, 17, 3, 7,
  59, -2, 74, 6, 34, -35, -44, 37, -31, 23, -14, -38, -1, 3, -8, 25,
  -23, 27, 23, 18, 2, -54, -28, 14, 50, -46, 85, -4, -4, -13, 15, 63,
  -43, 49, -33, 58, 8, -38, 24, -11, -47, 55, 4, 31, -52, 77, -4, 31,
  1, -21, 17, -57, 0, 48, 26, --78,
  43, -7, 17, -12, 94, -81, -30, 52, -28, -20, 42, -55, -16, 43, -58, -32,
  -38, -6, 29, -55, 47, -16, 21, 0, -39, 15, -16, -37, -50, -56, -15, 33,
  40, -23, -12, 37, -59, 57, -5, -19, -30, -20, 16, 29, -68, 32, 58, -3,
  -35, 26, -4, 12, 34, 42, -31, -62, -13, -9, -38, 20, 0, 36, -46, -57,
  28, 35, -49, -51, 29, 15, -10, 38, -70, -50, 27, -45, 79, -40, -2, -50,
  -41, 50, 20, 57, 40, -35, -36, -6, 15, -53, 75, -22, 6, 2, 55, -61,
  -56, 36, -61, 40, -42, 73, 9, -23, -48, -32, 26, -59, 69, -35, -53, 59,
  -82, 33, 9, 20, 17, 42, -50, 34, -1, -36, 43, -15, -5, -26, 21, 1,
  75, 22, -60, -7, 23, 4, 0, 5, 53, -35, 38, -11, -11, 57, -17, 11,
  12, -73, -6, 0, 64, -1, -52, -5, 21, 14, 12, -51, 4, -40, 14, -28,
  58, 3, -2, -29, -46, -67, 44, -3, -69, 33, -45, 13, -48, 37, -78, 75,
  25, -15, 16, -5, 41, -19, 29, -3, 16, 13, 12, 4, 5, -82, 45, -49,
  25, -55, -1, -1, -23, 23, -35, 4, -39, 26, -83, 44, -36, -19, -13, 52,
  -17, 36, -21, -2, 26, -49, 49, 31, -14, -1, -54, 37, 1, -39, -30, -34,
  2, 3, 1, 18, 57, -41, 70, -60, -1, 25, 2, -3, -39, -25,
  96, 5, 18, 0, 70, -54, -53, 60, -4, -36, -2, 49, -41, -67, 65, -72,
  -10, 61, -35, 60, 18, -49, -24, 29, -8, -2, -33, -45, 75, -18, 6, 28,
  45, -58, -33, 9, -52, 12, -8, 7, 30, -67, -1, 87, -38, -26, -87, 38,
  -90, 11, 0, 34, -10, 43, -33, -22, -5, 16, -27, -27, 27, 60, -15, 42,
  27, 8, 0, -22, -38, 38, 58, -71, 87, -50, 93, -61, 42, -60, 49, -10,
  33, -12, 1, -24, -24, 33, -22, 48, -18, 52, -53, -13, 38, -1, -43, 40,
  -22, 29, 19, 3, -17, 3, 28, -5, 56, -21, 10, -12, 18, 18, -27, -35,
  40, 0, 5, -81, 8, -84, 30, 15, 68, -48, -22, 5, 10, -64, 41, -24,
  18, -4, -49, 11, -26, 9, -9, 56, -59, -61, -18, 29, -5, 26, 52, -65,
  -4, 37, -42, 29, 18, -40, 20, -4, -26, 30, 23, 54, -64, 55, -13, 61,
  -26, 51, -45, 20, -30, 30, 6, 0, -9, 66, -68, 82, 13, 2, -23, 35,
  19, 29, -25, -22, 21, 46, 31, -32, 43, 2, -53, 45, -61, 5, -8, -11,
  -17, 27, 16, -15, -44, 40, -52, 79, -2, -24, 22, 36, 1, -27, 16, -43,
  34, 35, -32, -2, 51, 52, 21, 7, -51, 24, -10, 24, -1, -77, 6, -21, -30, 31,
  -53, 62, -20, -4, 62, 8, -64, 26, 44, -65, 40, -28, -24, 70, -18, -51,
  32, -25, 63, -2, 4, 10, -59, 17, -61, 91, -60, 37, -30, 14, -42, -16,
  -31, -29, 22, -25, -37, 62, 41, 34, 27, 58, 9, -27, 26, 23, 11, 31,
  -74, 45, -34, 58, -80, 39, -29, -8, -8, -25, 43, -29, 24, 40, 45, -66,
  16, 43, -29, -6, 4, -16, -3, 36, -32, 33, 23, 67, -16, -26, 19, -16,
  40, 62, -65, 55, -48, 6, -26, 23, -28, 86, -38, -39, 58, -65, -7, -55,
  46, -12, 53, -45, 68, -25, 23, 58, -47, 22, 10, -2, -72, 14, -29, -64,
  1, -57, 59, -6, 41, -63, -8, -48, 85, -56, -55, 58, -50, -3, -16, -67,
  79, -24, -9, 15, 19, -14, 39, 24, -33, 6, -42, -5, -47, -8, -40, 22,
  38, -16, -40, -13, -14, -29, -1, -7, 9, 47, -46, 62, -53, -30, 55, -74,
  9, -32, 47, -81, 91, -46, 10, -43, -61, 60, -19, -45, -72, 8, 10, 47,
  26, 25, -27, -39, 66, -30, 10, -24, 32, -14, -52, 37, 12, -30, -52, -4,
  4, 54, -52, 34, -45, 51, -18, -8, 20, 21, -35, 55, -39, -58, 59, -52,
  14, 28, -55, 33, -42, 50, -53, -34, -5, -13, -53, -77, 54, -37, -1, -64, -44, 40, 14, -48, -50, -39,
  -12, -17, 47, -43, 68, -9, 9, -82, 88, -89, 85, -24, -41, -11, 45, 34,
  5, 55, -68, 36, -43, 13, 53, 12, 41, -49, 32, -3, -30, 50, 27, 34,
  7, 11, -23, -16, 55, -29, -28, 48, 2, -11, -25, 52, 41, -72, 19, -21,
  36, 6, -44, -27, 22, -55, -54, -7, -45, 15, 19, -14, 43, 19, -26, -14,
  -36, 8, 21, -31, -45, -33, -45, 31, -25, -44, -18, -47, -17, 30, -1, -39,
  25, 20, -13, -84, 69, 3, -10, -44, 42, -29, 39, -22, -23, -18, 40, -7,
  67, -33, 106, -41, 36, -78, 47, 4, -20, -54, 62, 20, -78, -41, 40, 5,
  -32, 1, 52, -35, -45, -3, -8, 8, 36, -44, -36, -52, 1, 5, 41, 13,
  -18, 43, -7, 5, 22, -17, -48, 63, 26, -16, 26, 6, 14, 36, -47, 61,
  -48, -55, 92, -40, 19, -61, 37, -14, -22, 66, -61, 43, 39, -79, -14, 50,
  19, 46, -55, -24, -48, 27, -56, 43, 1, 30, -46, -12, -32, -4, -41, -19,
  -6, -46, 46, -53, 6, -7, -36, 41, -61, 31, -44, 16, 6, 17, 28, -35,
  30, -47, 0, 37, -15, 3, -9, -5, -23, 46, 46, 17, -32, -17, -62, 35,
  -35, 14, 8, 37, -51, -55, -19, -20, 14, 41, -34, 0, ter.
 *   T_CONST       (Optional)    If set, T will be taken to be constant, else
 *                               T will be read from a pointer.
 */

#if defined(TEMPLATE_NAME)

#ifdef SPECIFIC_ROP
#if rop3_uses_S(SPECIFIC_ROP)
#define S_USED
#endif
#if rop3_uses_T(SPECIFIC_ROP)
#define T_USED
#endif
#else /* !SPECIFIC_ROP */
#define S_USED
#define T_USED
#endif /* SPECIFIC_ROP */

/* We work in 'chunks' here; for bigendian machines, we can safely use
 * chunks of 'int' size. For little endian machines where we have a cheap
 * endian swap, we can do likewise. For others, we'll work at the byte
 * level. */
#if !ARCH_IS_BIG_ENDIAN && !defined(ENDIAN_SWAP_INT)
#define CHUNKSIZE 8
#define CHUNK byte
#define CHUNKONES 255

#define ADJUST_TO_CHUNK(d,dpos) do {} while (0)

#else /* ARCH_IS_BIG_ENDIAN || defined(ENDIAN_SWAP_INT) */
#if ARCH_LOG2_SIZEOF_INT == 2
#define CHUNKSIZE 32
#define CHUNK unsigned int
#define CHUNKONES 0xFFFFFFFFU

#if ARCH_SIZEOF_PTR == (1<<ARCH_LOG2_SIZEOF_INT)
#define ROP_PTRDIFF_T int
#
/* Library "client" bitmap structures */

#ifndef gsbitmap_INCLUDED
#define gsbitmap_INCLUDED

#include "gsstype.h"		/* for extern_st */

/*
 * The Ghostscript library stores all bitmaps bit-big-endian (i.e., the 0x80
 * bit of the first byte corresponds to x=0), as a sequence of bytes (i.e.,
 * you can't do word-oriented operations on them if you're on a
 * little-endian platform like the Intel 80x86 or VAX).  The first scan line
 * corresponds to y=0 in whatever coordinate system is relevant.
 *
 * The structures defined here are for APIs that don't impose any alignment
 * restrictions on either the starting address or the raster (distance
 * between scan lines) of bitmap data.  The structures defined in gxbitmap.h
 * do impose alignment restrictions, so that the library can use more
 * efficient algorithms; they are declared with identical contents to the
 * ones defined here, so that one can cast between them under appropriate
 * circumstances (aligned to unaligned is always safe; unaligned to
 * aligned charstring_skip_next(ch, state, encrypted)\
  (encrypted ? decrypt_skip_next(ch, state) : 0)

/* This is the full state of the Type 1 interpreter. */
#define ostack_size 48		/* per Type 2 documentation */
#define ipstack_size 10		/* per documentation */
struct gs_type1_state_s {
    t1_hinter h;
    /* The following are set at initialization */
    gs_font_type1 *pfont;	/* font-specific data */
    gs_gstate *pgs;              /* gs_gstate */
    gx_path *path;		/* path for appending */
    bool no_grid_fitting;
    int paint_type;		/* 0/3 for fill, 1/2 for stroke */
    void *callback_data;
    fixed_coeff fc;		/* cached fixed coefficients */
    float flatness;		/* flatness for character curves */
    point_scale scale;		/* oversampling scale */
    gs_log2_scale_point log2_subpixels;	/* log2 of the number of subpixels */
    gs_fixed_point origin;	/* character origin */
    /* The following are updated dynamically */
    fixed ostack[ostack_size];	/* the Type 1 operand stack */
    int os_count;		/* # of _dc_ht_binary_get_nonzero_comps);
extern  dev_color_proc_get_nonzero_comps(gx_dc_ht_colored_get_nonzero_comps);

/* convert between color types and color type indices */
extern int gx_get_dc_type_index(const gx_device_color *);
extern const gx_device_color_type_t * gx_get_dc_type_from_index(int);

/* the two canonical "get_phase" methods */
extern  dev_color_proc_get_phase(gx_dc_no_get_phase);
extern  dev_color_proc_get_phase(gx_dc_ht_get_phase);

#define gs_color_writes_pure(pgs)\
  color_writes_pure(gs_currentdevicecolor_inline(pgs), (pgs)->log_op)

/* Set up device color 1 for writing into a mask cache */
/* (e.g., the character cache). */
int gx_set_device_color_1(gs_gstate * pgs);

/* Remap the color if necessary. */
int gx_remap_color(gs_gstate *);

#define gx_set_dev_color(pgs)\
    color_is_set(gs_currentdevicecolor_inline(pgs)) ? 0 :\
      gx_remap_color(pgs);

/* Indicate that the device color needs remapping. */
#define gx_unset_dev_color(pgs)\
  color_unset(gs_currentdevicecolor_inline(pgs))
#defode_color(gx_default_gray_encode);

/*
 * This is the default encode_color routine for grayscale devices
 * that provide a map_rgb_color procedure, but don't themselves
 * provide encode_color.
 */
dev_proc_encode_color(gx_backwards_compatible_gray_encode);

/*
 * These are the default routines for converting a gx_color_index into
 * a list of device colorant values
 */
dev_proc_decode_color(gx_error_decode_color);
dev_proc_decode_color(gx_default_decode_color);

/*
 * convert a float paint value to a fractional value with clamping to
 * [0,1]
 */
frac gx_unit_frac(float fvalue);
/* Determine if the device is using the standard color mapping procs.  In
   such a case, we can make use of the faster icc color conversions for
   images */
bool gx_device_uses_std_cmap_procs(gx_device * dev,
                                   const gs_gstate * pgs);
void cmap_transfer_halftone(gx_color_value *pconc, gx_device_color * pdc,
     const gs_gstate * pgs, gx_device * dev, bool has_transfer,
     bool has_halftone, gs_coelect, pcs)\
  ((pgs)->cmap_procs->map_devicen)(pcc, pdc, pgs, dev, select, pcs)

/* Map a color */
#include "gxcindex.h"
#include "gxcvalue.h"

/*
  Get the mapping procedures appropriate for the currently set
  color model.
 */
#define dev_t_proc_get_color_mapping_procs(proc, dev_t) \
    const gx_cm_color_map_procs * (proc)(const dev_t * dev, const gx_device **)

#define dev_proc_get_color_mapping_procs(proc) \
    dev_t_proc_get_color_mapping_procs(proc, gx_device)

/*
  Define the options for the component_type parameter to get_color_comp_index
  routines.  Note:  This information is currently being used by the routines
  for identifying when they are being given a separation name.  Some devices
  automaticaly add separations to the device's components if the separation
  is not previously known and there is room in the device.  Overprint
  simulation required a split of the NO_COMP_NAME_TYPE depending if we
  are calling from the halftone setup or overprint setup.
*/
#define NO_COMP_NAME_TYPE_HT	0
#deficolor_index *)op->tcolors)[0];
        tc[1] = ((const gx_color_index *)op->tcolors)[1];
#if T_1BIT == MAYBE
    } else
        troll = 0;
#endif /* T_1BIT == MAYBE */
#endif /* defined(T_1BIT) */
    do {
#if defined(S_USED) && !defined(S_CONST)
        rop_operand S;
#endif /* defined(S_USED) && !defined(S_CONST) */
#if defined(T_USED) && !defined(T_CONST)
        rop_operand T;
#endif /* defined(T_USED) && !defined(T_CONST) */
#if defined(S_1BIT) && S_1BIT == MAYBE
        if (sroll == 0) {
#endif /* defined(S_1BIT) && S_1BIT == MAYBE */
#if !defined(S_1BIT) || S_1BIT == MAYBE
            FETCH_S;
#endif /* !defined(S_1BIT) || S_1BIT == MAYBE */
#if defined(S_1BIT) && S_1BIT == MAYBE
        } else
#endif /* defined(S_1BIT) && S_1BIT == MAYBE */
        {
#ifdef S_1BIT
            --sroll;
            S = sc[(*s >> sroll) & 1];
            if (sroll == 0) {
                sroll = 8;
                s++;
            }
#endif /* S_1BIT */
        }
#if defined(T_1BIT) && T_1BIT == MAYBE
        if (troll == 100
#endif
    active_line local_active[MAX_LOCAL_ACTIVE];
    int local_windings[MAX_LOCAL_ACTIVE];
};

#define LOOP_FILL_RECTANGLE_DIRECT(fo, x, y, w, h)\
  (/*fo->fill_direct*/FILL_DIRECT ?\
   (fo)->fill_rect((fo)->dev, x, y, w, h, (fo)->pdevc->colors.pure) :\
   gx_fill_rectangle_device_rop(x, y, w, h, (fo)->pdevc, (fo)->dev, (fo)->lop))

/* ---------------- Statistics ---------------- */

/* #define COLLECT_STATS_FILL */

#ifdef COLLECT_STATS_FILL
struct stats_fill_s {
    long
        fill, fill_alloc, y_up, y_down, horiz, x_step, slow_x, iter, find_y,
        band, band_step, band_fill, afill, slant, slant_shallow, sfill,
        mq_cross, cross_slow, cross_low, order, slow_order;
};
typedef struct stats_fill_s stats_fill_t;
extern stats_fill_t stats_fill;

#  define INCR(x) (++(stats_fill.x))
#  define INCR_EXPR(x) INCR(x)
#  define INCR_BY(x,n) (stats_fill.x += (n))
#else
#  define INCR(x) DO_NOTHING
#  define INCR_EXPR(x) discard(0)
#  define INCR_BY(x,n) DO_NOTHING
#endif

#endif /* gxfill_INCLUD monotonic_y;		/* "false" means "don't know"; only for scanline. */
    gx_flattened_iterator fi;
    bool more_flattened;
    int contour_count;
/*
 * "Pending" lines (not reached in the Y ordering yet) use next and prev
 * to order lines by increasing starting Y.  "Active" lines (being scanned)
 * use next and prev to order lines by increasing current X, or if the
 * current Xs are equal, by increasing final X.
 */
    active_line *prev, *next;
/* Link together active_lines allocated individually */
    active_line *alloc_next;
};

typedef struct fill_options_s {
    fixed ymin, ymax;
    const gx_device_color * pdevc;
    gs_logical_operation_t lop;
    bool fill_direct;
    fixed fixed_flat;
    bool fill_by_trapezoids;
    fixed adjust_left, adjust_right;
    fixed adjust_below, adjust_above;
    gx_device *dev;
    const gs_fixed_rect * pbox;
    bool is_spotan;
    int rule;
    dev_proc_fill_rectangle((*fill_rect));
    dev_proc_fill_trapezoid((*fill_trap));
} fill_options;

/* Line list structure */
ory_t *, uint, ulong);
/* Free pattern cache and its components. */
void gx_pattern_cache_free(gx_pattern_cache *pcache);

/* Get or set the Pattern cache in a gstate. */
gx_pattern_cache *gstate_pattern_cache(gs_gstate *);
void gstate_set_pattern_cache(gs_gstate *, gx_pattern_cache *);

/*
 * Define a device for accumulating the rendering of a Pattern.
 * This is actually a wrapper for two other devices: one that accumulates
 * the actual pattern image (if this is a colored pattern), and one that
 * accumulates a mask defining which pixels in the image are set.
 */
typedef struct gx_device_pattern_accum_s {
    gx_device_forward_common;
    /* Client sets these before opening */
    gs_memory_t *bitmap_memory;
    const gs_pattern1_instance_t *instance;
    /* open sets these */
    gx_device_memory *bits;	/* target also points to bits */
    gx_device_memory *mask;

    /* If we have transparency, then we will just
    use the PDF14 buffer directly instead
    of the memory device.  That is
    what this po{
    gs_matrix matrix;		/* CTM when the function was sampled */
    ulong max_size;		/* max bitmap size */
} gx_ht_order_screen_params_t;
struct gx_ht_order_s {
    gx_ht_cell_params_t params;	/* parameters defining the cells */
    ushort width;
    ushort height;
    ushort raster;
    ushort shift;
    ushort orig_height;
    ushort orig_shift;
    uint full_height;
    uint num_levels;		/* = levels size */
    uint num_bits;		/* = countof(bit_data) = width * height */
    const gx_ht_order_procs_t *procs;
    gs_memory_t *data_memory;	/* for levels and bit_data, may be 0 */
    uint *levels;
    void *bit_data;
    gx_ht_cache *cache;		/* cache to use */
    gx_transfer_map *transfer;	/* TransferFunction or 0 */
    gx_ht_order_screen_params_t screen_params;
    byte *threshold;
    bool threshold_inverted;
};

#define ht_order_is_complete(porder)\
  ((porder)->shift == 0)
#define ht_order_full_height(porder)\
  ((porder)->shift == 0 ? (porder)->height :\
   (porder)->width / igcd((porder)->width, (pordet a DeviceN color into device colorants using the custom client
 * client callback.
 */
int gx_remap_concrete_custom_color_DeviceN(const frac * pconc,
        const gs_color_space * pcs, gx_device_color * pdc,
        const gs_gstate * pgs, gx_device * dev, gs_color_select_t select);

/* "CLIENT COLOR CALLBACK APPLICATION INTERFACE" */
/*
 * In order to give some flexibility to the Ghostscript client API, we are
 * allowing the client to define a set of call back procedures for processing
 * color spaces.
 *
 * See the comments at the start of src/gsnamecl.c
 */
/*
 * The 'client color' call back structure definitions.  The call back structure
 * consists of a pointer to a list of client color space handling procedures
 * and a pointer to a client data structure.
 */

typedef struct client_custom_color_params_s {
    /* Client callback handlers */
    struct client_custom_color_procs_s * client_procs;
    /* For global client data */
    void * data;
} client_custom_color_params_t;

/*
 * Define a base type f_colors - See comments above.
 *
 * This routine returns a positive value (0 to n) which is the device colorant
 * number if the name is found.  It returns GX_DEVICE_COLOR_MAX_COMPONENTS if
 * the color component is found but is not being used due to the
 * SeparationOrder parameter.  It returns a negative value if not found.
 *
 * This routine will also add separations to the device if space is
 * available.
 */
int devn_get_color_comp_index(gx_device * dev,
    gs_devn_params * pdevn_params, equivalent_cmyk_color_params * pequiv_colors,
    const char * pname, int name_size, int component_type,
    int auto_spot_colors);

/* Utility routine for getting DeviceN parameters */
int devn_get_params(gx_device * pdev, gs_param_list * plist,
                    gs_devn_params * pdevn_params,
                    equivalent_cmyk_color_params * pequiv_colors);

/*
 * Utility routine for handling DeviceN related parameters.  This routine
 * assumes that the device is based upon a standard printer type device.
 * (See tcat _XMSTRINGGETTEXTCONCAT
#define _XmStrings _XMSTRINGS
#define _XmToHorizontalPixels _XMTOHORIZONTALPIXELS
#define _XmToVerticalPixels _XMTOVERTICALPIXELS
#define _XmTopShadowColorDefault _XMTOPSHADOWCOLORDEFAULT
#define _Xm_fastPtr _XM_FASTPTR
#define _XtCheckSubclassFlag _XTCHECKSUBCLASSFLAG
#define _XtInherit _XTINHERIT
#define _XtInheritTranslations _XTINHERITTRANSLATIONS
#define applicationShellWidgetClass APPLICATIONSHELLWIDGETCLASS
#define compositeWidgetClass COMPOSITEWIDGETCLASS
#define lib$ediv LIB$EDIV
#define lib$find_file LIB$FIND_FILE
#define lib$find_file_end LIB$FIND_FILE_END
#define lib$set_symbol LIB$SET_SYMBOL
#define lib$sfree1_dd LIB$SFREE1_DD
#define lib$spawn LIB$SPAWN
#define lib$subx LIB$SUBX
#define lib$wait LIB$WAIT
#define overrideShellWidgetClass OVERRIDESHELLWIDGETCLASS
#define pthread_attr_create PTHREAD_ATTR_CREATE
#define pthread_attr_delete PTHREAD_ATTR_DELETE
#define pthread_attr_destroy PTHREAD_ATTR_DESTROY
#define pthread_attr_getdetach_np PTHREAD_ATTR_GETDETACH_NP
#defiXT
#define XmCreateScrolledWindow XMCREATESCROLLEDWINDOW
#define XmCreateSelectionDialog XMCREATESELECTIONDIALOG
#define XmCreateSeparator XMCREATESEPARATOR
#define XmCreateSeparatorGadget XMCREATESEPARATORGADGET
#define XmCreateTemplateDialog XMCREATETEMPLATEDIALOG
#define XmCreateText XMCREATETEXT
#define XmCreateTextField XMCREATETEXTFIELD
#define XmCreateToggleButton XMCREATETOGGLEBUTTON
#define XmCreateToggleButtonGadget XMCREATETOGGLEBUTTONGADGET
#define XmCreateWarningDialog XMCREATEWARNINGDIALOG
#define XmCvtCTToXmString XMCVTCTTOXMSTRING
#define XmDestroyPixmap XMDESTROYPIXMAP
#define XmDragStart XMDRAGSTART
#define XmDropSiteRegister XMDROPSITEREGISTER
#define XmDropSiteUnregister XMDROPSITEUNREGISTER
#define XmDropSiteUpdate XMDROPSITEUPDATE
#define XmDropTransferStart XMDROPTRANSFERSTART
#define XmFileSelectionBoxGetChild XMFILESELECTIONBOXGETCHILD
#define XmFileSelectionDoSearch XMFILESELECTIONDOSEARCH
#define XmFontListAppendEntry XMFONTLISTAPPENDENTRY
#define XmFontListCopy XMFONTLISTCOPY
#defie XGetScreenSaver XGETSCREENSAVER
#define XGetSelectionOwner XGETSELECTIONOWNER
#define XGetSubImage XGETSUBIMAGE
#define XGetVisualInfo XGETVISUALINFO
#define XGetWMColormapWindows XGETWMCOLORMAPWINDOWS
#define XGetWMHints XGETWMHINTS
#define XGetWMName XGETWMNAME
#define XGetWMNormalHints XGETWMNORMALHINTS
#define XGetWindowAttributes XGETWINDOWATTRIBUTES
#define XGetWindowProperty XGETWINDOWPROPERTY
#define XGrabButton XGRABBUTTON
#define XGrabKeyboard XGRABKEYBOARD
#define XGrabPointer XGRABPOINTER
#define XGrabServer XGRABSERVER
#define XHeightOfScreen XHEIGHTOFSCREEN
#define XIconifyWindow XICONIFYWINDOW
#define XIfEvent XIFEVENT
#define XInitImage XINITIMAGE
#define XInstallColormap XINSTALLCOLORMAP
#define XInternAtom XINTERNATOM
#define XIntersectRegion XINTERSECTREGION
#define XKeycodeToKeysym XKEYCODETOKEYSYM
#define XKeysymToKeycode XKEYSYMTOKEYCODE
#define XKeysymToString XKEYSYMTOSTRING
#define XKillClient XKILLCLIENT
#define XListFonts XLISTFONTS
#define XListFontsWithInfo XLISTFONTSWITHINFO
#dft) & rop3_D) == 0 iff idempotent
 */
#define rop3_is_idempotent(op)\
  !( (~op) & ((op) << rop3_D_shift) & rop3_D )

/* Transparency */
#define source_transparent_default false
#define pattern_transparent_default false

/*
 * We define a logical operation as a RasterOp, transparency flags,
 * and render algorithm all packed into a single integer.
 * In principle, we should use a structure, but most C implementations
 * implement structure values very inefficiently.
 *
 * In addition, we define a "pdf14" flag which indicates that PDF
 * transparency is in effect. This doesn't change rendering in any way,
 * but does force the lop to be considered non-idempotent. The lop_pdf14
 * bit is used for fill/stroke ops but even if this is clear, we still
 * may be painting in a transparency buffer in an idempotent mode.
 */
#define lop_rop(lop) ((gs_rop3_t)((lop) & 0xff))        /* must be low-order bits */
#define lop_S_transparent 0x100
#define lop_T_transparent 0x200
#define lop_pdf14 0x400

static inline int
lop_she above, but using the caller_handle given here,
 * rather than the default one specified at gsapi_new_instance time. */
GSDLLEXPORT int GSDLLAPI gsapi_set_poll_with_handle(void *instance,
    int (GSDLLCALLPTR poll_fn)(void *caller_handle), void *caller_handle);

/* Set the display device callback structure.
 * If the display device is used, this must be called
 * after gsapi_new_instance() and before gsapi_init_with_args().
 * See gdevdisp.h for more details.
 * DEPRECATED: Use the gsapi_register_callback mechanism instead.
 */
GSDLLEXPORT int GSDLLAPI gsapi_set_display_callback(
   void *instance, display_callback *callback);

/* The callout mechanism allows devices to query "callers" (users of the
 * DLL) in device specific ways. The callout function pointer type will
 * be called with:
 *   callout_handle = the value given at registration
 *   device_name    = the name of the current device
 *   id             = An integer, guaranteed to be unique within the
 *                    callouts from a given d gx_monitor_t *lock;		/* handle for the monitor */
    bool cache_full;		/* flag that some thread needs a cache slot */
    gx_semaphore_t *full_wait;	/* semaphore for waiting when the cache is full */
} gsicc_link_cache_t;

/* A linked list structure to keep DeviceN ICC profiles
 * that the user wishes to use to achieve accurate rendering
 * with DeviceN (typically non CMYK or CMYK + spot) colors.
 * The ICC profiles used for this will require a special
 * private tag in the ICC profile that defines the colorant
 * names and they must match those in the DeviceN color
 * space.  Note this is not to say that DeviceN color
 * management can only be achieved with ICC profiles.  If
 * a customer has a proprietary mixing model for inks, they
 * will be able to hook in their method in the location
 * in the code where the DeviceN colors are processed.  If
 * there is no ICC color management of the DeviceN colors
 * and the DeviceN colors are NOT the native colors
 * for the device, then the colors will be transformackthresholdC;    /* Chrominance threshold */
        bool supports_devn;        /* If the target handles devn colors */
        gs_overprint_control_t overprint_control;	/* enable is the default */
        gsicc_namelist_t *spotnames;  /* If our device profiles are devn */
        bool prebandthreshold;     /* Used to indicate use of HT pre-clist */
        gs_memory_t *memory;
        rc_header rc;
};

/*  Used so that we can specify if we want to link with Device input color spaces
    during the link creation process. For the DeviceN case, the DeviceN profile
    must match the DeviceN profile in colorant order and number of colorants.
    Also, used to indicate if the profile matches one of the default profiles in
    the icc manager.  This is useful for reducing clist size since we will encode
    this value instead of the ICC profile.
*/
typedef enum {
    DEFAULT_NONE,   /* A profile that was actually embedded in a doc */
    DEFAULT_GRAY,   /* The default DeviceGray profile */
    DEFAULT_RGB,    /*  lists and devices */
/* Requires gxdevice.h */

#ifndef gxcpath_INCLUDED
#  define gxcpath_INCLUDED

#include "gxdevcli.h"

/* We expose the implementation of clipping lists so that clients */
/* can allocate clipping lists or devices on the stack. */

/*
 * For clipping, a path is represented as a list of rectangles.
 * Normally, a path is created as a list of segments;
 * installing it as a clipping path creates the rectangle list.
 * However, when the clipping path originates in some other way
 * (e.g., from initclip, or for clipping a cached character),
 * or if it is a non-trivial intersection of two paths,
 * the resulting clipping path exists only as a rectangle list;
 * clippath constructs the segment representation if needed.
 * Note that even if the path only exists as a rectangle list,
 * its bounding box (path.bbox) is still correct.
 */

/*
 * Rectangle list structure.
 * Consecutive gx_clip_rect entries either have the same Y values,
 * or ymin of this entry >= ymax of the previous entry.
 */
t_ptrs 3
/*extern_st(st_gs_text_params); */
#define public_st_gs_text_params() /* in gstext.c */\
  gs_public_st_composite(st_gs_text_params, gs_text_params_t,\
    "gs_text_params", text_params_enum_ptrs, text_params_reloc_ptrs)

/* Assuming REPLACE_WIDTHS is set, return the width of the i'th character. */
int gs_text_replaced_width(const gs_text_params_t *text, uint index,
                           gs_point *pwidth);

/*
 * Define the abstract type for the structure that tracks the state of text
 * processing.
 */
typedef struct gs_text_enum_s gs_text_enum_t;

/*
 * Define the driver procedure for text.  This procedure must allocate
 * the enumerator (see gxtext.h) and initialize the procs and rc members.
 */
#define dev_t_proc_text_begin(proc, dev_t)\
  int proc(dev_t *dev,\
    gs_gstate *pgs,\
    const gs_text_params_t *text,\
    gs_font *font,\
    const gx_clip_path *pcpath,		/* if DO_DRAW */\
    gs_text_enum_t **ppte)
#define dev_proc_text_begin(proc)\
  dev_t_proc_text_begin(proc, gx_device)

/*
 r for uncolored pattern */
    /* CAUTION: gs_paint_color structure must be the last field in
       gs_client_color_s to allow allocating a smaller space when
       a small number of color components is in use.
    */
};

extern_st(st_client_color);
#define public_st_client_color() /* in gscolor.c */\
  gs_public_st_ptrs1(st_client_color, gs_client_color, "gs_client_color",\
    client_color_enum_ptrs, client_color_reloc_ptrs, pattern)
#define st_client_color_max_ptrs 1

/* Define the color space for a transparency */
/* Used to keep track of parent versus child */
/* color space changes with Smask and for */
/* blending */
typedef enum {
    GRAY_SCALE,
    DEVICE_RGB,
    DEVICE_CMYK,
    CIE_XYZ,
    DEVICEN,
    ICC,
    UNKNOWN,
    OTHER
} gs_transparency_color_t;


/*
 * Color model component polarity. An "unknown" value has been added to
 * this enumeration.  This is used for devices and color spaces.
 */
typedef enum {
    GX_CINFO_POLARITY_UNKNOWN = -1,
    GX_CINFO_POLARITY_SUBTRACTIVE = 0,
    G= s[0] + (s[1] << 7) + (s[2] << 14) + ... (s[n] << (n * 7))
 *
 * In words, the high-order bit is used as a continue bit; it is off
 * only for the last byte of the string. The low-order 7 bits of each
 * byte for the base-128 digit, with the low-order digits preceding
 * the high-order digits.
 *
 * The encoding considers all numbers as unsigned. It may be used with
 * signed quantities (just change the interpretation), though obviously
 * it is inefficient with negative numbers.
 *
 * This code was originally part of the command list device module.
 * Though the names used here differ from those used from those used in
 * that module, they follow the same pattern, which accounts for certain
 * peculiarities.
 */
#define enc_u_shift     7
#define enc_u_lim_1b    (1U << enc_u_shift)
#define enc_u_lim_2b    (1U << (2 * enc_u_shift))

/* determine the encoded size of an (unsigned) integer */
extern  int     enc_u_size_uint(uint);

#define enc_u_sizew(w)                                      \
    ( (uint)(w) < enst gs_gstate * pgs, bool traditional);
int gx_fill_stroke_path(gs_gstate *pgs, int rule);

/*
 * gx_gstate_stroke_add needs a device for the sake of absolute-length
 * dots (and for no other reason).
 */
int gx_gstate_stroke_add(gx_path *ppath, gx_path *to_path,
                         gx_device *dev, const gs_gstate *pgs);

/* ------ Imager procedures ------ */

/*
 * Tweak the fill adjustment if necessary so that (nearly) empty
 * rectangles are guaranteed to produce some output.
 */
void gx_adjust_if_empty(const gs_fixed_rect *, gs_fixed_point *);

/*
 * Compute the amount by which to expand a stroked bounding box to account
 * for line width, caps and joins.  If the amount is too large to fit in a
 * gs_fixed_point, return gs_error_limitcheck.  Return 0 if the result is
 * exact, 1 if it is conservative.
 *
 * This procedure is fast, but the result may be conservative by a large
 * amount if the miter limit is large.  If this matters, use strokepath +
 * pathbbox.
 */
int gx_stroke_path_expansion(const ice -- the device that uses the mask image to
 * clip the (opaque) image data -- and its enumerator.
 * The device is closed and freed at the end of processing the image.
 */
#define IMAGE3_MAKE_MCDE_PROC(proc)\
  int proc(/* The initial arguments are those of begin_typed_image. */\
               gx_device *dev,\
           const gs_gstate *pgs,\
           const gs_matrix *pmat,\
           const gs_image_common_t *pic,\
           const gs_int_rect *prect,\
           const gx_drawing_color *pdcolor,\
           const gx_clip_path *pcpath, gs_memory_t *mem,\
           gx_image_enum_common_t **pinfo,\
           /* The following arguments are added. */\
           gx_device **pmcdev, gx_device *midev,\
           gx_image_enum_common_t *pminfo,\
           const gs_int_point *origin)
typedef IMAGE3_MAKE_MCDE_PROC((*image3_make_mcde_proc_t));

/*
 * Begin processing an ImageType 3 image, with the mask device creation
 * procedures as additional parameters.
 */
int gx_begin_image3_generic(gx_device * dev,
  fptr(op), (svar->read_id | svar->write_id) == r_size(op))
#define file_is_invalid(svar,op)\
  (svar = fptr(op), (svar->read_id | svar->write_id) != r_size(op))
#define check_file(svar,op)\
  BEGIN\
    check_type(*(op), t_file);\
    if ( file_is_invalid(svar, op) ) return_error(gs_error_ioerror);\
  END

/* Close a file stream. */
int file_close_file(stream *);

int file_close_finish(stream *);

/* Disable further access on the stream by mangling the id's */
int file_close_disable(stream *);

/* Create a stream on a string or a file. */
/* String ownership retained by the caller, for example
   Postscript string objects owned by the Postscript
   interpreter
 */
void sread_string(stream *, const byte *, uint);
void sread_string_reusable(stream *, const byte *, uint);

/* The string ownership is transferred from caller to stream.
   string_mem pointer must be allocator used to allocate the
   "string" buffer.
 */
void
sread_transient_string(stream *s, gs_memory_t *string_mem, const byte *ptr, uint len);
void
e time__INCLUDED

/* We must include std.h before any file that includes sys/types.h. */
#include "std.h"

/*
 * The location (or existence) of certain system headers is
 * environment-dependent. We detect this in the makefile
 * and conditionally define switches in gconfig_.h.
 */
#include "gconfig_.h"

/*
 * Some System V environments don't include sys/time.h.
 * The HAVE_SYS_TIME_H switch in gconfig_.h reflects this.
 */
#if defined(HAVE_SYS_TIME_H) && HAVE_SYS_TIME_H == 1
#  include <sys/time.h>
#  if defined(Plan9) || defined(M_UNIX) || defined(_IBMR2) || \
      defined(_SEQUENT_) || defined(__GNUC__) || defined(__INTEL_COMPILER) ||\
      defined(__hpux) || defined(__SUNPRO_C)
     /* Plan 9, SCO, AIX and Sequent's DYNIX/ptx need both time.h and
      * sys/time.h! As of version 2.2, at least some glibc
      * installations also require both files.
      * Following Duraid Madina's request we also do it on Intel compiler.
      */
#    include <time.h>
#  endif
#else
#  include <time.h>
#  if !defined      dst_bpc;    /* Destination bpc */
    int                  *errors;     /* Error diffusion table */
    byte                 *scaled_data;/* Downscaled data (only used for non
                                       * integer downscales). */
    int                   scaled_span;/* Num bytes in scaled scanline */
    gx_downscale_core    *down_core;  /* Core downscaling function */
    gs_get_bits_params_t  params;     /* Params if in planar mode */
    int                   num_comps;  /* Number of components as rendered */
    int                   num_planes; /* Number of planes if planar, 0 otherwise */

    gx_downscale_liner   *liner;      /* Source for line data */

    int                   early_cm;
    gx_downscale_cm_fn   *apply_cm;
    void                 *apply_cm_arg;
    int                   post_cm_num_comps;

    void                 *ets_config;
    gx_downscale_core    *ets_downscale;

    byte                 *pre_cm[GS_CLIENT_COLOR_MAX_COMPONENTS];
    byte                 *post_cmist *);
int gs_putdevparams(gx_io_device *, gs_param_list *);

/* Convert an OS error number to a PostScript error */
/* if opening a file fails. */
int gs_fopen_errno_to_code(int);

/* Interface functions for clients that want iodev independent access to */
/* the gp_enumerate functions */
file_enum *gs_enumerate_files_init(gs_memory_t * mem, const char *pat, uint patlen);
uint gs_enumerate_files_next(gs_memory_t * mem, file_enum * pfen, char *ptr, uint maxlen);
void gs_enumerate_files_close(gs_memory_t * mem, file_enum * pfen);

/* Test whether a string is equal to a character. */
/* (This is used for access testing in file_open procedures.) */
#define streq1(str, chr)\
  ((str)[0] == (chr) && (str)[1] == 0)

/* Finally, the IODevice structure itself. */
struct gx_io_device_s {
    const char *dname;		/* the IODevice name */
    const char *dtype;		/* the type returned by currentdevparams */
    gx_io_device_procs procs;
    gs_memory_t *memory;
    void *state;		/* (if the IODevice has state) */
};

structurveto/closepath, */
/* endpath */
int gdev_vector_dopath(gx_device_vector * vdev, const gx_path * ppath,
                       gx_path_type_t type, const gs_matrix *pmat);

/* dorect may call beginpath, moveto, lineto, closepath */
int gdev_vector_dorect(gx_device_vector * vdev, fixed x0, fixed y0,
                       fixed x1, fixed y1, gx_path_type_t type);

/* Finally, define the extended device structure. */
#define gx_device_vector_common\
        gx_device_common;\
        gs_memory_t *v_memory;\
                /* Output element writing procedures */\
        const gx_device_vector_procs *vec_procs;\
                /* Output file */\
        char fname[fname_size + 1];\
        gp_file *file;\
        stream *strm;\
        byte *strmbuf;\
        uint strmbuf_size;\
        int open_options;	/* see below */\
                /* Graphics state */\
        gs_gstate state;\
        float *dash_pattern;\
        uint dash_pattern_size;\
        bool fill_used_process_color;\
        bool stroke_used       if ( code == 1 )
        {
            code = (*dev_proc(dev, open_device))(dev);
            [Check code for <0]
        }
 *
 * This implementation also has the special property that it can forward
 * unrecognized param_read_ calls to another parameter list, called the
 * target.  This allows constructing incrementally modified parameter lists.
 * Note that this is only relevant for put_params (reading from the
 * parameter list).
 */

typedef struct gs_c_param_s gs_c_param;	/* opaque here */
typedef struct gs_c_param_list_s {
    gs_param_list_common;
    gs_c_param *head;
    gs_param_list *target;
    uint count;
    bool any_requested;
    gs_param_collection_type_t coll_type;
} gs_c_param_list;
#define private_st_c_param_list()	/* in gsparam.c */\
  gs_private_st_ptrs2(st_c_param_list, gs_c_param_list, "c_param_list",\
    c_param_list_enum_ptrs, c_param_list_reloc_ptrs, head, target)

/* Define a GC descriptor for gs_param_string. */
/* This structure descriptor is only for non persistent gs_paparam_string_array na;\
        dict_type d
typedef union gs_param_value_s {
    GS_PARAM_VALUE_UNION(gs_param_collection);
} gs_param_value;

/*
 * Define a structure containing a dynamically typed value (a value along
 * with its type).
 */
typedef struct gs_param_typed_value_s {
    gs_param_value value;
    gs_param_type type;
} gs_param_typed_value;
/*
 * Garbage collection of gs_param_values depends on the value type and on
 * the 'd' member of the union.  We provide enum_ptrs and reloc_ptrs
 * procedures that handle all the other cases -- i.e., cases other than
 * heterogenous collections.
 */
struct_proc_enum_ptrs(gs_param_typed_value_enum_ptrs);
struct_proc_reloc_ptrs(gs_param_typed_value_reloc_ptrs);
#define gs_param_typed_value_max_ptrs 1

/*
 * Define the representation alternatives for heterogenous collections.
 * _any must be 0, for Boolean testing.
 */
typedef enum {

    /* Create or accept a general dictionary. */

    gs_param_collection_dict_any = 0,

    /* Create a dictionary with integer);

void smask_copy(int num_rows, int num_cols, int row_stride,
                         byte *gs_restrict src, const byte *gs_restrict des);
int smask_icc(gx_device *dev, int num_rows, int num_cols, int n_chan,
               int row_stride, int plane_stride, byte *gs_restrict src, const byte *gs_restrict des,
               gsicc_link_t *icclink, bool deep);
/* For spot colors, blend modes must be white preserving and separable */
bool blend_valid_for_spot(gs_blend_mode_t blend_mode);

/**
 * art_blend_pixel_8: Compute PDF 1.4 blending function on 8-bit pixels.
 * @dst: Where to store resulting pixel.
 * @backdrop: Backdrop pixel color.
 * @src: Source pixel color.
 * @n_chan: Number of channels.
 * @blend_mode: Blend mode.
 * @pblend_procs: Procs for handling non separable blending modes.
 * @p14dev: pdf14 device.  Needed for handling CompatibleOverprint mode
 *
 * Computes the blend of two pixels according the PDF 1.4 transparency
 * spec (section 3.2, Blend Mode). A few things to keep in mind about
 * th


/* Client interface to Indexed color facilities */

#ifndef gscindex_INCLUDED
#  define gscindex_INCLUDED

#include "gscspace.h"
#include "gxfrac.h"

/*
 * Indexed color spaces.
 *
 * If the color space will use a procedure rather than a byte table,
 * ptbl should be set to 0.
 *
 * Unlike most of the other color space constructors, this one initializes
 * some of the fields of the colorspace. In the case in which a string table
 * is used for mapping, it initializes the entire structure. Note that the
 * client is responsible for the table memory in that case; the color space
 * will not free it when the color space itself is released.
 *
 * For the case of an indexed color space based on a procedure, a default
 * procedure will be provided that simply echoes the color values already in
 * the palette; the client may override these procedures by use of
 * gs_cspace_indexed_set_proc. If the client wishes to insert values into
 * the palette, it should do so by using gs_cspace_indexed_value_array, and
 * di every 100
 *    allocations and discover that the corruption happens between events
 *    X and X+100. You can then rerun using Memento_paranoidAt(X), and
 *    it'll only start exhaustively checking when it reaches X.
 *
 * More than one memory allocator?
 *
 *    If you have more than one memory allocator in the system (like for
 *    instance the ghostscript chunk allocator, that builds on top of the
 *    standard malloc and returns chunks itself), then there are some things
 *    to note:
 *
 *    * If the secondary allocator gets its underlying blocks from calling
 *      malloc, then those will be checked by Memento, but 'subblocks' that
 *      are returned to the secondary allocator will not. There is currently
 *      no way to fix this other than trying to bypass the secondary
 *      allocator. One way I have found to do this with the chunk allocator
 *      is to tweak its idea of a 'large block' so that it puts every
 *      allocation in its own chunk. Clearly this negates the point of having
xfont *proc(gx_device *dev, const byte *fname, uint len,\
    int encoding_index, const gs_uid *puid, const gs_matrix *pmat,\
    gs_memory_t *mem)
    xfont_proc_lookup_font((*lookup_font));

    /*
     * Convert a character name to an xglyph code.  encoding_index is
     * actually a gs_encoding_index_t.  Either chr or glyph may be absent
     * (gs_no_char/glyph), but not both.  glyph_name is the glyph's
     * (string) name if the glyph is not GS_NO_GLYPH and is not a CID.
     */
    /*
     * This procedure was deprecated as of release 3.43, but still
     * supported.  In release 7.21, the argument list was changed, and the
     * procedure is no longer deprecated.
     */

#define xfont_proc_char_xglyph(proc)\
  gx_xglyph proc(gx_xfont *xf, gs_char chr, int encoding_index,\
    gs_glyph glyph, const gs_const_string *glyph_name)
    xfont_proc_char_xglyph((*char_xglyph));

    /* Get the metrics for a character. */
    /* Note: pwidth changed in release 2.9.7. */

#define xfont_proc_char_metrics(proc)* allocate and initialize the iterator
   returns a pointer to its local state or NULL on failure */
void *gp_enumerate_fonts_init(gs_memory_t *mem);

/* get the next element in the font enumeration
   Takes a pointer to its local state and pointers in which to
   return C strings. The string 'name' is the font name, 'path'
   is the access path for the font resource. The returned strings
   are only safe to reference until until the next call.
   Returns 0 when no more fonts are available, a positive value
   on success, or negative value on error. */
int gp_enumerate_fonts_next(void *enum_state, char **fontname, char **path);

/* clean up and deallocate the iterator */
void gp_enumerate_fonts_free(void *enum_state);

/* ----- Platform specific file operations ----- */

/* The following functions are implemented by each platform, and
 * never called directly by devices or core code (only by the
 * gp_file functions themselves). */

FILE *gp_fopen_impl(gs_memory_t *mem, const char *fname, const char *mode);


/*
 * The following are only relevant for X Windows.
 */

/* Get the environment variable that specifies the display to use. */
const char *gp_getenv_display(void);

/* ------ File naming and accessing ------ */

/*
 * Define the maximum size of a file name returned by gp_open_scratch_file
 * or gp_open_printer.  (This should really be passed as an additional
 * parameter, but it would break too many clients to make this change now.)
 * Note that this is the size of the buffer, not the maximum number of
 * characters: the latter is one less, because of the terminating \0.
 *
 * This used to be 260, the same as the MAX_PATH value on Windows,
 * but although MAX_PATH still exists on Windows, it is no longer
 * the maximum length of a path - doh??
 * We now use 4k as a reasonable limit for most environments.
 */
#define gp_file_name_sizeof 4096

/* Define the character used for separating file names in a list. */
extern const char gp_file_name_list_separator;

/* Define the default scratch file name prefix. */
/


/* Definitions for Arcfour cipher and filter */
/* Requires scommon.h; strimpl.h if any templates are referenced */

#ifndef sarc4_INCLUDED
#  define sarc4_INCLUDED

#include "scommon.h"

/* Arcfour is a symmetric cipher whose state is maintained
 * in two indices into an accompanying 8x8 S box. this will
 * typically be allocated on the stack, and so has no memory
 * management associated.
 */
struct stream_arcfour_state_s
{
    stream_state_common;	/* a define from scommon.h */
    unsigned int x, y;
    unsigned char S[256];
};

typedef struct stream_arcfour_state_s stream_arcfour_state;

int s_arcfour_set_key(stream_arcfour_state * state, const unsigned char *key,
                      int keylength);

#define private_st_arcfour_state()	/* used in sarc4.c */\
  gs_private_st_simple(st_arcfour_state, stream_arcfour_state,\
    "Arcfour filter state")
extern const stream_template s_arcfour_template;

/* (de)crypt a section of text in a buffer -- the procedure is the same
 * in each direction. see strimpom).q.y;\
  END

/*
 * Calculate the difference of two rectangles, a list of up to 4 rectangles.
 * Return the number of rectangles in the list, and set the first rectangle
 * to the intersection.  The resulting first rectangle is guaranteed not to
 * be anomalous (q < p) iff it was not anomalous originally.
 *
 * Note that unlike the macros above, we need different versions of this
 * depending on the data type of the individual values: we'll only implement
 * the variations that we need.
 */
int int_rect_difference(gs_int_rect * outer, const gs_int_rect * inner,
                        gs_int_rect * diffs /*[4] */ );

/*
 * Check whether a parallelogram is a rectangle.
 */
#define PARALLELOGRAM_IS_RECT(ax, ay, bx, by)\
  ( ((ax) | (by)) == 0 || ((bx) | (ay)) == 0 )

/*
 * Convert a rectangular parallelogram to a rectangle, carefully following
 * the center-of-pixel rule in all cases.
 */
#define INT_RECT_FROM_PARALLELOGRAM(prect, px, py, ax, ay, bx, by)\
  BEGIN\
    int px_ = fixed2int_pixround(px);\
    iasic_enum_ptrs, basic_reloc_ptrs,\
    0, &supreloc\
  }
#define gs_public_st_suffix_add0_local(stname, stype, sname, supenum, supreloc, supstname)\
  gs__st_suffix_add0_local(public_st, stname, stype, sname, supenum, supreloc, supstname)
#define gs_private_st_suffix_add0_local(stname, stype, sname, supenum, supreloc, supstname)\
  gs__st_suffix_add0_local(private_st, stname, stype, sname, supenum, supreloc, supstname)

        /* Suffix subclasses with no additional pointers and finalization. */
        /* This is a hack -- subclasses should inherit finalization, */
        /* but that would require a superclass pointer in the descriptor, */
        /* which would perturb things too much right now. */

#define gs__st_suffix_add0_final(scope_st, stname, stype, sname, penum, preloc, pfinal, supstname)\
  static ENUM_PTRS_BEGIN_PROC(penum) {\
    ENUM_PREFIX(supstname, 0);\
  } ENUM_PTRS_END_PROC\
  static RELOC_PTRS_BEGIN(preloc) {\
    RELOC_PREFIX(supstname);\
  } RELOC_PTRS_END\
  gs__st_complex_only(scope_stype, e4, e5, e6)\
  };\
  gs__st_basic_final(scope_st, stname, stype, sname, penum, preloc, pfinal)
#define gs_public_st_ptrs6_final(stname, stype, sname, penum, preloc, pfinal, e1, e2, e3, e4, e5, e6)\
  gs__st_ptrs6_final(public_st, stname, stype, sname, penum, preloc, pfinal, e1, e2, e3, e4, e5, e6)
#define gs_private_st_ptrs6_final(stname, stype, sname, penum, preloc, pfinal, e1, e2, e3, e4, e5, e6)\
  gs__st_ptrs6_final(private_st, stname, stype, sname, penum, preloc, pfinal, e1, e2, e3, e4, e5, e6)

        /* Structures with 7 pointers. */

#define gs__st_ptrs7(scope_st, stname, stype, sname, penum, preloc, e1, e2, e3, e4, e5, e6, e7)\
  BASIC_PTRS(penum) {\
    GC_OBJ_ELT3(stype, e1, e2, e3), GC_OBJ_ELT3(stype, e4, e5, e6), GC_OBJ_ELT(stype, e7)\
  };\
  gs__st_basic(scope_st, stname, stype, sname, penum, preloc)
#define gs_public_st_ptrs7(stname, stype, sname, penum, preloc, e1, e2, e3, e4, e5, e6, e7)\
  gs__st_ptrs7(public_st, stname, stype, sname, penum, preloc, e1, e2, e3, e4, e5, e6, e7)
#defi*)vptr)->member, sizeof(((stype *)vptr)->member))
#define RELOC_SUPER(stype, supst, member)\
  RELOC_SUPER_ELT(stype, supst, member)

    /* Backward compatibility. */

#define ENUM_RETURN(ptr) return ENUM_OBJ(ptr)
#define ENUM_RETURN_PTR(typ, elt) return ENUM_OBJ_ELT(typ, elt)
#define ENUM_RETURN_STRING_PTR(typ, elt) return ENUM_STRING_ELT(typ, elt)
#define ENUM_RETURN_CONST_STRING(ptr) return ENUM_CONST_STRING(ptr)
#define ENUM_RETURN_CONST_STRING_PTR(typ, elt) return ENUM_CONST_STRING_ELT(typ, elt)

/* -------------- Simple structures (no internal pointers). -------------- */

#define gs__st_simple(scope_st, stname, stype, sname)\
  scope_st stname = { sizeof(stype), sname, 0, 0, gs_no_struct_enum_ptrs, gs_no_struct_reloc_ptrs, 0, 0 }
#define gs_public_st_simple(stname, stype, sname)\
  gs__st_simple(public_st, stname, stype, sname)
#define gs_private_st_simple(stname, stype, sname)\
  gs__st_simple(private_st, stname, stype, sname)

#define gs__st_simple_final(scope_st, stname, stype, sname, pfinal)\
  scif the definer of a structure wants to make
 * available the ability to create an instance but does not want to
 * expose the structure definition, it must export a creator procedure.
 */
/*
 * If the structure is defined in a .c file, we require that the following
 * appear together:
 *      - The definition of the structure xxx_s;
 *      - The gs_private_st_xxx macro that creates the descriptor.
 * Note that we only allow this if the structure is completely private
 * to a single file.  Again, the file must export a creator procedure
 * if it wants external clients to be able to create instances.
 *
 * Some structures are embedded inside others.  In order to be able to
 * construct the composite pointer enumeration procedures, for such
 * structures we must define not only the st_xxx descriptor, but also
 * a st_xxx_max_ptrs constant that gives the maximum number of pointers
 * the enumeration procedure will return.  This is an unfortunate consequence
 * of the method we have chosen for implementing pointeation. */
void fn_common_free(gs_function_t * pfn, bool free_params, gs_memory_t * mem);

/* Check the values of m, n, Domain, and (if supplied) Range. */
int fn_check_mnDR(const gs_function_params_t * params, int m, int n);

/* Generic get_info implementation (no Functions or DataSource). */
FN_GET_INFO_PROC(gs_function_get_info_default);

/*
 * Write generic parameters (FunctionType, Domain, Range) on a parameter list.
 */
int fn_common_get_params(const gs_function_t *pfn, gs_param_list *plist);

/*
 * Copy an array of numeric values when scaling a function.
 */
void *fn_copy_values(const void *pvalues, int count, int size,
                     gs_memory_t *mem);

/*
 * If necessary, scale the Range or Decode array for fn_make_scaled.
 * Note that we must always allocate a new array.
 */
int fn_scale_pairs(const float **ppvalues, const float *pvalues, int npairs,
                   const gs_range_t *pranges, gs_memory_t *mem);

/*
 * Scale the generic part of a function (Domain and Range).
 * The client mused.current_glyph appropriately;
     *   also, it must reset the current font in the graphics state to its
     *   original value each time each time (after the first) that the
     *   procedure is called to process further characters of the string.
     *
     *   - If TEXT_RETURN_WIDTH is set, the procedure must set
     *   returned.total_width when(ever) it returns.
     *
     * We should provide a default implementation that makes all these
     * things simple, but currently we don't.
     */

#define text_enum_proc_process(proc)\
  int proc(gs_text_enum_t *pte)

    text_enum_proc_process((*process));

    /*
     * After the implementation returned TEXT_PROCESS_RENDER, determine
     * whether it needs the entire character description, or only the width
     * (escapement).
     */

#define text_enum_proc_is_width_only(proc)\
  bool proc(const gs_text_enum_t *pte)

    text_enum_proc_is_width_only((*is_width_only));

    /*
     * Return the width of the current character (in user space coordinatesdefine public_st_gs_text_enum()	/* in gstext.c */\
  gs_public_st_composite(st_gs_text_enum, gs_text_enum_t, "gs_text_enum_t",\
    text_enum_enum_ptrs, text_enum_reloc_ptrs)

/*
 * Initialize a newly created text enumerator.  Implementations of
 * text_begin must call this just after allocating the enumerator.
 * Note that this procedure can return an error, e.g., if attempting
 * a glyph-based operation with a composite font.
 */
int gs_text_enum_init(gs_text_enum_t *pte,
                      const gs_text_enum_procs_t *procs,
                      gx_device *dev, gs_gstate *pgs,
                      const gs_text_params_t *text,
                      gs_font *font,
                      const gx_clip_path *pcpath,
                      gs_memory_t *mem);

/* Allocate a text enumerator.
 * This is primarily intended for code avoiding the device API, such
 * as that purely for retrieving metrics
 */
gs_text_enum_t *
gs_text_enum_alloc(gs_memory_t * mem, gs_gstate * pgs, client_name_t cname);

/*
 * Copy thrner, Robert Wilhelm, and Werner Lemberg.
 *
 *  This file is part of the FreeType project, and may only be used
 *  modified and distributed under the terms of the FreeType project
 *  license, LICENSE.TXT. By continuing to use, modify, or distribute
 *  this file you indicate that you have read the license and
 *  understand and accept it fully.
 *
 *  NOTE:
 *
 *   All these declarations are library internals, and *not* part
 *   of the high-level interface.  See also 'freetype.h'.
 *
 ******************************************************************/

#ifndef TTTYPES_H
#define TTTYPES_H

#include "ttconfig.h"
#include "tttype.h"

#ifdef DEBUG
#ifndef ARM_1212
#include <stdlib.h>
#include <stdio.h>
#else
#include "std.h"
#endif
#endif

  typedef unsigned char   Byte;

  typedef unsigned short  UShort;
  typedef signed   short  Short;

  typedef unsigned long   ULong;
  typedef signed   long   Long;

  typedef int             Int;

  typedef long            Integer;

  /* Simple access types: pointers and  any necessary color mapping data.
 */
int cmd_put_color_mapping(gx_device_clist_writer * cldev,
                                  const gs_gstate * pgs);
/*
 * Add commands to represent a full (device) halftone.
 * (This routine should probably be in some other module.)
 */
int cmd_put_halftone(gx_device_clist_writer * cldev,
                     const gx_device_halftone * pdht);

/* ------ Exported by gxclrast.c for gxclread.c ------ */

/*
 * Define whether we are actually rendering a band, or just executing
 * the put_params that occurs at the beginning of each page.
 */
typedef enum {
    playback_action_render,
    playback_action_render_no_pdf14,
    playback_action_setup
} clist_playback_action;

/* Play back and rasterize one band. */
int clist_playback_band(clist_playback_action action,
                        gx_device_clist_reader *cdev,
                        stream *s, gx_device *target,
                        int x0, int y0, gs_memory_t *mem);

/* Playback the band file, taking the indicated ve cache space for the reading pass based on the replicated size.
 * See the clist_change_tile procedure for the algorithm that chooses the
 * replication factors.
 */

/* ---------------- Block file entries ---------------- */

typedef struct cmd_block_s {
    int band_min, band_max;
#define cmd_band_end (-1)	/* end of band file */
    int64_t pos;		/* starting position in cfile */
} cmd_block;

/* ---------------- Band state ---------------- */

/* Remember the current state of one band when writing or reading. */
struct gx_clist_state_s {
    gx_color_index colors[2];	/* most recent colors */
    gx_device_color_saved sdc;  /* last device color for this band */
    uint tile_index;		/* most recent tile index */
    gx_bitmap_id tile_id;	/* most recent tile id */
/* Since tile table entries may be deleted and/or moved at any time, */
/* the following is the only reliable way to check whether tile_index */
/* references a particular tile id: */
#define cls_has_tile_id(cldev, pcls, tid, offset_temp)\
  ((pcls);
void clist_cfd_init(stream_CFD_state *ss, int width, int height,
                    gs_memory_t *mem);

/* Write out a block of data of arbitrary size and content to a      */
/* specified band at the given offset PAST the last band in the page */
/* Used for various data such as the icc profile table and the       */
/* per band color_usage array                                        */
/*                                                                   */
/* If the size is not well defined, then the data itself should      */
/* contain information for length or logical end-of-data.            */
int cmd_write_pseudo_band(gx_device_clist_writer *cldev, unsigned char *pbuf,
                          int data_size, int pseudo_band_offset);
/*
 * A command always consists of an operation followed by operands;
 * the syntax of the operands depends on the operation.
 * In the operation definitions below:
 *      + (prefixed) means the operand is in the low 4 bits of the opcode.
 *      # means a variable-s | \
        (1<<BLEND_MODE_Exclusion)) >> (B)) & 1) == 0)

/* Define the parameter structure for a transparency group. */
/* (Update gs_trans_group_params_init if these change.) */
typedef struct gs_transparency_group_params_s {
    const gs_color_space *ColorSpace;
    bool Isolated;
    bool Knockout;
    float group_shape;
    float group_opacity;
    bool image_with_SMask;
    int text_group;
    bool shade_group;
    bool page_group;
    bool idle;
    uint mask_id;
    int group_color_numcomps;
    gs_transparency_color_t group_color_type;
    int64_t icc_hashcode;                    /* Needed when we are doing clist reading */
    cmm_profile_t *iccprofile;               /* The profile  */
} gs_transparency_group_params_t;

/* Define the parameter structure for a transparency mask. */
typedef enum {
    TRANSPARENCY_MASK_Alpha,
    TRANSPARENCY_MASK_Luminosity,
    TRANSPARENCY_MASK_None          /* special case for removing a SMask from the tos */
} gs_transparency_mask_subtype_t;

#define GS_TRANSPA-------- */

/* is_spotan_device() in gxfill.c uses san_open */
/* to identify the spot analyzer device         */
dev_proc_open_device(san_open);

#endif /* gzspotan_INCLUDED */
/* Copyright (C) 2001-2023 Artifex Software, Inc.
   All Rights Reserved.

   This software is provided AS-IS with no warranty, either express or
   implied.

   This software is distributed under license and may not be copied,
   modified or distributed except as expressly authorized under the terms
   of the license contained in the file LICENSE in this distribution.

   Refer to licensing information at http://www.artifex.com or contact
   Artifex Software, Inc.,  39 Mesa Street, Suite 108A, San Francisco,
   CA 94129, USA, for further information.
*/


/* Common definitions for default subclass device */

#ifndef gdev_default_subclass_INCLUDED
#  define gdev_default_subclass_INCL