/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (https://www.swig.org).
 * Version 4.5.1
 *
 * Do not make changes to this file unless you know what you are doing - modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

#define SWIG_PYTHON_INTERPRETER_NO_DEBUG

/* This seems to be necessary on some Windows machines with Py_LIMITED_API,
otherwise compilation can fail because free() and malloc() are not declared. */
#include <stdlib.h>



#define SWIG_VERSION 0x040501
#define SWIGPYTHON
#define SWIG_PYTHON_DIRECTOR_NO_VTABLE

#define SWIG_name    "_extra"
/* -----------------------------------------------------------------------------
 *  This section contains generic SWIG labels for method/variable
 *  declarations/attributes, and other compiler dependent labels.
 * ----------------------------------------------------------------------------- */

/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
#  define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
#  define SWIGTEMPLATEDISAMBIGUATOR template
# else
#  define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif

/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
#   define SWIGINLINE inline
# else
#   define SWIGINLINE
# endif
#endif

/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
#     define SWIGUNUSED __attribute__ ((__unused__))
#   else
#     define SWIGUNUSED
#   endif
# elif defined(__ICC) || defined (__clang__)
#   define SWIGUNUSED __attribute__ ((__unused__))
# else
#   define SWIGUNUSED
# endif
#endif

#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
#   pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif

#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
#   define SWIGUNUSEDPARM(p)
# else
#   define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif

/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif

/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif

/* exporting methods */
#if defined(__GNUC__)
#  if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
#    ifndef GCC_HASCLASSVISIBILITY
#      define GCC_HASCLASSVISIBILITY
#    endif
#  endif
#endif

#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
#   if defined(STATIC_LINKED)
#     define SWIGEXPORT
#   else
#     define SWIGEXPORT __declspec(dllexport)
#   endif
# else
#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
#     define SWIGEXPORT __attribute__ ((visibility("default")))
#   else
#     define SWIGEXPORT
#   endif
# endif
#endif

/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
#   define SWIGSTDCALL __stdcall
# else
#   define SWIGSTDCALL
# endif
#endif

/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif

/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif

/* Deal with Apple's deprecated 'AssertMacros.h' from Carbon-framework */
#if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES)
# define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
#endif

/* Intel's compiler complains if a variable which was never initialised is
 * cast to void, which is a common idiom which we use to indicate that we
 * are aware a variable isn't used.  So we just silence that warning.
 * See: https://github.com/swig/swig/issues/192 for more discussion.
 */
#ifdef __INTEL_COMPILER
# pragma warning disable 592
#endif

#if defined(__cplusplus) && __cplusplus >= 201103L
# define SWIG_NOEXCEPT noexcept
#else
# define SWIG_NOEXCEPT throw()
#endif 

#define SWIG_QUOTE_STRING(x) #x
#define SWIG_STRINGIFY(x) SWIG_QUOTE_STRING(x)

/* -----------------------------------------------------------------------------
 * swigcompat.swg
 *
 * Macros to provide support compatibility with older C and C++ standards.
 *
 * Note that SWIG expects __cplusplus to be defined to the appropriate C++ standard.
 * MSVC users are urged to check and examine the /Zc:__cplusplus compiler option.
 * See https://learn.microsoft.com/en-us/cpp/build/reference/zc-cplusplus.
 * ----------------------------------------------------------------------------- */

/* C99 and C++11 should provide snprintf, but define SWIG_NO_SNPRINTF
 * if you're missing it.
 */
#if ((defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) || \
     (defined __cplusplus && __cplusplus >= 201103L) || \
     defined SWIG_HAVE_SNPRINTF) && \
    !defined SWIG_NO_SNPRINTF
# define SWIG_snprintf(O,S,F,A) snprintf(O,S,F,A)
# define SWIG_snprintf2(O,S,F,A,B) snprintf(O,S,F,A,B)
#else
/* Fallback versions ignore the buffer size, but most of our uses either have a
 * fixed maximum possible size or dynamically allocate a buffer that's large
 * enough.
 */
# define SWIG_snprintf(O,S,F,A) sprintf(O,F,A)
# define SWIG_snprintf2(O,S,F,A,B) sprintf(O,F,A,B)
#endif


#if defined(__GNUC__) && defined(_WIN32) && !defined(SWIG_PYTHON_NO_HYPOT_WORKAROUND)
/* Workaround for '::hypot' has not been declared', see https://bugs.python.org/issue11566 */
# include <math.h>
#endif

#if !defined(PY_SSIZE_T_CLEAN) && !defined(SWIG_NO_PY_SSIZE_T_CLEAN)
#define PY_SSIZE_T_CLEAN
#endif

#if __GNUC__ >= 7
#pragma GCC diagnostic push
#if defined(__cplusplus) && __cplusplus >= 201703L
#pragma GCC diagnostic ignored "-Wregister" /* For python-2.7 headers that use register */
#endif
#endif

#if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG)
/* Use debug wrappers with the Python release dll */

#if defined(_MSC_VER) && _MSC_VER >= 1929
/* Workaround compilation errors when redefining _DEBUG in MSVC 2019 version 16.10 and later
 * See https://github.com/swig/swig/issues/2090 */
# include <corecrt.h>
#endif

# undef _DEBUG
# include <Python.h>
# define _DEBUG 1
#else
# include <Python.h>
#endif


#if __GNUC__ >= 7
#pragma GCC diagnostic pop
#endif

#include <stdio.h>
#include <stdlib.h>

/* -----------------------------------------------------------------------------
 * swigrun.swg
 *
 * This file contains generic C API SWIG runtime support for pointer
 * type checking.
 * ----------------------------------------------------------------------------- */

/* This should only be incremented when either the layout of swig_type_info changes,
   or for whatever reason, the runtime changes incompatibly */
#define SWIG_RUNTIME_VERSION "5"

/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
#ifdef SWIG_TYPE_TABLE
# define SWIG_TYPE_TABLE_NAME SWIG_STRINGIFY(SWIG_TYPE_TABLE)
#else
# define SWIG_TYPE_TABLE_NAME
#endif

/*
  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
  creating a static or dynamic library from the SWIG runtime code.
  In 99.9% of the cases, SWIG just needs to declare them as 'static'.

  But only do this if strictly necessary, ie, if you have problems
  with your compiler or suchlike.
*/

#ifndef SWIGRUNTIME
# define SWIGRUNTIME SWIGINTERN
#endif

#ifndef SWIGRUNTIMEINLINE
# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
#endif

/*  Generic buffer size */
#ifndef SWIG_BUFFER_SIZE
# define SWIG_BUFFER_SIZE 1024
#endif

/* Flags for pointer conversions */
#define SWIG_POINTER_DISOWN        0x1
#define SWIG_CAST_NEW_MEMORY       0x2
#define SWIG_POINTER_NO_NULL       0x4
#define SWIG_POINTER_CLEAR         0x8
#define SWIG_POINTER_RELEASE       (SWIG_POINTER_CLEAR | SWIG_POINTER_DISOWN)

/* Flags for new pointer objects */
#define SWIG_POINTER_OWN           0x1


/*
   Flags/methods for returning states.

   The SWIG conversion methods, as ConvertPtr, return an integer
   that tells if the conversion was successful or not. And if not,
   an error code can be returned (see swigerrors.swg for the codes).

   Use the following macros/flags to set or process the returning
   states.

   In old versions of SWIG, code such as the following was usually written:

     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
       // success code
     } else {
       //fail code
     }

   Now you can be more explicit:

    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
    if (SWIG_IsOK(res)) {
      // success code
    } else {
      // fail code
    }

   which is the same really, but now you can also do

    Type *ptr;
    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
    if (SWIG_IsOK(res)) {
      // success code
      if (SWIG_IsNewObj(res) {
        ...
	delete *ptr;
      } else {
        ...
      }
    } else {
      // fail code
    }

   I.e., now SWIG_ConvertPtr can return new objects and you can
   identify the case and take care of the deallocation. Of course that
   also requires SWIG_ConvertPtr to return new result values, such as

      int SWIG_ConvertPtr(obj, ptr,...) {
        if (<obj is ok>) {
          if (<need new object>) {
            *ptr = <ptr to new allocated object>;
            return SWIG_NEWOBJ;
          } else {
            *ptr = <ptr to old object>;
            return SWIG_OLDOBJ;
          }
        } else {
          return SWIG_BADOBJ;
        }
      }

   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
   SWIG errors code.

   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
   allows returning the 'cast rank', for example, if you have this

       int food(double)
       int fooi(int);

   and you call

      food(1)   // cast rank '1'  (1 -> 1.0)
      fooi(1)   // cast rank '0'

   just use the SWIG_AddCast()/SWIG_CheckState()
*/

#define SWIG_OK                    (0)
/* Runtime errors are < 0 */
#define SWIG_ERROR                 (-1)
/* Errors in range -1 to -99 are in swigerrors.swg (errors for all languages including those not using the runtime) */
/* Errors in range -100 to -199 are language specific errors defined in *errors.swg */
/* Errors < -200 are generic runtime specific errors */
#define SWIG_ERROR_RELEASE_NOT_OWNED (-200)

#define SWIG_IsOK(r)               (r >= 0)
#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)

/* The CastRankLimit says how many bits are used for the cast rank */
#define SWIG_CASTRANKLIMIT         (1 << 8)
/* The NewMask denotes the object was created (using new/malloc) */
#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)
/* The TmpMask is for in/out typemaps that use temporary objects */
#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)
/* The binary string mask denotes using string without unicode */
#define SWIG_BINARYSTRMASK         (SWIG_TMPOBJMASK << 1)
/* Simple returning values */
#define SWIG_BADOBJ                (SWIG_ERROR)
#define SWIG_OLDOBJ                (SWIG_OK)
#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)
#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)
#define SWIG_BINARYSTR             (SWIG_OK | SWIG_BINARYSTRMASK)
/* Check, add and del object mask methods */
#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
#define SWIG_AddBinaryStrMask(r)   (SWIG_IsOK(r) ? (r | SWIG_BINARYSTRMASK) : r)
#define SWIG_DelBinaryStrMask(r)   (SWIG_IsOK(r) ? (r & ~SWIG_BINARYSTRMASK) : r)
#define SWIG_IsBinaryStr(r)        (SWIG_IsOK(r) && (r & SWIG_BINARYSTRMASK))

/* Cast-Rank Mode */
#if defined(SWIG_CASTRANK_MODE)
#  ifndef SWIG_TypeRank
#    define SWIG_TypeRank             unsigned long
#  endif
#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */
#    define SWIG_MAXCASTRANK          (2)
#  endif
#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)
#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)
SWIGINTERNINLINE int SWIG_AddCast(int r) {
  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
}
SWIGINTERNINLINE int SWIG_CheckState(int r) {
  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0;
}
#else /* no cast-rank mode */
#  define SWIG_AddCast(r) (r)
#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
#endif


#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef void *(*swig_converter_func)(void *, int *);
typedef struct swig_type_info *(*swig_dycast_func)(void **);

/* Structure to store information on one type */
typedef struct swig_type_info {
  const char             *name;			/* mangled name of this type */
  const char             *str;			/* human readable name of this type */
  swig_dycast_func        dcast;		/* dynamic cast function down a hierarchy */
  struct swig_cast_info  *cast;			/* linked list of types that can cast into this type */
  void                   *clientdata;		/* language specific type data */
  int                    owndata;		/* flag if the structure owns the clientdata */
} swig_type_info;

/* Structure to store a type and conversion function used for casting */
typedef struct swig_cast_info {
  swig_type_info         *type;			/* pointer to type that is equivalent to this type */
  swig_converter_func     converter;		/* function to cast the void pointers */
  struct swig_cast_info  *next;			/* pointer to next array of casts | pointer to cast hashed by value */
  unsigned int            value;		/* index of the last valid element in the array | typename hash value */
} swig_cast_info;

/* Structure used to store module information
 * Each module generates one structure like this, and the runtime collects
 * all of these structures and stores them in a circularly linked list.*/
typedef struct swig_module_info {
  swig_type_info         **types;		/* Array of pointers to swig_type_info structures that are in this module */
  size_t                 size;		        /* Number of types in this module */
  struct swig_module_info *next;		/* Pointer to next element in circularly linked list */
  swig_type_info         **type_initial;	/* Array of initially generated type structures */
  swig_cast_info         **cast_initial;	/* Array of initially generated casting structures */
  void                    *clientdata;		/* Language specific module data */
} swig_module_info;

/*
  Compare two type names skipping the space characters, therefore
  "char*" == "char *" and "Class<int>" == "Class<int >", etc.

  Return 0 when the two name types are equivalent, as in
  strncmp, but skipping ' '.
*/
SWIGRUNTIME int
SWIG_TypeNameComp(const char *f1, const char *l1,
		  const char *f2, const char *l2) {
  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
    while ((*f1 == ' ') && (f1 != l1)) ++f1;
    while ((*f2 == ' ') && (f2 != l2)) ++f2;
    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;
  }
  return (int)((l1 - f1) - (l2 - f2));
}

/*
  Check type equivalence in a name list like <name1>|<name2>|...
  Return 0 if equal, -1 if nb < tb, 1 if nb > tb
*/
SWIGRUNTIME int
SWIG_TypeCmp(const char *nb, const char *tb) {
  int equiv = 1;
  const char* te = tb + strlen(tb);
  const char* ne = nb;
  while (equiv != 0 && *ne) {
    for (nb = ne; *ne; ++ne) {
      if (*ne == '|') break;
    }
    equiv = SWIG_TypeNameComp(nb, ne, tb, te);
    if (*ne) ++ne;
  }
  return equiv;
}

/*
  Check type equivalence in a name list like <name1>|<name2>|...
  Return 0 if not equal, 1 if equal
*/
SWIGRUNTIME int
SWIG_TypeEquiv(const char *nb, const char *tb) {
  return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0;
}

/*
 * Hash function for type name strings, based on maRushPrime1Hash (http://amsoftware.narod.ru/algo2.html)
 */
SWIGRUNTIME unsigned int SWIG_Hash(const char *str, unsigned int len) {
  const unsigned char *data = (const unsigned char *)str;
  unsigned int hash = len, i = 0, k;
  int rem = (int)len;

  while (rem >= (int)sizeof(unsigned int)) {
    memcpy(&k, data, sizeof(unsigned int));
    k += i++;
    hash ^= k;
    hash *= 171717;
    data += sizeof(unsigned int);
    rem -= (int)sizeof(unsigned int);
  }

  switch (rem) {
    case 3: k = (unsigned int)(data[2]) << 16;
            k |= (unsigned int)(data[1]) << 8;
            k |= (unsigned int)(data[0]);
            k += i++;
            hash ^= k;
            hash *= 171717;
            break;
    case 2: k = (unsigned int)(data[1]) << 8;
            k |= (unsigned int)(data[0]);
            k += i++;
            hash ^= k;
            hash *= 171717;
            break;
    case 1: k = (unsigned int)(data[0]);
            k += i++;
            hash ^= k;
            hash *= 171717;
            break;
  }
  return hash;
}

/*
  Check the typename
*/
SWIGRUNTIME swig_cast_info *
SWIG_TypeCheck(const char *c, swig_type_info *ty) {
  static const unsigned int scan_threshold = 4;
  if (ty) {
    swig_cast_info *head = ty->cast;
    unsigned int hash_value = 0;
    int hashed = 0;

    while (head) {

      if (strcmp(head->type->name, c) == 0) {
        return head;
      }

      if (head->value) {
        swig_cast_info *iter;
        swig_cast_info *last = head + head->value;
        swig_cast_info *first = head + 1;
        int search = 1;

        if (!hashed) {
          if (head->value < scan_threshold) {
            for (iter = first; iter <= last; iter++) {
              if (strcmp(iter->type->name, c) == 0) {
                return iter;
              }
            }
            search = 0;
          } else {
            hashed = 1;
            hash_value = SWIG_Hash(c, (unsigned int)strlen(c));
          }
        }

        if (search) {
          /* Binary search over sorted <'next'|'value'> pairs */
          do {
            iter = first + ((last - first) >> 1);
            if (iter->value < hash_value) {
              first = iter + 1;
            } else if (iter->value == hash_value) {

              if (strcmp(iter->next->type->name, c) == 0) {
                return iter->next;
              }

              /* Hash collision check */
              for (last = iter + 1; last->next && last->value == hash_value; last++) {
                if (strcmp(last->next->type->name, c) == 0) {
                  return last->next;
                }
              }
              for (first = iter - 1; first != head && first->value == hash_value; first--) {
                if (strcmp(first->next->type->name, c) == 0) {
                  return first->next;
                }
              }
              break;
            } else
              last = iter - 1;
          } while (first <= last);
        }
      }
      head = head->next;
    }
  }
  return 0;
}

/*
  Check the type by type address
*/
SWIGRUNTIME swig_cast_info *
SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) {
  if (ty) {
    swig_cast_info *head = ty->cast;
    while (head) {
      if (head->type == from) {
        return head;
      }

      if (head->value) {
        swig_cast_info *iter;
        swig_cast_info *last = head + head->value;
        swig_cast_info *first = head + 1;

        /* Binary search over sorted array of casts */
        do {
          iter = first + ((last - first) >> 1);
          if (iter->type < from) {
            first = iter + 1;
          } else if (iter->type == from) {
            return iter;
          } else
            last = iter - 1;
        } while (first <= last);
      }
      head = head->next;
    }
  }
  return 0;
}

/*
  Cast a pointer up an inheritance hierarchy
*/
SWIGRUNTIMEINLINE void *
SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {
  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);
}

/*
   Dynamic pointer casting. Down an inheritance hierarchy
*/
SWIGRUNTIME swig_type_info *
SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
  swig_type_info *lastty = ty;
  if (!ty || !ty->dcast) return ty;
  while (ty && (ty->dcast)) {
    ty = (*ty->dcast)(ptr);
    if (ty) lastty = ty;
  }
  return lastty;
}

/*
  Return the name associated with this type
*/
SWIGRUNTIMEINLINE const char *
SWIG_TypeName(const swig_type_info *ty) {
  return ty->name;
}

/*
  Return the pretty name associated with this type,
  that is an unmangled type name in a form presentable to the user.
*/
SWIGRUNTIME const char *
SWIG_TypePrettyName(const swig_type_info *type) {
  /* The "str" field contains the equivalent pretty names of the
     type, separated by vertical-bar characters.  Choose the last
     name. It should be the most specific; a fully resolved name
     but not necessarily with default template parameters expanded. */
  if (!type) return NULL;
  if (type->str != NULL) {
    const char *last_name = type->str;
    const char *s;
    for (s = type->str; *s; s++)
      if (*s == '|') last_name = s+1;
    return last_name;
  }
  else
    return type->name;
}

/*
   Set the clientdata field for a type
*/
SWIGRUNTIME void
SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
  swig_cast_info *head = ti->cast;
  /* if (ti->clientdata == clientdata) return; */
  ti->clientdata = clientdata;

  while (head) {
    swig_cast_info *cast;
    for (cast = head; (unsigned int)(cast - head) <= head->value; cast++) {
      if (!cast->converter) {
        swig_type_info *tc = cast->type;
        if (!tc->clientdata) {
          SWIG_TypeClientData(tc, clientdata);
        }
      }
    }
    head = head->next;
  }
}

SWIGRUNTIME void
SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
  SWIG_TypeClientData(ti, clientdata);
  ti->owndata = 1;
}

/*
  Search for a swig_type_info structure only by mangled name
  Search is a O(log #types)

  We start searching at module start, and finish searching when start == end.
  Note: if start == end at the beginning of the function, we go all the way around
  the circular list.
*/
SWIGRUNTIME swig_type_info *
SWIG_MangledTypeQueryModule(swig_module_info *start,
                            swig_module_info *end,
		            const char *name) {
  swig_module_info *iter = start;
  do {
    if (iter->size) {
      size_t l = 0;
      size_t r = iter->size - 1;
      do {
	/* since l+r >= 0, we can (>> 1) instead (/ 2) */
	size_t i = (l + r) >> 1;
	const char *iname = iter->types[i]->name;
	if (iname) {
	  int compare = strcmp(name, iname);
	  if (compare == 0) {
	    return iter->types[i];
	  } else if (compare < 0) {
	    if (i) {
	      r = i - 1;
	    } else {
	      break;
	    }
	  } else if (compare > 0) {
	    l = i + 1;
	  }
	} else {
	  break; /* should never happen */
	}
      } while (l <= r);
    }
    iter = iter->next;
  } while (iter != end);
  return 0;
}

/*
  Search for a swig_type_info structure for either a mangled name or a human readable name.
  It first searches the mangled names of the types, which is a O(log #types)
  If a type is not found it then searches the human readable names, which is O(#types).

  We start searching at module start, and finish searching when start == end.
  Note: if start == end at the beginning of the function, we go all the way around
  the circular list.
*/
SWIGRUNTIME swig_type_info *
SWIG_TypeQueryModule(swig_module_info *start,
                     swig_module_info *end,
		     const char *name) {
  /* STEP 1: Search the name field using binary search */
  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
  if (ret) {
    return ret;
  } else {
    /* STEP 2: If the type hasn't been found, do a complete search
       of the str field (the human readable name) */
    swig_module_info *iter = start;
    do {
      size_t i = 0;
      for (; i < iter->size; ++i) {
	if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
	  return iter->types[i];
      }
      iter = iter->next;
    } while (iter != end);
  }

  /* neither found a match */
  return 0;
}

/*
   Pack binary data into a string
*/
SWIGRUNTIME char *
SWIG_PackData(char *c, void *ptr, size_t sz) {
  static const char hex[17] = "0123456789abcdef";
  const unsigned char *u = (unsigned char *) ptr;
  const unsigned char *eu =  u + sz;
  for (; u != eu; ++u) {
    unsigned char uu = *u;
    *(c++) = hex[(uu & 0xf0) >> 4];
    *(c++) = hex[uu & 0xf];
  }
  return c;
}

/*
   Unpack binary data from a string
*/
SWIGRUNTIME const char *
SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
  unsigned char *u = (unsigned char *) ptr;
  const unsigned char *eu = u + sz;
  for (; u != eu; ++u) {
    char d = *(c++);
    unsigned char uu;
    if ((d >= '0') && (d <= '9'))
      uu = (unsigned char)((d - '0') << 4);
    else if ((d >= 'a') && (d <= 'f'))
      uu = (unsigned char)((d - ('a'-10)) << 4);
    else
      return (char *) 0;
    d = *(c++);
    if ((d >= '0') && (d <= '9'))
      uu |= (unsigned char)(d - '0');
    else if ((d >= 'a') && (d <= 'f'))
      uu |= (unsigned char)(d - ('a'-10));
    else
      return (char *) 0;
    *u = uu;
  }
  return c;
}

/*
   Pack 'void *' into a string buffer.
*/
SWIGRUNTIME char *
SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
  char *r = buff;
  if ((2*sizeof(void *) + 2) > bsz) return 0;
  *(r++) = '_';
  r = SWIG_PackData(r,&ptr,sizeof(void *));
  if (strlen(name) + 1 > (bsz - (size_t)(r - buff))) return 0;
  strcpy(r,name);
  return buff;
}

SWIGRUNTIME const char *
SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
  if (*c != '_') {
    if (strcmp(c,"NULL") == 0) {
      *ptr = (void *) 0;
      return name;
    } else {
      return 0;
    }
  }
  return SWIG_UnpackData(++c,ptr,sizeof(void *));
}

SWIGRUNTIME char *
SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
  char *r = buff;
  size_t lname = (name ? strlen(name) : 0);
  if ((2*sz + 2 + lname) > bsz) return 0;
  *(r++) = '_';
  r = SWIG_PackData(r,ptr,sz);
  if (lname) {
    strncpy(r,name,lname+1);
  } else {
    *r = 0;
  }
  return buff;
}

SWIGRUNTIME const char *
SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
  if (*c != '_') {
    if (strcmp(c,"NULL") == 0) {
      memset(ptr,0,sz);
      return name;
    } else {
      return 0;
    }
  }
  return SWIG_UnpackData(++c,ptr,sz);
}

#ifdef __cplusplus
}
#endif

/* SWIG Errors applicable to all language modules, values are reserved from -1 to -99 */
#define  SWIG_UnknownError    	   -1
#define  SWIG_IOError        	   -2
#define  SWIG_RuntimeError   	   -3
#define  SWIG_IndexError     	   -4
#define  SWIG_TypeError      	   -5
#define  SWIG_DivisionByZero 	   -6
#define  SWIG_OverflowError  	   -7
#define  SWIG_SyntaxError    	   -8
#define  SWIG_ValueError     	   -9
#define  SWIG_SystemError    	   -10
#define  SWIG_AttributeError 	   -11
#define  SWIG_MemoryError    	   -12
#define  SWIG_NullReferenceError   -13


#if !defined(SWIG_NO_HEAPTYPES)
#if !defined(SWIG_HEAPTYPES)
#define SWIG_HEAPTYPES
#endif
#endif

#if defined(SWIG_HEAPTYPES)
#if PY_VERSION_HEX < 0x030c0000
#include <structmember.h>
#define Py_READONLY READONLY
#define Py_T_PYSSIZET T_PYSSIZET
#endif
#endif

#include <stddef.h> /* For offsetof */


/* Wrapper around PyUnicode_AsUTF8AndSize - call Py_XDECREF on the returned pbytes when finished with the returned string */
SWIGINTERN const char *
SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes)
{
#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
  *pbytes = NULL;
  return PyUnicode_AsUTF8AndSize(str, psize);
#else
  const char *chars;
  *pbytes = PyUnicode_AsUTF8String(str);
  chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL;
  if (chars && psize)
    *psize = PyBytes_Size(*pbytes);
  return chars;
#endif
}

#define SWIG_RUNTIME_MODULE "swig_runtime_data" SWIG_RUNTIME_VERSION

/* SWIGPY_USE_CAPSULE is no longer used within SWIG itself, but some user interface files check for it. */
# define SWIGPY_USE_CAPSULE
#ifdef SWIGPYTHON_BUILTIN
# define SWIGPY_CAPSULE_ATTR_NAME "type_pointer_capsule_builtin" SWIG_TYPE_TABLE_NAME
#else
# define SWIGPY_CAPSULE_ATTR_NAME "type_pointer_capsule" SWIG_TYPE_TABLE_NAME
#endif
#define SWIGPY_CAPSULE_NAME SWIG_RUNTIME_MODULE "." SWIGPY_CAPSULE_ATTR_NAME

#if defined(Py_LIMITED_API)
# define PyTuple_GET_ITEM PyTuple_GetItem
/* Note that PyTuple_SetItem() has different semantics from PyTuple_SET_ITEM as it decref's the original tuple item, so in general they cannot be used
  interchangeably. However in SWIG-generated code PyTuple_SET_ITEM is only used with newly initialized tuples without any items and for them this does work. */
# define PyTuple_SET_ITEM PyTuple_SetItem
# define PyTuple_GET_SIZE PyTuple_Size
# define PyCFunction_GET_FLAGS PyCFunction_GetFlags
# define PyCFunction_GET_FUNCTION PyCFunction_GetFunction
# define PyCFunction_GET_SELF PyCFunction_GetSelf
# define PyList_GET_ITEM PyList_GetItem
# define PyList_SET_ITEM PyList_SetItem
# define PySliceObject PyObject
#endif

/* Increment and Decrement wrappers - for portability when using the stable abi and for performance otherwise */
#ifdef Py_LIMITED_API
# define SWIG_Py_INCREF Py_IncRef
# define SWIG_Py_XINCREF Py_IncRef
# define SWIG_Py_DECREF Py_DecRef
# define SWIG_Py_XDECREF Py_DecRef
#else
# define SWIG_Py_INCREF Py_INCREF
# define SWIG_Py_XINCREF Py_XINCREF
# define SWIG_Py_DECREF Py_DECREF
# define SWIG_Py_XDECREF Py_XDECREF
#endif

#if (PY_VERSION_HEX >= 0x030d00a6) && (!defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d00a6)
# define SWIG_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName
#else
SWIGINTERN PyObject *
SWIG_PyType_GetFullyQualifiedName(PyTypeObject *type) {
  PyObject *result = NULL;
  PyObject *qualname = PyObject_GetAttrString((PyObject *)type, "__qualname__");
  if (qualname) {
    PyObject *mod = PyObject_GetAttrString((PyObject *)type, "__module__");
    if (mod) {
      if (PyUnicode_Check(mod) && PyUnicode_CompareWithASCIIString(mod, "builtins") && PyUnicode_CompareWithASCIIString(mod, "__main__")) {
        result = PyUnicode_FromFormat("%U%c%U", mod, '.', qualname);
        SWIG_Py_DECREF(qualname);
      } else {
        result = qualname;
      }
      SWIG_Py_DECREF(mod);
    } else {
      result = qualname;
    }
  }

  return result;
}
#endif

/* gh-114329 added PyList_GetItemRef() to Python 3.13.0a4 */
#if (PY_VERSION_HEX >= 0x030d00a4) && (!defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d00a4)
# define SWIG_PyList_GetItemRef PyList_GetItemRef
#else
SWIGINTERN PyObject *
SWIG_PyList_GetItemRef(PyObject *op, Py_ssize_t index) {
  PyObject *item = PyList_GetItem(op, index);
  Py_XINCREF(item);
  return item;
}
#endif

/* gh-106004 added PyDict_GetItemRef() and PyDict_GetItemStringRef() to Python 3.13.0a1
   functions are renamed here for compatibility with abi3audit */
#if (PY_VERSION_HEX >= 0x030d00a1) && (!defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d00a1)
# define SWIG_PyDict_GetItemRef PyDict_GetItemRef
# define SWIG_PyDict_GetItemStringRef PyDict_GetItemStringRef
#else
SWIGINTERN int
SWIG_PyDict_GetItemRef(PyObject *mp, PyObject *key, PyObject **result) {
  PyObject *item = PyDict_GetItemWithError(mp, key);
  if (item != NULL) {
    *result = (PyObject *)(item);
    SWIG_Py_INCREF(*result);
    return 1;
  }
  if (!PyErr_Occurred()) {
    *result = NULL;
    return 0;
  }
  *result = NULL;
  return -1;
}

SWIGINTERN int
SWIG_PyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result) {
  int res;
  PyObject *key_obj = PyUnicode_FromString(key);
  if (key_obj == NULL) {
    *result = NULL;
    return -1;
  }
  res = SWIG_PyDict_GetItemRef(mp, key_obj, result);
  Py_DECREF(key_obj);
  return res;
}
#endif

/* -----------------------------------------------------------------------------
 * error manipulation
 * ----------------------------------------------------------------------------- */

SWIGRUNTIME PyObject*
SWIG_Python_ErrorType(int code) {
  PyObject* type = 0;
  switch(code) {
  case SWIG_MemoryError:
    type = PyExc_MemoryError;
    break;
  case SWIG_IOError:
    type = PyExc_IOError;
    break;
  case SWIG_RuntimeError:
    type = PyExc_RuntimeError;
    break;
  case SWIG_IndexError:
    type = PyExc_IndexError;
    break;
  case SWIG_TypeError:
    type = PyExc_TypeError;
    break;
  case SWIG_DivisionByZero:
    type = PyExc_ZeroDivisionError;
    break;
  case SWIG_OverflowError:
    type = PyExc_OverflowError;
    break;
  case SWIG_SyntaxError:
    type = PyExc_SyntaxError;
    break;
  case SWIG_ValueError:
    type = PyExc_ValueError;
    break;
  case SWIG_SystemError:
    type = PyExc_SystemError;
    break;
  case SWIG_AttributeError:
    type = PyExc_AttributeError;
    break;
  case SWIG_NullReferenceError:
    type = PyExc_TypeError;
    break;
  default:
    type = PyExc_RuntimeError;
  }
  return type;
}


SWIGRUNTIME void
SWIG_Python_AddErrorMsg(const char* mesg)
{
  PyObject *type = 0;
  PyObject *value = 0;
  PyObject *traceback = 0;

  if (PyErr_Occurred())
    PyErr_Fetch(&type, &value, &traceback);
  if (value) {
    PyObject *old_str = PyObject_Str(value);
    PyObject *bytes = NULL;
    const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes);
    PyErr_Clear();
    SWIG_Py_XINCREF(type);
    if (tmp)
      PyErr_Format(type, "%s %s", tmp, mesg);
    else
      PyErr_Format(type, "%s", mesg);
    SWIG_Py_XDECREF(bytes);
    SWIG_Py_DECREF(old_str);
    SWIG_Py_DECREF(value);
  } else {
    PyErr_SetString(PyExc_RuntimeError, mesg);
  }
}

SWIGRUNTIME int
SWIG_Python_TypeErrorOccurred(PyObject *obj)
{
  PyObject *error;
  if (obj)
    return 0;
  error = PyErr_Occurred();
  return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError);
}

SWIGRUNTIME void
SWIG_Python_RaiseOrModifyTypeError(const char *message)
{
  if (SWIG_Python_TypeErrorOccurred(NULL)) {
    /* Use existing TypeError to preserve stacktrace and enhance with given message */
    PyObject *newvalue;
    PyObject *type = NULL, *value = NULL, *traceback = NULL;
    PyErr_Fetch(&type, &value, &traceback);
    newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message);
    if (newvalue) {
      SWIG_Py_XDECREF(value);
      PyErr_Restore(type, newvalue, traceback);
    } else {
      PyErr_Restore(type, value, traceback);
    }
  } else {
    /* Raise TypeError using given message */
    PyErr_SetString(PyExc_TypeError, message);
  }
}

#if defined(SWIG_PYTHON_NO_THREADS)
#  if defined(SWIG_PYTHON_THREADS)
#    undef SWIG_PYTHON_THREADS
#  endif
#endif
#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */
#  if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL)
#    define SWIG_PYTHON_USE_GIL
#  endif
#  if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */
#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)
#      if PY_VERSION_HEX < 0x03070000
#        define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads()
#      else
#        define SWIG_PYTHON_INITIALIZE_THREADS
#      endif
#    endif
#    ifdef __cplusplus /* C++ code */
       class SWIG_Python_Thread_Block {
         bool status;
         PyGILState_STATE state;
       public:
         void end() { if (status) { PyGILState_Release(state); status = false;} }
         SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {}
         ~SWIG_Python_Thread_Block() { end(); }
       };
       class SWIG_Python_Thread_Allow {
         bool status;
         PyThreadState *save;
       public:
         void end() { if (status) { status = false; PyEval_RestoreThread(save); }}
         SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {}
         ~SWIG_Python_Thread_Allow() { end(); }
       };
#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   SWIG_Python_Thread_Block _swig_thread_block
#      define SWIG_PYTHON_THREAD_END_BLOCK     _swig_thread_block.end()
#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   SWIG_Python_Thread_Allow _swig_thread_allow
#      define SWIG_PYTHON_THREAD_END_ALLOW     _swig_thread_allow.end()
#    else /* C code */
#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   PyGILState_STATE _swig_thread_block = PyGILState_Ensure()
#      define SWIG_PYTHON_THREAD_END_BLOCK     PyGILState_Release(_swig_thread_block)
#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   PyThreadState *_swig_thread_allow = PyEval_SaveThread()
#      define SWIG_PYTHON_THREAD_END_ALLOW     PyEval_RestoreThread(_swig_thread_allow)
#    endif
#  else /* Old thread way, not implemented, user must provide it */
#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)
#      define SWIG_PYTHON_INITIALIZE_THREADS
#    endif
#    if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK)
#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK
#    endif
#    if !defined(SWIG_PYTHON_THREAD_END_BLOCK)
#      define SWIG_PYTHON_THREAD_END_BLOCK
#    endif
#    if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW)
#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW
#    endif
#    if !defined(SWIG_PYTHON_THREAD_END_ALLOW)
#      define SWIG_PYTHON_THREAD_END_ALLOW
#    endif
#  endif
#else /* No thread support */
#  define SWIG_PYTHON_INITIALIZE_THREADS
#  define SWIG_PYTHON_THREAD_BEGIN_BLOCK
#  define SWIG_PYTHON_THREAD_END_BLOCK
#  define SWIG_PYTHON_THREAD_BEGIN_ALLOW
#  define SWIG_PYTHON_THREAD_END_ALLOW
#endif

/* -----------------------------------------------------------------------------
 * Python API portion that goes into the runtime
 * ----------------------------------------------------------------------------- */

#ifdef __cplusplus
extern "C" {
#endif

/* -----------------------------------------------------------------------------
 * Constant declarations
 * ----------------------------------------------------------------------------- */

/* Constant Types */
#define SWIG_PY_POINTER 4
#define SWIG_PY_BINARY  5

/* Constant information structure */
typedef struct swig_const_info {
  int type;
  const char *name;
  long lvalue;
  double dvalue;
  void   *pvalue;
  swig_type_info **ptype;
} swig_const_info;

#ifdef __cplusplus
}
#endif


/* -----------------------------------------------------------------------------
 * pyrun.swg
 *
 * This file contains the runtime support for Python modules
 * and includes code for managing global variables and pointer
 * type checking.
 *
 * ----------------------------------------------------------------------------- */

#if PY_VERSION_HEX < 0x03050000
# error "This version of SWIG only supports Python >= 3.5"
#endif

/* Common SWIG API */

/* for raw pointers */
#define SWIG_Python_ConvertPtr(obj, pptr, type, flags)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Python_ConvertPtr(obj, pptr, type, flags)
#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own)

#ifdef SWIGPYTHON_BUILTIN
#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(self, ptr, type, flags)
#else
#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(NULL, ptr, type, flags)
#endif

#define SWIG_InternalNewPointerObj(ptr, type, flags)	SWIG_Python_NewPointerObj(NULL, ptr, type, flags)

#define SWIG_CheckImplicit(ty)                          SWIG_Python_CheckImplicit(ty) 
#define SWIG_AcquirePtr(ptr, src)                       SWIG_Python_AcquirePtr(ptr, src)
#define swig_owntype                                    int

/* for raw packed data */
#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)

/* for class or struct pointers */
#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)
#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)

/* for C or C++ function pointers */
#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Python_ConvertFunctionPtr(obj, pptr, type)
#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Python_NewPointerObj(NULL, ptr, type, 0)

/* for C++ member pointers, ie, member methods */
#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)


/* Runtime API */

#define SWIG_GetModule(clientdata)                      SWIG_Python_GetModule(clientdata)
#define SWIG_SetModule(clientdata, pointer)             SWIG_Python_SetModule(pointer)
#define SWIG_NewClientData(obj)                         SwigPyClientData_New(obj)

#define SWIG_SetErrorObj                                SWIG_Python_SetErrorObj                            
#define SWIG_SetErrorMsg                        	SWIG_Python_SetErrorMsg				   
#define SWIG_ErrorType(code)                    	SWIG_Python_ErrorType(code)                        
#define SWIG_Error(code, msg)            		SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) 
#define SWIG_fail                        		goto fail					   

/* Runtime API implementation */

/* Error manipulation */

SWIGINTERN void 
SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) {
  SWIG_PYTHON_THREAD_BEGIN_BLOCK; 
  PyErr_SetObject(errtype, obj);
  SWIG_Py_DECREF(obj);
  SWIG_PYTHON_THREAD_END_BLOCK;
}

SWIGINTERN void 
SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) {
  SWIG_PYTHON_THREAD_BEGIN_BLOCK;
  PyErr_SetString(errtype, msg);
  SWIG_PYTHON_THREAD_END_BLOCK;
}

#define SWIG_Python_Raise(obj, type, desc)  SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj)

/* Set a constant value */

#if defined(SWIGPYTHON_BUILTIN)

SWIGINTERN void
SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) {
  PyObject *s = PyUnicode_InternFromString(key);
  PyList_Append(seq, s);
  SWIG_Py_DECREF(s);
}

SWIGINTERN void
SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) {   
  PyDict_SetItemString(d, name, obj);
  SWIG_Py_DECREF(obj);
  if (public_interface)
    SwigPyBuiltin_AddPublicSymbol(public_interface, name);
}

#else

SWIGINTERN void
SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) {   
  PyDict_SetItemString(d, name, obj);
  SWIG_Py_DECREF(obj);
}

#endif

/* SWIG runtime data Python module */
static PyObject *Swig_runtime_data_module_global = NULL;

/* Create/obtain the single swig_runtime_data module which is used across different SWIG generated modules */
SWIGINTERN PyObject *
SWIG_runtime_data_module(void) {
  if (!Swig_runtime_data_module_global) {
#if (PY_VERSION_HEX >= 0x030d0000) && (!defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000)
    /* free-threading note: the GIL is always enabled when this function is first called
       by SWIG_init, so there's no risk of race conditions */
    Swig_runtime_data_module_global = PyImport_AddModuleRef(SWIG_RUNTIME_MODULE);
#else
    Swig_runtime_data_module_global = PyImport_AddModule(SWIG_RUNTIME_MODULE);
    SWIG_Py_XINCREF(Swig_runtime_data_module_global);
#endif
  }
  assert(Swig_runtime_data_module_global);
  return Swig_runtime_data_module_global;
}

/* Append a value to the result obj */
SWIGINTERN PyObject*
SWIG_Python_AppendOutput(PyObject* result, PyObject* obj, int is_void) {
  if (!result) {
    result = obj;
  } else if (result == Py_None && is_void) {
    SWIG_Py_DECREF(result);
    result = obj;
  } else {
    if (!PyList_Check(result)) {
      PyObject *o2 = result;
      result = PyList_New(1);
      if (result) {
        PyList_SET_ITEM(result, 0, o2);
      } else {
        SWIG_Py_DECREF(obj);
        return o2;
      }
    }
    PyList_Append(result,obj);
    SWIG_Py_DECREF(obj);
  }
  return result;
}

/* Unpack the argument tuple */

SWIGINTERN Py_ssize_t
SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs)
{
  if (!args) {
    if (!min && !max) {
      return 1;
    } else {
      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", 
		   name, (min == max ? "" : "at least "), (int)min);
      return 0;
    }
  }  
  if (!PyTuple_Check(args)) {
    if (min <= 1 && max >= 1) {
      Py_ssize_t i;
      objs[0] = args;
      for (i = 1; i < max; ++i) {
	objs[i] = 0;
      }
      return 2;
    }
    PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple");
    return 0;
  } else {
    Py_ssize_t l = PyTuple_GET_SIZE(args);
    if (l < min) {
      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
		   name, (min == max ? "" : "at least "), (int)min, (int)l);
      return 0;
    } else if (l > max) {
      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
		   name, (min == max ? "" : "at most "), (int)max, (int)l);
      return 0;
    } else {
      Py_ssize_t i;
      for (i = 0; i < l; ++i) {
	objs[i] = PyTuple_GET_ITEM(args, i);
      }
      for (; l < max; ++l) {
	objs[l] = 0;
      }
      return i + 1;
    }    
  }
}

SWIGINTERN int
SWIG_Python_CheckNoKeywords(PyObject *kwargs, const char *name) {
  int no_kwargs = 1;
  if (kwargs) {
    assert(PyDict_Check(kwargs));
    if (PyDict_Size(kwargs) > 0) {
      PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name);
      no_kwargs = 0;
    }
  }
  return no_kwargs;
}

/* A functor is a function object with one single object argument */
#define SWIG_Python_CallFunctor(functor, obj)	        PyObject_CallFunctionObjArgs(functor, obj, NULL);

/*
  Helper for static pointer initialization for both C and C++ code, for example
  static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...);
*/
#ifdef __cplusplus
#define SWIG_STATIC_POINTER(var)  var
#else
#define SWIG_STATIC_POINTER(var)  var = 0; if (!var) var
#endif

#ifdef __cplusplus
extern "C" {
#endif

/* Python-specific SWIG API */
#define SWIG_newvarlink()                             SWIG_Python_newvarlink()
#define SWIG_addvarlink(p, name, get_attr, set_attr)  SWIG_Python_addvarlink(p, name, get_attr, set_attr)
#define SWIG_InstallConstants(d, constants)           SWIG_Python_InstallConstants(d, constants)
 
/* -----------------------------------------------------------------------------
 * global variable support code.
 * ----------------------------------------------------------------------------- */
 
typedef struct swig_globalvar {   
  char       *name;                  /* Name of global variable */
  PyObject *(*get_attr)(void);       /* Return the current value */
  int       (*set_attr)(PyObject *); /* Set the value */
  struct swig_globalvar *next;
} swig_globalvar;

typedef struct swig_varlinkobject {
  PyObject_HEAD
  swig_globalvar *vars;
} swig_varlinkobject;

SWIGINTERN PyObject *
SwigVarLink_repr(PyObject *SWIGUNUSEDPARM(v)) {
  return PyUnicode_InternFromString("<Swig global variables>");
}

SWIGINTERN PyObject *
SwigVarLink_str(PyObject *o) {
  swig_varlinkobject *v = (swig_varlinkobject *) o;
  PyObject *str = PyUnicode_InternFromString("(");
  PyObject *tail;
  PyObject *joined;
  swig_globalvar *var;
  for (var = v->vars; var; var=var->next) {
    tail = PyUnicode_FromString(var->name);
    joined = PyUnicode_Concat(str, tail);
    SWIG_Py_DECREF(str);
    SWIG_Py_DECREF(tail);
    str = joined;
    if (var->next) {
        tail = PyUnicode_InternFromString(", ");
        joined = PyUnicode_Concat(str, tail);
        SWIG_Py_DECREF(str);
        SWIG_Py_DECREF(tail);
        str = joined;
    }
  }
  tail = PyUnicode_InternFromString(")");
  joined = PyUnicode_Concat(str, tail);
  SWIG_Py_DECREF(str);
  SWIG_Py_DECREF(tail);
  str = joined;
  return str;
}

SWIGINTERN void
SwigVarLink_dealloc(PyObject *o) {
  swig_varlinkobject *v = (swig_varlinkobject *) o;
  swig_globalvar *var = v->vars;
  while (var) {
    swig_globalvar *n = var->next;
    free(var->name);
    free(var);
    var = n;
  }
}

SWIGINTERN PyObject *
SwigVarLink_getattr(PyObject *o, char *n) {
  swig_varlinkobject *v = (swig_varlinkobject *) o;
  PyObject *res = NULL;
  swig_globalvar *var = v->vars;
  while (var) {
    if (strcmp(var->name,n) == 0) {
      res = (*var->get_attr)();
      break;
    }
    var = var->next;
  }
  if (res == NULL && !PyErr_Occurred()) {
    PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n);
  }
  return res;
}

SWIGINTERN int
SwigVarLink_setattr(PyObject *o, char *n, PyObject *p) {
  swig_varlinkobject *v = (swig_varlinkobject *) o;
  int res = 1;
  swig_globalvar *var = v->vars;
  while (var) {
    if (strcmp(var->name,n) == 0) {
      res = (*var->set_attr)(p);
      break;
    }
    var = var->next;
  }
  if (res == 1 && !PyErr_Occurred()) {
    PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n);
  }
  return res;
}

SWIGINTERN PyTypeObject*
SwigVarLink_TypeOnce(void) {
  static char SwigVarLink_doc[] = "Swig variable link object";
#ifndef SWIG_HEAPTYPES
  static PyTypeObject varlink_type;
  static int type_init = 0;
  if (!type_init) {
    const PyTypeObject tmp = {
      PyVarObject_HEAD_INIT(NULL, 0)
      SWIG_RUNTIME_MODULE ".SwigVarLink", /* tp_name */
      sizeof(swig_varlinkobject),         /* tp_basicsize */
      0,                                  /* tp_itemsize */
      (destructor) SwigVarLink_dealloc,   /* tp_dealloc */
#if PY_VERSION_HEX < 0x030800b4
      (printfunc)0,                       /* tp_print */
#else
      (Py_ssize_t)0,                      /* tp_vectorcall_offset */
#endif
      (getattrfunc) SwigVarLink_getattr,  /* tp_getattr */
      (setattrfunc) SwigVarLink_setattr,  /* tp_setattr */
      0,                                  /* tp_compare */
      (reprfunc) SwigVarLink_repr,        /* tp_repr */
      0,                                  /* tp_as_number */
      0,                                  /* tp_as_sequence */
      0,                                  /* tp_as_mapping */
      0,                                  /* tp_hash */
      0,                                  /* tp_call */
      (reprfunc) SwigVarLink_str,         /* tp_str */
      0,                                  /* tp_getattro */
      0,                                  /* tp_setattro */
      0,                                  /* tp_as_buffer */
      0,                                  /* tp_flags */
      SwigVarLink_doc,                    /* tp_doc */
      0,                                  /* tp_traverse */
      0,                                  /* tp_clear */
      0,                                  /* tp_richcompare */
      0,                                  /* tp_weaklistoffset */
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
      0,                                  /* tp_del */
      0,                                  /* tp_version_tag */
      0,                                  /* tp_finalize */
#if PY_VERSION_HEX >= 0x03080000
      0,                                  /* tp_vectorcall */
#endif
#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000)
      0,                                  /* tp_print */
#endif
#if PY_VERSION_HEX >= 0x030c0000
      0,                                  /* tp_watched */
#endif
#if PY_VERSION_HEX >= 0x030d00a4
      0,                                  /* tp_versions_used */
#endif
#ifdef COUNT_ALLOCS
      0,                                  /* tp_allocs */
      0,                                  /* tp_frees */
      0,                                  /* tp_maxalloc */
      0,                                  /* tp_prev */
      0                                   /* tp_next */
#endif
    };
    PyObject *runtime_data_module = SWIG_runtime_data_module();
    varlink_type = tmp;
    type_init = 1;
    if (PyType_Ready(&varlink_type) < 0)
      return NULL;
    if (PyModule_AddObject(runtime_data_module, "SwigVarLink", (PyObject *)&varlink_type) == 0)
      SWIG_Py_INCREF((PyObject *)&varlink_type);
  }
  return &varlink_type;
#else
  PyType_Slot slots[] = {
    { Py_tp_dealloc, (void *)SwigVarLink_dealloc },
    { Py_tp_repr, (void *)SwigVarLink_repr },
    { Py_tp_getattr, (void *)SwigVarLink_getattr },
    { Py_tp_setattr, (void *)SwigVarLink_setattr },
    { Py_tp_str, (void *)SwigVarLink_str },
    { Py_tp_doc, (void *)SwigVarLink_doc },
    { 0, NULL }
  };
  PyType_Spec spec = {
    SWIG_RUNTIME_MODULE ".SwigVarLink",
    sizeof(swig_varlinkobject),
    0,
    Py_TPFLAGS_DEFAULT,
    slots
  };
  PyObject *pytype = PyType_FromSpec(&spec);
  PyObject *runtime_data_module = SWIG_runtime_data_module();
  if (pytype && PyModule_AddObject(runtime_data_module, "SwigVarLink", pytype) == 0)
    SWIG_Py_INCREF(pytype);
  return (PyTypeObject *)pytype;
#endif
}

SWIGRUNTIME PyTypeObject*
SwigVarLink_Type(void) {
  static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigVarLink_TypeOnce();
  return type;
}

/* Create a variable linking object for use later */
SWIGINTERN PyObject *
SWIG_Python_newvarlink(void) {
  swig_varlinkobject *result = PyObject_New(swig_varlinkobject, SwigVarLink_Type());
  if (result) {
    result->vars = 0;
  }
  return ((PyObject*) result);
}

SWIGINTERN void 
SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
  swig_varlinkobject *v = (swig_varlinkobject *) p;
  swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
  if (gv) {
    size_t size = strlen(name)+1;
    gv->name = (char *)malloc(size);
    if (gv->name) {
      memcpy(gv->name, name, size);
      gv->get_attr = get_attr;
      gv->set_attr = set_attr;
      gv->next = v->vars;
    }
  }
  v->vars = gv;
}


static PyObject *Swig_Globals_global = NULL;
  
SWIGINTERN PyObject *
SWIG_globals(void) {
  if (Swig_Globals_global == NULL) {
    Swig_Globals_global = SWIG_newvarlink();
  }
  return Swig_Globals_global;
}

#ifdef __cplusplus
}
#endif

/* -----------------------------------------------------------------------------
 * Pointer declarations
 * ----------------------------------------------------------------------------- */

/* Flags for new pointer objects */
#define SWIG_POINTER_NOSHADOW       (SWIG_POINTER_OWN      << 1)
#define SWIG_POINTER_NEW            (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN)

#define SWIG_POINTER_IMPLICIT_CONV  (SWIG_POINTER_DISOWN   << 1)

#define SWIG_BUILTIN_TP_INIT	    (SWIG_POINTER_OWN << 2)
#define SWIG_BUILTIN_INIT	    (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN)

#ifdef __cplusplus
extern "C" {
#endif

/* The python void return value */

SWIGRUNTIMEINLINE PyObject * 
SWIG_Py_Void(void)
{
  PyObject *none = Py_None;
  SWIG_Py_INCREF(none);
  return none;
}

/* SwigPyClientData */

typedef struct {
  PyObject *klass;
  PyObject *newraw;
  PyObject *newargs;
  PyObject *destroy;
  int delargs;
  int implicitconv;
  PyTypeObject *pytype;
} SwigPyClientData;

SWIGRUNTIMEINLINE int 
SWIG_Python_CheckImplicit(swig_type_info *ty)
{
  SwigPyClientData *data = (SwigPyClientData *)ty->clientdata;
  int fail = data ? data->implicitconv : 0;
  if (fail)
    PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors.");
  return fail;
}

SWIGRUNTIMEINLINE PyObject *
SWIG_Python_ExceptionType(swig_type_info *desc) {
  SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0;
  PyObject *klass = data ? data->klass : 0;
  return (klass ? klass : PyExc_RuntimeError);
}


SWIGRUNTIME SwigPyClientData * 
SwigPyClientData_New(PyObject* obj)
{
  if (!obj) {
    return 0;
  } else {
    SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData));
    /* the klass element */
    data->klass = obj;
    SWIG_Py_INCREF(data->klass);
    /* the newraw method and newargs arguments used to create a new raw instance */
    if (PyObject_IsInstance(obj, (PyObject *)&PyType_Type)) {
      data->newraw = 0;
      SWIG_Py_INCREF(obj);
      data->newargs = obj;
    } else {
      data->newraw = PyObject_GetAttrString(data->klass, "__new__");
      if (data->newraw) {
        data->newargs = PyTuple_New(1);
        if (data->newargs) {
          SWIG_Py_INCREF(obj);
          PyTuple_SET_ITEM(data->newargs, 0, obj);
        } else {
          SWIG_Py_DECREF(data->newraw);
          SWIG_Py_DECREF(data->klass);
          free(data);
          return 0;
        }
      } else {
        SWIG_Py_INCREF(obj);
        data->newargs = obj;
      }
    }
    /* the destroy method, aka as the C++ delete method */
    data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__");
    if (PyErr_Occurred()) {
      PyErr_Clear();
      data->destroy = 0;
    }
    if (data->destroy) {
      data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O);
    } else {
      data->delargs = 0;
    }
    data->implicitconv = 0;
    data->pytype = 0;
    return data;
  }
}

SWIGRUNTIME void 
SwigPyClientData_Del(SwigPyClientData *data)
{
  SWIG_Py_XDECREF(data->klass);
  SWIG_Py_XDECREF(data->newraw);
  SWIG_Py_XDECREF(data->newargs);
  SWIG_Py_XDECREF(data->destroy);
  free(data);
}

/* =============== SwigPyObject =====================*/

typedef struct {
  PyObject_HEAD
  void *ptr;
  swig_type_info *ty;
  int own;
  PyObject *next;
  PyObject *swigdict;
  PyObject *weakreflist;
} SwigPyObject;


#ifdef SWIGPYTHON_BUILTIN

SWIGRUNTIME PyObject *
SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args))
{
  SwigPyObject *sobj = (SwigPyObject *)v;

  if (!sobj->swigdict)
    sobj->swigdict = PyDict_New();

  SWIG_Py_XINCREF(sobj->swigdict);
  return sobj->swigdict;
}

#endif

SWIGRUNTIME PyObject *
SwigPyObject_long(SwigPyObject *v)
{
  return PyLong_FromVoidPtr(v->ptr);
}

SWIGRUNTIME PyObject *
SwigPyObject_format(const char* fmt, SwigPyObject *v)
{
  PyObject *res = NULL;
  PyObject *args = PyTuple_New(1);
  if (args) {
    PyObject *val = SwigPyObject_long(v);
    if (val) {
      PyObject *ofmt;
      PyTuple_SET_ITEM(args, 0, val);
      ofmt = PyUnicode_FromString(fmt);
      if (ofmt) {
        res = PyUnicode_Format(ofmt,args);
        SWIG_Py_DECREF(ofmt);
      }
    }
    SWIG_Py_DECREF(args);
  }
  return res;
}

SWIGRUNTIME PyObject *
SwigPyObject_oct(SwigPyObject *v)
{
  return SwigPyObject_format("%o",v);
}

SWIGRUNTIME PyObject *
SwigPyObject_hex(SwigPyObject *v)
{
  return SwigPyObject_format("%x",v);
}

SWIGRUNTIME PyObject *
SwigPyObject_repr(SwigPyObject *v)
{
  const char *name = SWIG_TypePrettyName(v->ty);
  PyObject *repr = PyUnicode_FromFormat("<Swig Object of type '%s' at %p>", (name ? name : "unknown"), (void *)v);
  if (repr && v->next) {
    PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next);
    if (nrep) {
      PyObject *joined = PyUnicode_Concat(repr, nrep);
      SWIG_Py_DECREF(repr);
      SWIG_Py_DECREF(nrep);
      repr = joined;
    } else {
      SWIG_Py_DECREF(repr);
      repr = NULL;
    }
  }
  return repr;
}

/* We need a version taking two PyObject* parameters so it's a valid
 * PyCFunction to use in SwigPyObject_methods[]. */
SWIGRUNTIME PyObject *
SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args))
{
  return SwigPyObject_repr((SwigPyObject*)v);
}

SWIGRUNTIME int
SwigPyObject_compare(PyObject *v, PyObject *w)
{
  /* tp_compare is only called when both objects have the same type, so
   * the casts are guaranteed to be ok. */
  void *i = ((SwigPyObject *)v)->ptr;
  void *j = ((SwigPyObject *)w)->ptr;
  return (i < j) ? -1 : ((i > j) ? 1 : 0);
}

SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *);

/* Rich comparison support */
SWIGRUNTIME PyObject*
SwigPyObject_richcompare(PyObject *v, PyObject *w, int op)
{
  PyObject* res = NULL;
  if (!PyErr_Occurred()) {
    /* Per https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_richcompare
     * the first argument is guaranteed to be an instance of SwigPyObject, but the
     * second is not, so we typecheck that one. */
    if ((op != Py_EQ && op != Py_NE) || !SwigPyObject_Check(w)) {
      SWIG_Py_INCREF(Py_NotImplemented);
      return Py_NotImplemented;
    }
    res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0);
  }
  return res;
}


SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void);

#ifdef SWIGPYTHON_BUILTIN
static swig_type_info *SwigPyObject_stype = 0;
SWIGRUNTIME PyTypeObject*
SwigPyObject_Type(void) {
    SwigPyClientData *cd;
    assert(SwigPyObject_stype);
    cd = (SwigPyClientData*) SwigPyObject_stype->clientdata;
    assert(cd);
    assert(cd->pytype);
    return cd->pytype;
}
#else
SWIGRUNTIME PyTypeObject*
SwigPyObject_Type(void) {
  static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce();
  return type;
}
#endif

SWIGRUNTIMEINLINE int
SwigPyObject_Check(PyObject *op) {
  PyTypeObject *target_tp = SwigPyObject_Type();
  PyTypeObject *op_type = Py_TYPE(op);
#ifdef SWIGPYTHON_BUILTIN
  /* Only builtin types have SwigPyObject as a base type */
  return PyType_IsSubtype(op_type, target_tp);
#else
  /* Check for an exact match to SwigPyObject */
  if (op_type == target_tp) {
    return 1;
  } else {
    /* Fallback for multiple modules */
    int cmp;
    PyObject *tpname = SWIG_PyType_GetFullyQualifiedName(op_type);
    if (!tpname)
      return 0;
    cmp = PyUnicode_CompareWithASCIIString(tpname, SWIG_RUNTIME_MODULE ".SwigPyObject");
    SWIG_Py_DECREF(tpname);
    return cmp == 0;
  }
#endif
}

SWIGRUNTIME PyObject *
SwigPyObject_New(void *ptr, swig_type_info *ty, int own);

static PyObject* Swig_Capsule_global = NULL;

SWIGRUNTIME void
SwigPyObject_dealloc(PyObject *v)
{
  SwigPyObject *sobj = (SwigPyObject *) v;
  PyObject *next = sobj->next;
  if (sobj->own == SWIG_POINTER_OWN) {
    swig_type_info *ty = sobj->ty;
    SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0;
    PyObject *destroy = data ? data->destroy : 0;
    if (destroy) {
      /* destroy is always a VARARGS method */
      PyObject *res;

      /* PyObject_CallFunction() has the potential to silently drop
         the active exception.  In cases of unnamed temporary
         variable or where we just finished iterating over a generator
         StopIteration will be active right now, and this needs to
         remain true upon return from SwigPyObject_dealloc.  So save
         and restore. */
      
      PyObject *type = NULL, *value = NULL, *traceback = NULL;
      PyErr_Fetch(&type, &value, &traceback);

      if (data->delargs) {
        /* we need to create a temporary object to carry the destroy operation */
        PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0);
        if (tmp) {
          res = SWIG_Python_CallFunctor(destroy, tmp);
        } else {
          res = 0;
        }
        SWIG_Py_XDECREF(tmp);
      } else {
        PyCFunction meth = PyCFunction_GET_FUNCTION(destroy);
        PyObject *mself = PyCFunction_GET_SELF(destroy);
        res = ((*meth)(mself, v));
      }
      if (!res)
        PyErr_WriteUnraisable(destroy);

      PyErr_Restore(type, value, traceback);

      SWIG_Py_XDECREF(res);
    } 
#if !defined(SWIG_PYTHON_SILENT_MEMLEAK)
    else {
      const char *name = SWIG_TypePrettyName(ty);
      printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown"));
    }
#endif
    SWIG_Py_XDECREF(Swig_Capsule_global);
  }
  SWIG_Py_XDECREF(next);
  SWIG_Py_XDECREF(sobj->swigdict);
  PyObject_Free(v);
}

SWIGRUNTIME PyObject* 
SwigPyObject_append(PyObject* v, PyObject* next)
{
  SwigPyObject *sobj = (SwigPyObject *) v;
  if (!SwigPyObject_Check(next)) {
    PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject");
    return NULL;
  }
  ((SwigPyObject *)next)->next = sobj->next;
  sobj->next = next;
  SWIG_Py_INCREF(next);
  return SWIG_Py_Void();
}

SWIGRUNTIME PyObject* 
SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
{
  SwigPyObject *sobj = (SwigPyObject *) v;
  if (sobj->next) {    
    SWIG_Py_INCREF(sobj->next);
    return sobj->next;
  } else {
    return SWIG_Py_Void();
  }
}

SWIGINTERN PyObject*
SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
{
  SwigPyObject *sobj = (SwigPyObject *)v;
  sobj->own = 0;
  return SWIG_Py_Void();
}

SWIGINTERN PyObject*
SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
{
  SwigPyObject *sobj = (SwigPyObject *)v;
  sobj->own = SWIG_POINTER_OWN;
  return SWIG_Py_Void();
}

SWIGINTERN PyObject*
SwigPyObject_own(PyObject *v, PyObject *args)
{
  PyObject *val = 0;
  if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) {
    return NULL;
  } else {
    SwigPyObject *sobj = (SwigPyObject *)v;
    PyObject *obj = PyBool_FromLong(sobj->own);
    if (val) {
      if (PyObject_IsTrue(val)) {
        SWIG_Py_DECREF(SwigPyObject_acquire(v,args));
      } else {
        SWIG_Py_DECREF(SwigPyObject_disown(v,args));
      }
    } 
    return obj;
  }
}

static PyMethodDef
SwigPyObject_methods[] = {
  {"disown",  SwigPyObject_disown,  METH_NOARGS,  "releases ownership of the pointer"},
  {"acquire", SwigPyObject_acquire, METH_NOARGS,  "acquires ownership of the pointer"},
  {"own",     SwigPyObject_own,     METH_VARARGS, "returns/sets ownership of the pointer"},
  {"append",  SwigPyObject_append,  METH_O,       "appends another 'this' object"},
  {"next",    SwigPyObject_next,    METH_NOARGS,  "returns the next 'this' object"},
  {"__repr__",SwigPyObject_repr2,   METH_NOARGS,  "returns object representation"},
  {0, 0, 0, 0}  
};

SWIGRUNTIME PyTypeObject*
SwigPyObject_TypeOnce(void) {
  static char SwigPyObject_doc[] = "Swig object holding a C/C++ pointer";
#ifndef SWIG_HEAPTYPES
  static PyNumberMethods SwigPyObject_as_number = {
    (binaryfunc)0, /*nb_add*/
    (binaryfunc)0, /*nb_subtract*/
    (binaryfunc)0, /*nb_multiply*/
    (binaryfunc)0, /*nb_remainder*/
    (binaryfunc)0, /*nb_divmod*/
    (ternaryfunc)0,/*nb_power*/
    (unaryfunc)0,  /*nb_negative*/
    (unaryfunc)0,  /*nb_positive*/
    (unaryfunc)0,  /*nb_absolute*/
    (inquiry)0,    /*nb_bool*/
    0,		   /*nb_invert*/
    0,		   /*nb_lshift*/
    0,		   /*nb_rshift*/
    0,		   /*nb_and*/
    0,		   /*nb_xor*/
    0,		   /*nb_or*/
    (unaryfunc)SwigPyObject_long, /*nb_int*/
    0, /*nb_reserved*/
    (unaryfunc)0,                 /*nb_float*/
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_matrix_multiply */
  };

  static PyTypeObject swigpyobject_type;
  static int type_init = 0;
  if (!type_init) {
    const PyTypeObject tmp = {
      PyVarObject_HEAD_INIT(NULL, 0)
      SWIG_RUNTIME_MODULE ".SwigPyObject",  /* tp_name */
      sizeof(SwigPyObject),                 /* tp_basicsize */
      0,                                    /* tp_itemsize */
      (destructor)SwigPyObject_dealloc,     /* tp_dealloc */
#if PY_VERSION_HEX < 0x030800b4
      (printfunc)0,                         /* tp_print */
#else
      (Py_ssize_t)0,                        /* tp_vectorcall_offset */
#endif
      (getattrfunc)0,                       /* tp_getattr */
      (setattrfunc)0,                       /* tp_setattr */
      0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */
      (reprfunc)SwigPyObject_repr,          /* tp_repr */
      &SwigPyObject_as_number,              /* tp_as_number */
      0,                                    /* tp_as_sequence */
      0,                                    /* tp_as_mapping */
      (hashfunc)0,                          /* tp_hash */
      (ternaryfunc)0,                       /* tp_call */
      0,                                    /* tp_str */
      PyObject_GenericGetAttr,              /* tp_getattro */
      0,                                    /* tp_setattro */
      0,                                    /* tp_as_buffer */
      Py_TPFLAGS_DEFAULT,                   /* tp_flags */
      SwigPyObject_doc,                     /* tp_doc */
      0,                                    /* tp_traverse */
      0,                                    /* tp_clear */
      (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */
      offsetof(SwigPyObject, weakreflist),  /* tp_weaklistoffset */
      0,                                    /* tp_iter */
      0,                                    /* tp_iternext */
      SwigPyObject_methods,                 /* tp_methods */
      0,                                    /* tp_members */
      0,                                    /* tp_getset */
      0,                                    /* tp_base */
      0,                                    /* tp_dict */
      0,                                    /* tp_descr_get */
      0,                                    /* tp_descr_set */
      0,                                    /* tp_dictoffset */
      0,                                    /* tp_init */
      0,                                    /* tp_alloc */
      0,                                    /* tp_new */
      0,                                    /* tp_free */
      0,                                    /* tp_is_gc */
      0,                                    /* tp_bases */
      0,                                    /* tp_mro */
      0,                                    /* tp_cache */
      0,                                    /* tp_subclasses */
      0,                                    /* tp_weaklist */
      0,                                    /* tp_del */
      0,                                    /* tp_version_tag */
      0,                                    /* tp_finalize */
#if PY_VERSION_HEX >= 0x03080000
      0,                                    /* tp_vectorcall */
#endif
#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000)
      0,                                    /* tp_print */
#endif
#if PY_VERSION_HEX >= 0x030c0000
      0,                                    /* tp_watched */
#endif
#if PY_VERSION_HEX >= 0x030d00a4
      0,                                    /* tp_versions_used */
#endif
#ifdef COUNT_ALLOCS
      0,                                    /* tp_allocs */
      0,                                    /* tp_frees */
      0,                                    /* tp_maxalloc */
      0,                                    /* tp_prev */
      0                                     /* tp_next */
#endif
    };
    PyObject *runtime_data_module = SWIG_runtime_data_module();
    swigpyobject_type = tmp;
    type_init = 1;
    if (PyType_Ready(&swigpyobject_type) != 0)
      return NULL;
    if (PyModule_AddObject(runtime_data_module, "SwigPyObject", (PyObject *)&swigpyobject_type) == 0)
      SWIG_Py_INCREF((PyObject *)&swigpyobject_type);
  }
  return &swigpyobject_type;
#else
  static PyMemberDef SwigPyObject_members[] = {
      { (char *)"__dictoffset__", Py_T_PYSSIZET, offsetof(SwigPyObject, swigdict), Py_READONLY, NULL },
      { (char *)"__weaklistoffset__", Py_T_PYSSIZET, offsetof(SwigPyObject, weakreflist), Py_READONLY, NULL },
      { NULL, 0, 0, 0, NULL }
  };
  PyType_Slot slots[] = {
    { Py_tp_dealloc, (void *)SwigPyObject_dealloc },
    { Py_tp_repr, (void *)SwigPyObject_repr },
    { Py_tp_getattro, (void *)PyObject_GenericGetAttr },
    { Py_tp_doc, (void *)SwigPyObject_doc },
    { Py_tp_richcompare, (void *)SwigPyObject_richcompare },
    { Py_tp_methods, (void *)SwigPyObject_methods },
    { Py_nb_int, (void *)SwigPyObject_long },
    { Py_tp_members, (void *)SwigPyObject_members },
    { 0, NULL }
  };
  PyType_Spec spec = {
    SWIG_RUNTIME_MODULE ".SwigPyObject",
    sizeof(SwigPyObject),
    0,
    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
    slots
  };
  PyObject *pytype = PyType_FromSpec(&spec);
  PyObject *runtime_data_module = SWIG_runtime_data_module();
#if !defined(Py_LIMITED_API)
/* While this __dictoffset__ is only used with the builtin wrappers, SwigPyObject ought to be
   identical when created for use by proxy class wrappers in case it is shared across multiple modules. */
#if PY_VERSION_HEX < 0x03090000
    /* Workaround as __dictoffset__ and __weaklistoffset__ above are only supported from python-3.9 */
  if (pytype) {
    ((PyTypeObject *)pytype)->tp_dictoffset = offsetof(SwigPyObject, swigdict);
    ((PyTypeObject *)pytype)->tp_weaklistoffset = offsetof(SwigPyObject, weakreflist);
  }
#endif
#endif
  if (pytype && PyModule_AddObject(runtime_data_module, "SwigPyObject", pytype) == 0)
    SWIG_Py_INCREF(pytype);
  return (PyTypeObject *)pytype;
#endif
}

SWIGRUNTIME PyObject *
SwigPyObject_New(void *ptr, swig_type_info *ty, int own)
{
  SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_Type());
  if (sobj) {
    sobj->ptr  = ptr;
    sobj->ty   = ty;
    sobj->own  = own;
    sobj->next = 0;
    sobj->swigdict = 0;
    sobj->weakreflist = 0;
    if (own == SWIG_POINTER_OWN) {
      /* Obtain a reference to the Python capsule wrapping the module information, so that the
       * module information is correctly destroyed after all SWIG python objects have been freed
       * by the GC (and corresponding destructors invoked) */
      SWIG_Py_XINCREF(Swig_Capsule_global);
    }
  }
  return (PyObject *)sobj;
}

/* -----------------------------------------------------------------------------
 * Implements a simple Swig Packed type, and use it instead of string
 * ----------------------------------------------------------------------------- */

typedef struct {
  PyObject_HEAD
  void *pack;
  swig_type_info *ty;
  size_t size;
} SwigPyPacked;

SWIGRUNTIME PyObject *
SwigPyPacked_repr(SwigPyPacked *v)
{
  char result[SWIG_BUFFER_SIZE];
  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
    return PyUnicode_FromFormat("<Swig Packed at %s%s>", result, v->ty->name);
  } else {
    return PyUnicode_FromFormat("<Swig Packed %s>", v->ty->name);
  }  
}

SWIGRUNTIME PyObject *
SwigPyPacked_str(SwigPyPacked *v)
{
  char result[SWIG_BUFFER_SIZE];
  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){
    return PyUnicode_FromFormat("%s%s", result, v->ty->name);
  } else {
    return PyUnicode_FromString(v->ty->name);
  }
}

SWIGRUNTIME int
SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w)
{
  size_t i = v->size;
  size_t j = w->size;
  int s = (i < j) ? -1 : ((i > j) ? 1 : 0);
  return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2*v->size);
}

SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void);

SWIGRUNTIME PyTypeObject*
SwigPyPacked_Type(void) {
  static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce();
  return type;
}

SWIGRUNTIMEINLINE int
SwigPyPacked_Check(PyObject *op) {
  PyTypeObject *target_tp = SwigPyPacked_Type();
  PyTypeObject *op_type = Py_TYPE(op);
  /* Check for an exact match to SwigPyPacked */
  if (op_type == target_tp) {
    return 1;
  } else {
    /* Fallback for multiple modules */
    int cmp;
    PyObject *tpname = SWIG_PyType_GetFullyQualifiedName(op_type);
    if (!tpname)
      return 0;
    cmp = PyUnicode_CompareWithASCIIString(tpname, SWIG_RUNTIME_MODULE ".SwigPyPacked");
    SWIG_Py_DECREF(tpname);
    return cmp == 0;
  }
}

SWIGRUNTIME void
SwigPyPacked_dealloc(PyObject *v)
{
  if (SwigPyPacked_Check(v)) {
    SwigPyPacked *sobj = (SwigPyPacked *) v;
    free(sobj->pack);
  }
  PyObject_Free(v);
}

SWIGRUNTIME PyTypeObject*
SwigPyPacked_TypeOnce(void) {
  static char SwigPyPacked_doc[] = "Swig object holding a C/C++ function pointer";
#ifndef SWIG_HEAPTYPES
  static PyTypeObject swigpypacked_type;
  static int type_init = 0;
  if (!type_init) {
    const PyTypeObject tmp = {
      PyVarObject_HEAD_INIT(NULL, 0)
      SWIG_RUNTIME_MODULE ".SwigPyPacked",  /* tp_name */
      sizeof(SwigPyPacked),                 /* tp_basicsize */
      0,                                    /* tp_itemsize */
      (destructor)SwigPyPacked_dealloc,     /* tp_dealloc */
#if PY_VERSION_HEX < 0x030800b4
      (printfunc)0,                         /* tp_print */
#else
      (Py_ssize_t)0,                        /* tp_vectorcall_offset */
#endif
      (getattrfunc)0,                       /* tp_getattr */
      (setattrfunc)0,                       /* tp_setattr */
      0, /* tp_reserved in 3.0.1 */
      (reprfunc)SwigPyPacked_repr,          /* tp_repr */
      0,                                    /* tp_as_number */
      0,                                    /* tp_as_sequence */
      0,                                    /* tp_as_mapping */
      (hashfunc)0,                          /* tp_hash */
      (ternaryfunc)0,                       /* tp_call */
      (reprfunc)SwigPyPacked_str,           /* tp_str */
      PyObject_GenericGetAttr,              /* tp_getattro */
      0,                                    /* tp_setattro */
      0,                                    /* tp_as_buffer */
      Py_TPFLAGS_DEFAULT,                   /* tp_flags */
      SwigPyPacked_doc,                     /* tp_doc */
      0,                                    /* tp_traverse */
      0,                                    /* tp_clear */
      0,                                    /* tp_richcompare */
      0,                                    /* tp_weaklistoffset */
      0,                                    /* tp_iter */
      0,                                    /* tp_iternext */
      0,                                    /* tp_methods */
      0,                                    /* tp_members */
      0,                                    /* tp_getset */
      0,                                    /* tp_base */
      0,                                    /* tp_dict */
      0,                                    /* tp_descr_get */
      0,                                    /* tp_descr_set */
      0,                                    /* tp_dictoffset */
      0,                                    /* tp_init */
      0,                                    /* tp_alloc */
      0,                                    /* tp_new */
      0,                                    /* tp_free */
      0,                                    /* tp_is_gc */
      0,                                    /* tp_bases */
      0,                                    /* tp_mro */
      0,                                    /* tp_cache */
      0,                                    /* tp_subclasses */
      0,                                    /* tp_weaklist */
      0,                                    /* tp_del */
      0,                                    /* tp_version_tag */
      0,                                    /* tp_finalize */
#if PY_VERSION_HEX >= 0x03080000
      0,                                    /* tp_vectorcall */
#endif
#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000)
      0,                                    /* tp_print */
#endif
#if PY_VERSION_HEX >= 0x030c0000
      0,                                    /* tp_watched */
#endif
#if PY_VERSION_HEX >= 0x030d00a4
      0,                                    /* tp_versions_used */
#endif
#ifdef COUNT_ALLOCS
      0,                                    /* tp_allocs */
      0,                                    /* tp_frees */
      0,                                    /* tp_maxalloc */
      0,                                    /* tp_prev */
      0                                     /* tp_next */
#endif
    };
    PyObject *runtime_data_module = SWIG_runtime_data_module();
    swigpypacked_type = tmp;
    type_init = 1;
    if (PyType_Ready(&swigpypacked_type) != 0)
      return NULL;
    if (PyModule_AddObject(runtime_data_module, "SwigPyPacked", (PyObject *)&swigpypacked_type) == 0)
      SWIG_Py_INCREF((PyObject *)&swigpypacked_type);
  }
  return &swigpypacked_type;
#else
  PyType_Slot slots[] = {
    { Py_tp_dealloc, (void *)SwigPyPacked_dealloc },
    { Py_tp_repr, (void *)SwigPyPacked_repr },
    { Py_tp_str, (void *)SwigPyPacked_str },
    { Py_tp_getattro, (void *)PyObject_GenericGetAttr },
    { Py_tp_doc, (void *)SwigPyPacked_doc },
    { 0, NULL }
  };
  PyType_Spec spec = {
    SWIG_RUNTIME_MODULE ".SwigPyPacked",
    sizeof(SwigPyPacked),
    0,
    Py_TPFLAGS_DEFAULT,
    slots
  };
  PyObject *pytype = PyType_FromSpec(&spec);
  PyObject *runtime_data_module = SWIG_runtime_data_module();
  if (pytype && PyModule_AddObject(runtime_data_module, "SwigPyPacked", pytype) == 0)
    SWIG_Py_INCREF(pytype);
  return (PyTypeObject *)pytype;
#endif
}

SWIGRUNTIME PyObject *
SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty)
{
  SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_Type());
  if (sobj) {
    void *pack = malloc(size);
    if (pack) {
      memcpy(pack, ptr, size);
      sobj->pack = pack;
      sobj->ty   = ty;
      sobj->size = size;
    } else {
      PyObject_Free((PyObject *)sobj);
      sobj = 0;
    }
  }
  return (PyObject *) sobj;
}

SWIGRUNTIME swig_type_info *
SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size)
{
  if (SwigPyPacked_Check(obj)) {
    SwigPyPacked *sobj = (SwigPyPacked *)obj;
    if (sobj->size != size) return 0;
    memcpy(ptr, sobj->pack, size);
    return sobj->ty;
  } else {
    return 0;
  }
}

/* -----------------------------------------------------------------------------
 * pointers/data manipulation
 * ----------------------------------------------------------------------------- */

static PyObject *Swig_This_global = NULL;

SWIGRUNTIME PyObject *
SWIG_This(void)
{
  if (Swig_This_global == NULL)
    Swig_This_global = PyUnicode_FromString("this");
  return Swig_This_global;
}

/* Returns a borrowed reference to the 'this' object */
SWIGRUNTIME SwigPyObject *
SWIG_Python_GetSwigThis(PyObject *pyobj) 
{
  PyObject *obj;

  if (SwigPyObject_Check(pyobj))
    return (SwigPyObject *) pyobj;

#ifdef SWIGPYTHON_BUILTIN
  (void)obj;
  if (PyWeakref_CheckProxy(pyobj)) {
#if PY_VERSION_HEX >= 0x030d0000
    if (PyWeakref_GetRef(pyobj, &pyobj) > 0)
      Py_DECREF(pyobj);
    else
      pyobj = NULL;
#else
    pyobj = PyWeakref_GetObject(pyobj);
#endif
    if (pyobj && SwigPyObject_Check(pyobj))
      return (SwigPyObject*) pyobj;
  }
  return NULL;
#else

  obj = 0;

  obj = PyObject_GetAttr(pyobj, SWIG_This());
  if (obj) {
    SWIG_Py_DECREF(obj);
  } else {
    if (PyErr_Occurred()) PyErr_Clear();
    return 0;
  }
  if (obj && !SwigPyObject_Check(obj)) {
    /* a PyObject is called 'this', try to get the 'real this'
       SwigPyObject from it */ 
    return SWIG_Python_GetSwigThis(obj);
  }
  return (SwigPyObject *)obj;
#endif
}

/* Acquire a pointer value */

SWIGRUNTIME int
SWIG_Python_AcquirePtr(PyObject *obj, int own) {
  if (own == SWIG_POINTER_OWN) {
    SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj);
    if (sobj) {
      int oldown = sobj->own;
      sobj->own = own;
      return oldown;
    }
  }
  return 0;
}

/* Convert a pointer value */

SWIGRUNTIME int
SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) {
  int res;
  SwigPyObject *sobj;
  int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0;

  if (!obj)
    return SWIG_ERROR;
  if (obj == Py_None && !implicit_conv) {
    if (ptr)
      *ptr = 0;
    return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK;
  }

  res = SWIG_ERROR;

  sobj = SWIG_Python_GetSwigThis(obj);
  if (own)
    *own = 0;
  while (sobj) {
    void *vptr = sobj->ptr;
    if (ty) {
      swig_type_info *to = sobj->ty;
      if (to == ty) {
        /* no type cast needed */
        if (ptr) *ptr = vptr;
        break;
      } else {
        swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
        if (!tc) {
          sobj = (SwigPyObject *)sobj->next;
        } else {
          if (ptr) {
            int newmemory = 0;
            *ptr = SWIG_TypeCast(tc,vptr,&newmemory);
            if (newmemory == SWIG_CAST_NEW_MEMORY) {
              assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */
              if (own)
                *own = *own | SWIG_CAST_NEW_MEMORY;
            }
          }
          break;
        }
      }
    } else {
      if (ptr) *ptr = vptr;
      break;
    }
  }
  if (sobj) {
    if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) {
      res = SWIG_ERROR_RELEASE_NOT_OWNED;
    } else {
      if (own)
        *own = *own | sobj->own;
      if (flags & SWIG_POINTER_DISOWN) {
        sobj->own = 0;
      }
      if (flags & SWIG_POINTER_CLEAR) {
        sobj->ptr = 0;
      }
      res = SWIG_OK;
    }
  } else {
    if (implicit_conv) {
      SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0;
      if (data && !data->implicitconv) {
        PyObject *klass = data->klass;
        if (klass) {
          PyObject *impconv;
          data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/
          impconv = SWIG_Python_CallFunctor(klass, obj);
          data->implicitconv = 0;
          if (PyErr_Occurred()) {
            PyErr_Clear();
            impconv = 0;
          }
          if (impconv) {
            SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv);
            if (iobj) {
              void *vptr;
              res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0);
              if (SWIG_IsOK(res)) {
                if (ptr) {
                  *ptr = vptr;
                  /* transfer the ownership to 'ptr' */
                  iobj->own = 0;
                  res = SWIG_AddCast(res);
                  res = SWIG_AddNewMask(res);
                } else {
                  res = SWIG_AddCast(res);		    
                }
              }
            }
            SWIG_Py_DECREF(impconv);
          }
        }
      }
      if (!SWIG_IsOK(res) && obj == Py_None) {
        if (ptr)
          *ptr = 0;
        if (PyErr_Occurred())
          PyErr_Clear();
        res = SWIG_OK;
      }
    }
  }
  return res;
}

/* Convert a function ptr value */

SWIGRUNTIME int
SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) {
  if (!PyCFunction_Check(obj)) {
    return SWIG_ConvertPtr(obj, ptr, ty, 0);
  } else {
    void *vptr = 0;
    swig_cast_info *tc;

    /* here we get the method pointer for callbacks */
#ifndef Py_LIMITED_API
    const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
#else
    PyObject* pystr_doc = PyObject_GetAttrString(obj, "__doc__");
    PyObject *bytes = NULL;
    const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0;
#endif
    const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0;
    if (desc)
      desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0;
#ifdef Py_LIMITED_API
    SWIG_Py_XDECREF(bytes);
    SWIG_Py_XDECREF(pystr_doc);
#endif
    if (!desc)
      return SWIG_ERROR;
    tc = SWIG_TypeCheck(desc,ty);
    if (tc) {
      int newmemory = 0;
      *ptr = SWIG_TypeCast(tc,vptr,&newmemory);
      assert(!newmemory); /* newmemory handling not yet implemented */
    } else {
      return SWIG_ERROR;
    }
    return SWIG_OK;
  }
}

/* Convert a packed pointer value */

SWIGRUNTIME int
SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) {
  swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz);
  if (!to) return SWIG_ERROR;
  if (ty) {
    if (to != ty) {
      /* check type cast? */
      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
      if (!tc) return SWIG_ERROR;
    }
  }
  return SWIG_OK;
}  

/* -----------------------------------------------------------------------------
 * Create a new pointer object
 * ----------------------------------------------------------------------------- */

/*
  Create a new instance object, without calling __init__, and set the
  'this' attribute.
*/

SWIGRUNTIME PyObject* 
SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this)
{
  PyObject *inst = 0;
  PyObject *newraw = data->newraw;
  if (newraw) {
    inst = PyObject_Call(newraw, data->newargs, NULL);
    if (inst) {
      if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) {
        SWIG_Py_DECREF(inst);
        inst = 0;
      }
    }
  } else {
    PyObject *empty_args = PyTuple_New(0);
    if (empty_args) {
      PyObject *empty_kwargs = PyDict_New();
      if (empty_kwargs) {
#ifndef Py_LIMITED_API
        newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new;
#else
        newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new);
#endif
        inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs);
        SWIG_Py_DECREF(empty_kwargs);
        if (inst) {
          if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) {
            SWIG_Py_DECREF(inst);
            inst = 0;
          } else {
            PyType_Modified(Py_TYPE(inst));
          }
        }
      }
      SWIG_Py_DECREF(empty_args);
    }
  }
  return inst;
}

SWIGRUNTIME int
SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this)
{
  return PyObject_SetAttr(inst, SWIG_This(), swig_this);
} 


SWIGINTERN PyObject *
SWIG_Python_InitShadowInstance(PyObject *args) {
  PyObject *obj[2];
  if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) {
    return NULL;
  } else {
    SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]);
    if (sthis) {
      SWIG_Py_DECREF(SwigPyObject_append((PyObject*) sthis, obj[1]));
    } else {
      if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0)
        return NULL;
    }
    return SWIG_Py_Void();
  }
}

/* Create a new pointer object */

SWIGRUNTIME PyObject *
SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) {
  SwigPyClientData *clientdata;
  PyObject * robj;
  int own;

  if (!ptr)
    return SWIG_Py_Void();

  clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0;
  own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;
  if (clientdata && clientdata->pytype) {
    SwigPyObject *newobj;
    if (flags & SWIG_BUILTIN_TP_INIT) {
      newobj = (SwigPyObject*) self;
      if (newobj->ptr) {
#ifndef Py_LIMITED_API
        allocfunc alloc = clientdata->pytype->tp_alloc;
#else
        allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc);
#endif
        PyObject *next_self = alloc(clientdata->pytype, 0);
        while (newobj->next)
	  newobj = (SwigPyObject *) newobj->next;
        newobj->next = next_self;
        newobj = (SwigPyObject *)next_self;
        newobj->swigdict = 0;
        newobj->weakreflist = 0;
      }
    } else {
      newobj = PyObject_New(SwigPyObject, clientdata->pytype);
      if (newobj) {
        newobj->swigdict = 0;
        newobj->weakreflist = 0;
      }
    }
    if (newobj) {
      newobj->ptr = ptr;
      newobj->ty = type;
      newobj->own = own;
      newobj->next = 0;
      return (PyObject*) newobj;
    }
    return SWIG_Py_Void();
  }

  assert(!(flags & SWIG_BUILTIN_TP_INIT));

  robj = SwigPyObject_New(ptr, type, own);
  if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) {
    PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj);
    SWIG_Py_DECREF(robj);
    robj = inst;
  }
  return robj;
}

/* Create a new packed object */

SWIGRUNTIMEINLINE PyObject *
SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
  return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void();
}

/* -----------------------------------------------------------------------------*
 *  Get type list 
 * -----------------------------------------------------------------------------*/

#ifdef SWIG_LINK_RUNTIME
void *SWIG_ReturnGlobalTypeList(void *);
#endif

static PyObject *Swig_TypeCache_global = NULL;

/* The python cached type query */
SWIGRUNTIME PyObject *
SWIG_Python_TypeCache(void) {
  if (Swig_TypeCache_global == NULL) {
    Swig_TypeCache_global = PyDict_New();
  }
  return Swig_TypeCache_global;
}

SWIGRUNTIME swig_module_info *
SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) {
#ifdef SWIG_LINK_RUNTIME
  static void *type_pointer = (void *)0;
  /* first check if module already created */
  if (!type_pointer) {
    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);
  }
#else
  void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0);
  if (PyErr_Occurred()) {
    PyErr_Clear();
    type_pointer = (void *)0;
  }
#endif
  return (swig_module_info *) type_pointer;
}


#if defined(SWIG_REFCNT_DEBUG)
#define SWIG_PYOBJ_REFCNT(OBJ) fprintf(stdout, "" #OBJ " count %ld\n", (OBJ ? Py_REFCNT(OBJ) : 0))
#else
#define SWIG_PYOBJ_REFCNT(OBJ)
#endif

static int interpreter_counter = 0; /* how many (sub-)interpreters are using swig_module's types */

SWIGRUNTIME void
SWIG_Python_DestroyModule(PyObject *obj)
{
  swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME);
  swig_type_info **types = swig_module->types;
  size_t i;
  if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */
    return;
  for (i = 0; i < swig_module->size; ++i) {
    swig_type_info *ty = types[i];
    if (ty->owndata) {
      SwigPyClientData *data = (SwigPyClientData *) ty->clientdata;
      ty->clientdata = 0;
      if (data) SwigPyClientData_Del(data);
    }
  }
  SWIG_PYOBJ_REFCNT(Swig_This_global);
  SWIG_Py_XDECREF(Swig_This_global);
  Swig_This_global = NULL;

  SWIG_PYOBJ_REFCNT(Swig_Globals_global);
  SWIG_Py_XDECREF(Swig_Globals_global);
  Swig_Globals_global = NULL;

  SWIG_PYOBJ_REFCNT(Swig_TypeCache_global);
  SWIG_Py_XDECREF(Swig_TypeCache_global);
  Swig_TypeCache_global = NULL;

  SWIG_PYOBJ_REFCNT(Swig_Capsule_global);
  Swig_Capsule_global = NULL;

  SWIG_PYOBJ_REFCNT(Swig_runtime_data_module_global);
  SWIG_Py_XDECREF(Swig_runtime_data_module_global);
  Swig_runtime_data_module_global = NULL;
}

SWIGRUNTIME void
SWIG_Python_SetModule(swig_module_info *swig_module) {
  PyObject *runtime_data_module = SWIG_runtime_data_module();
  PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule);
  if (pointer && runtime_data_module) {
    if (PyModule_AddObject(runtime_data_module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) {
      ++interpreter_counter;
      Swig_Capsule_global = pointer;
    } else {
      SWIG_Py_DECREF(pointer);
    }
  } else {
    SWIG_Py_XDECREF(pointer);
  }
}

SWIGRUNTIME swig_type_info *
SWIG_Python_TypeQuery(const char *type)
{
  swig_type_info *descriptor;
  PyObject *cache = SWIG_Python_TypeCache();
  PyObject *obj;
  SWIG_PyDict_GetItemStringRef(cache, type, &obj);
  if (obj) {
    descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL);
  } else {
    swig_module_info *swig_module = SWIG_GetModule(0);
    descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type);
    if (descriptor) {
      obj = PyCapsule_New((void*) descriptor, NULL, NULL);
      if (obj) PyDict_SetItemString(cache, type, obj);
    }
  }
  SWIG_Py_XDECREF(obj);
  return descriptor;
}

/* 
   For backward compatibility only
*/
#define SWIG_POINTER_EXCEPTION  0
#define SWIG_arg_fail(arg)      SWIG_Python_ArgFail(arg)
#define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)

SWIGRUNTIME int
SWIG_Python_AddErrMesg(const char* mesg, int infront)
{  
  if (PyErr_Occurred()) {
    PyObject *type = 0;
    PyObject *value = 0;
    PyObject *traceback = 0;
    PyErr_Fetch(&type, &value, &traceback);
    if (value) {
      PyObject *old_str = PyObject_Str(value);
      PyObject *bytes = NULL;
      const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes);
      const char *errmesg = tmp ? tmp : "Invalid error message";
      SWIG_Py_XINCREF(type);
      PyErr_Clear();
      if (infront) {
	PyErr_Format(type, "%s %s", mesg, errmesg);
      } else {
	PyErr_Format(type, "%s %s", errmesg, mesg);
      }
      SWIG_Py_XDECREF(bytes);
      SWIG_Py_DECREF(old_str);
    }
    return 1;
  } else {
    return 0;
  }
}
  
SWIGRUNTIME int
SWIG_Python_ArgFail(int argnum)
{
  if (PyErr_Occurred()) {
    /* add information about failing argument */
    char mesg[256];
    PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum);
    return SWIG_Python_AddErrMesg(mesg, 1);
  } else {
    return 0;
  }
}

SWIGRUNTIMEINLINE const char *
SwigPyObject_GetDesc(PyObject *self)
{
  SwigPyObject *v = (SwigPyObject *)self;
  swig_type_info *ty = v ? v->ty : 0;
  return ty ? ty->str : "";
}

/* Convert a pointer value, signal an exception on a type mismatch */
SWIGRUNTIME void *
SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) {
  void *result;
  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
    PyErr_Clear();
  }
  return result;
}

#ifdef SWIGPYTHON_BUILTIN
SWIGRUNTIME int
SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) {
  PyTypeObject *tp = Py_TYPE(obj);
  PyObject *descr;
  PyObject *encoded_name;
  descrsetfunc f;
  int res = -1;

# ifdef Py_USING_UNICODE
  if (PyBytes_Check(name)) {
    name = PyUnicode_Decode(PyBytes_AsString(name), PyBytes_Size(name), NULL, NULL);
    if (!name)
      return -1;
  } else if (!PyUnicode_Check(name))
# else
  if (!PyBytes_Check(name))
# endif
  {
    PyObject *tpname = SWIG_PyType_GetFullyQualifiedName(Py_TYPE(name));
    PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%S'", tpname);
    SWIG_Py_DECREF(tpname);
    return -1;
  } else {
    SWIG_Py_INCREF(name);
  }

  if (!tp->tp_dict) {
    if (PyType_Ready(tp) != 0)
      goto done;
  }

  descr = _PyType_Lookup(tp, name);
  f = NULL;
  if (descr != NULL)
    f = Py_TYPE(descr)->tp_descr_set;
  if (!f) {
    if (PyBytes_Check(name)) {
      encoded_name = name;
      SWIG_Py_INCREF(name);
    } else {
      encoded_name = PyUnicode_AsUTF8String(name);
      if (!encoded_name)
        goto done;
    }
    PyErr_Format(PyExc_AttributeError, "'%s' object has no attribute '%s'", tp->tp_name, PyBytes_AsString(encoded_name));
    SWIG_Py_DECREF(encoded_name);
  } else {
    res = f(descr, obj, value);
  }
  
  done:
  SWIG_Py_DECREF(name);
  return res;
}
#endif


#ifdef __cplusplus
}
#endif



#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) 

#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) 



  #define SWIG_exception(code, msg) do { SWIG_Error(code, msg); SWIG_fail;; } while(0) 


/* -------- TYPES TABLE (BEGIN) -------- */

#define SWIGTYPE_p_char swig_types[0]
#define SWIGTYPE_p_fz_pixmap swig_types[1]
#define SWIGTYPE_p_fz_quad swig_types[2]
#define SWIGTYPE_p_fz_rect swig_types[3]
#define SWIGTYPE_p_fz_stext_char swig_types[4]
#define SWIGTYPE_p_fz_stext_line swig_types[5]
#define SWIGTYPE_p_fz_stext_page swig_types[6]
#define SWIGTYPE_p_mupdf__FzBuffer swig_types[7]
#define SWIGTYPE_p_mupdf__FzDevice swig_types[8]
#define SWIGTYPE_p_mupdf__FzDocument swig_types[9]
#define SWIGTYPE_p_mupdf__FzLink swig_types[10]
#define SWIGTYPE_p_mupdf__FzMatrix swig_types[11]
#define SWIGTYPE_p_mupdf__FzOutline swig_types[12]
#define SWIGTYPE_p_mupdf__FzPage swig_types[13]
#define SWIGTYPE_p_mupdf__FzPixmap swig_types[14]
#define SWIGTYPE_p_mupdf__FzPoint swig_types[15]
#define SWIGTYPE_p_mupdf__FzRect swig_types[16]
#define SWIGTYPE_p_mupdf__FzStextChar swig_types[17]
#define SWIGTYPE_p_mupdf__FzStextLine swig_types[18]
#define SWIGTYPE_p_mupdf__FzStextPage swig_types[19]
#define SWIGTYPE_p_mupdf__PdfAnnot swig_types[20]
#define SWIGTYPE_p_mupdf__PdfDocument swig_types[21]
#define SWIGTYPE_p_mupdf__PdfGraftMap swig_types[22]
#define SWIGTYPE_p_mupdf__PdfObj swig_types[23]
#define SWIGTYPE_p_mupdf__PdfPage swig_types[24]
#define SWIGTYPE_p_std__vectorT_std__string_t swig_types[25]
static swig_type_info *swig_types[27];
static swig_module_info swig_module = {swig_types, 26, 0, 0, 0, 0};
#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)

/* -------- TYPES TABLE (END) -------- */

#ifdef SWIG_TypeQuery
# undef SWIG_TypeQuery
#endif
#define SWIG_TypeQuery SWIG_Python_TypeQuery

/*-----------------------------------------------
              @(target):= _extra.so
  ------------------------------------------------*/
#define SWIG_init    PyInit__extra


#ifdef __cplusplus
#include <utility>
/* SwigValueWrapper is described in swig.swg */
template<typename T> class SwigValueWrapper {
  struct SwigSmartPointer {
    T *ptr;
    SwigSmartPointer(T *p) : ptr(p) { }
    ~SwigSmartPointer() { delete ptr; }
    SwigSmartPointer& operator=(SwigSmartPointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; }
    void reset(T *p) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = p; }
  } pointer;
  SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
  SwigValueWrapper(const SwigValueWrapper<T>& rhs);
public:
  SwigValueWrapper() : pointer(0) { }
  SwigValueWrapper& operator=(const T& t) { SwigSmartPointer tmp(new T(t)); pointer = tmp; return *this; }
#if __cplusplus >= 201103L
  SwigValueWrapper& operator=(T&& t) { SwigSmartPointer tmp(new T(std::move(t))); pointer = tmp; return *this; }
  operator T&&() const { return std::move(*pointer.ptr); }
#else
  operator T&() const { return *pointer.ptr; }
#endif
  T *operator&() const { return pointer.ptr; }
  static void reset(SwigValueWrapper& t, T *p) { t.pointer.reset(p); }
};

/*
 * SwigValueInit() is a generic initialisation solution as the following approach:
 * 
 *       T c_result = T();
 * 
 * doesn't compile for all types for example:
 * 
 *       unsigned int c_result = unsigned int();
 */
template <typename T> T SwigValueInit() {
  return T();
}

#if __cplusplus >= 201103L
# define SWIG_STD_MOVE(OBJ) std::move(OBJ)
#else
# define SWIG_STD_MOVE(OBJ) OBJ
#endif

#if __cplusplus >= 201103L
# define SWIG_OVERRIDE override
#else
# define SWIG_OVERRIDE
#endif

#endif


#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) 
#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) 


#include <stdexcept>


namespace swig {
  class SwigPtr_PyObject {
  protected:
    PyObject *_obj;

  public:
    SwigPtr_PyObject() :_obj(0)
    {
    }

    SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj)
    {
      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
      SWIG_Py_XINCREF(_obj);
      SWIG_PYTHON_THREAD_END_BLOCK;
    }
    
    SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj)
    {
      if (initial_ref) {
        SWIG_PYTHON_THREAD_BEGIN_BLOCK;
        SWIG_Py_XINCREF(_obj);
        SWIG_PYTHON_THREAD_END_BLOCK;
      }
    }
    
    SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) 
    {
      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
      SWIG_Py_XINCREF(item._obj);
      SWIG_Py_XDECREF(_obj);
      _obj = item._obj;
      SWIG_PYTHON_THREAD_END_BLOCK;
      return *this;      
    }
    
    ~SwigPtr_PyObject() 
    {
      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
      SWIG_Py_XDECREF(_obj);
      SWIG_PYTHON_THREAD_END_BLOCK;
    }
    
    operator PyObject *() const
    {
      return _obj;
    }

    PyObject *operator->() const
    {
      return _obj;
    }
  };
}


namespace swig {
  struct SwigVar_PyObject : SwigPtr_PyObject {
    SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { }
    
    SwigVar_PyObject & operator = (PyObject* obj)
    {
      SWIG_Py_XDECREF(_obj);
      _obj = obj;
      return *this;      
    }
  };
}


#include <string>


#include "mupdf/classes2.h"
#include "mupdf/exceptions.h"
#include "mupdf/internal.h"

#include <algorithm>
#include <float.h>


#define MAKE_MUPDF_VERSION_INT(major, minor, patch) ((major << 16) + (minor << 8) + (patch << 0))

#define MUPDF_VERSION_INT MAKE_MUPDF_VERSION_INT(FZ_VERSION_MAJOR, FZ_VERSION_MINOR, FZ_VERSION_PATCH)

#define MUPDF_VERSION_GE(major, minor, patch) \
        MUPDF_VERSION_INT >= MAKE_MUPDF_VERSION_INT(major, minor, patch)

/* Define a wrapper for PDF_NAME that returns a mupdf::PdfObj instead of a
pdf_obj*. This avoids implicit construction of a mupdf::PdfObj, which is
deliberately prohibited (with `explicit` on constructors) by recent MuPDF. */
#define PDF_NAME2(X) mupdf::PdfObj(PDF_NAME(X))

/* Returns equivalent of `repr(x)`. */
static std::string repr(PyObject* x)
{
    PyObject* repr = PyObject_Repr(x);
    PyObject* repr_str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");
    #ifdef Py_LIMITED_API
        const char* repr_str_s = PyBytes_AsString(repr_str);
    #else
        const char* repr_str_s = PyBytes_AS_STRING(repr_str);
    #endif
    std::string ret = repr_str_s;
    Py_DECREF(repr_str);
    Py_DECREF(repr);
    return ret;
}

#ifdef Py_LIMITED_API
    static PyObject* PySequence_ITEM(PyObject* o, Py_ssize_t i)
    {
        return PySequence_GetItem(o, i);
    }

    static const char* PyUnicode_AsUTF8(PyObject* o)
    {
        static PyObject* string = nullptr;
        Py_XDECREF(string);
        string = PyUnicode_AsUTF8String(o);
        return PyBytes_AsString(string);
    }
#endif


/* These are also in pymupdf/__init__.py. */
const char MSG_BAD_ANNOT_TYPE[] = "bad annot type";
const char MSG_BAD_APN[] = "bad or missing annot AP/N";
const char MSG_BAD_ARG_INK_ANNOT[] = "arg must be seq of seq of float pairs";
const char MSG_BAD_ARG_POINTS[] = "bad seq of points";
const char MSG_BAD_BUFFER[] = "bad type: 'buffer'";
const char MSG_BAD_COLOR_SEQ[] = "bad color sequence";
const char MSG_BAD_DOCUMENT[] = "cannot open broken document";
const char MSG_BAD_FILETYPE[] = "bad filetype";
const char MSG_BAD_LOCATION[] = "bad location";
const char MSG_BAD_OC_CONFIG[] = "bad config number";
const char MSG_BAD_OC_LAYER[] = "bad layer number";
const char MSG_BAD_OC_REF[] = "bad 'oc' reference";
const char MSG_BAD_PAGEID[] = "bad page id";
const char MSG_BAD_PAGENO[] = "bad page number(s)";
const char MSG_BAD_PDFROOT[] = "PDF has no root";
const char MSG_BAD_RECT[] = "rect is infinite or empty";
const char MSG_BAD_TEXT[] = "bad type: 'text'";
const char MSG_BAD_XREF[] = "bad xref";
const char MSG_COLOR_COUNT_FAILED[] = "color count failed";
const char MSG_FILE_OR_BUFFER[] = "need font file or buffer";
const char MSG_FONT_FAILED[] = "cannot create font";
const char MSG_IS_NO_ANNOT[] = "is no annotation";
const char MSG_IS_NO_IMAGE[] = "is no image";
const char MSG_IS_NO_PDF[] = "is no PDF";
const char MSG_IS_NO_DICT[] = "object is no PDF dict";
const char MSG_PIX_NOALPHA[] = "source pixmap has no alpha";
const char MSG_PIXEL_OUTSIDE[] = "pixel(s) outside image";

#define JM_BOOL(x) PyBool_FromLong((long) (x))

static PyObject *JM_UnicodeFromStr(const char *c);


#ifdef _WIN32

/* These functions are not provided on Windows. */

int vasprintf(char** str, const char* fmt, va_list ap)
{
    va_list ap2;

    va_copy(ap2, ap);
    int len = vsnprintf(nullptr, 0, fmt, ap2);
    va_end(ap2);
    
    char* buffer = (char*) malloc(len + 1);
    if (!buffer)
    {
        *str = nullptr;
        return -1;
    }
    va_copy(ap2, ap);
    int len2 = vsnprintf(buffer, len + 1, fmt, ap2);
    va_end(ap2);
    assert(len2 == len);
    *str = buffer;
    return len;
}

int asprintf(char** str, const char* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    int ret = vasprintf(str, fmt, ap);
    va_end(ap);

    return ret;
}
#endif


static void messagev(const char* format, va_list va)
{
    static PyObject* pymupdf_module = PyImport_ImportModule("pymupdf");
    static PyObject* message_fn = PyObject_GetAttrString(pymupdf_module, "message");
    char* text;
    vasprintf(&text, format, va);
    PyObject* text_py = PyUnicode_FromString(text);
    PyObject* args = PyTuple_Pack(1, text_py);
    PyObject* ret = PyObject_CallObject(message_fn, args);
    Py_XDECREF(ret);
    Py_XDECREF(args);
    Py_XDECREF(text_py);
    free(text);
}

static void messagef(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    messagev(format, args);
    va_end(args);
}

PyObject* JM_EscapeStrFromStr(const char* c)
{
    if (!c) return PyUnicode_FromString("");
    PyObject* val = PyUnicode_DecodeRawUnicodeEscape(c, (Py_ssize_t) strlen(c), "replace");
    if (!val)
    {
        val = PyUnicode_FromString("");
        PyErr_Clear();
    }
    return val;
}

PyObject* JM_EscapeStrFromBuffer(fz_buffer* buff)
{
    if (!buff) return PyUnicode_FromString("");
    unsigned char* s = nullptr;
    size_t len = mupdf::ll_fz_buffer_storage(buff, &s);
    PyObject* val = PyUnicode_DecodeRawUnicodeEscape((const char*) s, (Py_ssize_t) len, "replace");
    if (!val)
    {
        val = PyUnicode_FromString("");
        PyErr_Clear();
    }
    return val;
}

//----------------------------------------------------------------------------
// Deep-copies a source page to the target.
// Modified version of function of pdfmerge.c: we also copy annotations, but
// we skip some subtypes. In addition we rotate output.
//----------------------------------------------------------------------------
static void page_merge(
        mupdf::PdfDocument& doc_des,
        mupdf::PdfDocument& doc_src,
        int page_from,
        int page_to,
        int rotate,
        int links,
        int copy_annots,
        mupdf::PdfGraftMap& graft_map
        )
{
    // list of object types (per page) we want to copy

    /* Fixme: on linux these get destructed /after/
    mupdf/platform/c++/implementation/internal.cpp:s_thread_state, which causes
    problems - s_thread_state::m_ctx will have been freed. We have a hack
    that sets s_thread_state::m_ctx when destructed, so it mostly works when
    s_thread_state.get_context() is called after destruction, but this causes
    memento leaks and is clearly incorrect.
    
    Perhaps we could use pdf_obj* known_page_objs[] = {...} and create PdfObj
    wrappers as used - this would avoid any cleanup at exit. And it's a general
    solution to problem of ordering of cleanup of globals.
    */
    static pdf_obj* known_page_objs[] = {
            PDF_NAME(Contents),
            PDF_NAME(Resources),
            PDF_NAME(MediaBox),
            PDF_NAME(CropBox),
            PDF_NAME(BleedBox),
            PDF_NAME(TrimBox),
            PDF_NAME(ArtBox),
            PDF_NAME(Rotate),
            PDF_NAME(UserUnit)
            };
    int known_page_objs_num = sizeof(known_page_objs) / sizeof(known_page_objs[0]);
    mupdf::PdfObj   page_ref = mupdf::pdf_lookup_page_obj(doc_src, page_from);

    // make new page dict in dest doc
    mupdf::PdfObj   page_dict = mupdf::pdf_new_dict(doc_des, 4);
    mupdf::pdf_dict_put(page_dict, PDF_NAME2(Type), PDF_NAME2(Page));

    for (int i = 0; i < known_page_objs_num; ++i)
    {
        mupdf::PdfObj   known_page_obj(known_page_objs[i]);
        mupdf::PdfObj   obj = mupdf::pdf_dict_get_inheritable(page_ref, known_page_obj);
        if (obj.m_internal)
        {
            mupdf::pdf_dict_put(
                    page_dict,
                    known_page_obj,
                    mupdf::pdf_graft_mapped_object(graft_map, obj)
                    );
        }
    }

    // Copy annotations, but skip Link, Popup, IRT, Widget types
    // If selected, remove dict keys P (parent) and Popup
    if (copy_annots)
    {
        mupdf::PdfObj old_annots = mupdf::pdf_dict_get(page_ref, PDF_NAME2(Annots));
        int n = mupdf::pdf_array_len(old_annots);
        if (n > 0)
        {
            mupdf::PdfObj new_annots = mupdf::pdf_dict_put_array(page_dict, PDF_NAME2(Annots), n);
            for (int i = 0; i < n; i++)
            {
                mupdf::PdfObj o = mupdf::pdf_array_get(old_annots, i);
                if (!o.m_internal || !mupdf::pdf_is_dict(o)) // skip non-dict items
                {
                    continue;   // skip invalid/null/non-dict items
                }
                if (mupdf::pdf_dict_get(o, PDF_NAME2(IRT)).m_internal) continue;
                mupdf::PdfObj subtype = mupdf::pdf_dict_get(o, PDF_NAME2(Subtype));
                if (mupdf::pdf_name_eq(subtype, PDF_NAME2(Link))) continue;
                if (mupdf::pdf_name_eq(subtype, PDF_NAME2(Popup))) continue;
                if (mupdf::pdf_name_eq(subtype, PDF_NAME2(Widget))) continue;
                mupdf::pdf_dict_del(o, PDF_NAME2(Popup));
                mupdf::pdf_dict_del(o, PDF_NAME2(P));
                mupdf::PdfObj copy_o = mupdf::pdf_graft_mapped_object(graft_map, o);
                mupdf::PdfObj annot = mupdf::pdf_new_indirect(
                        doc_des,
                        mupdf::pdf_to_num(copy_o),
                        0
                        );
                mupdf::pdf_array_push(new_annots, annot);
            }
        }
    }
    // rotate the page
    if (rotate != -1)
    {
        mupdf::pdf_dict_put_int(page_dict, PDF_NAME2(Rotate), rotate);
    }
    // Now add the page dictionary to dest PDF
    mupdf::PdfObj ref = mupdf::pdf_add_object(doc_des, page_dict);

    // Insert new page at specified location
    mupdf::pdf_insert_page(doc_des, page_to, ref);
}

//-----------------------------------------------------------------------------
// Copy a range of pages (spage, epage) from a source PDF to a specified
// location (apage) of the target PDF.
// If spage > epage, the sequence of source pages is reversed.
//-----------------------------------------------------------------------------
static void JM_merge_range(
        mupdf::PdfDocument& doc_des,
        mupdf::PdfDocument& doc_src,
        int spage,
        int epage,
        int apage,
        int rotate,
        int links,
        int annots,
        int show_progress,
        mupdf::PdfGraftMap& graft_map
        )
{
    int afterpage = apage;
    int counter = 0;  // copied pages counter
    int total = mupdf::ll_fz_absi(epage - spage) + 1;  // total pages to copy

    if (spage < epage)
    {
        for (int page = spage; page <= epage; page++, afterpage++)
        {
            page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map);
            counter++;
            if (show_progress > 0 && counter % show_progress == 0)
            {
                messagef("Inserted %i of %i pages.", counter, total);
            }
        }
    }
    else
    {
        for (int page = spage; page >= epage; page--, afterpage++)
        {
            page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map);
            counter++;
            if (show_progress > 0 && counter % show_progress == 0)
            {
                messagef("Inserted %i of %i pages.", counter, total);
            }
        }
    }
}

static bool JM_have_operation(mupdf::PdfDocument& pdf)
{
    // Ensure valid journalling state
    if (pdf.m_internal->journal and !mupdf::pdf_undoredo_step(pdf, 0))
    {
        return 0;
    }
    return 1;
}

static void JM_ensure_operation(mupdf::PdfDocument& pdf)
{
    if (!JM_have_operation(pdf))
    {
        throw std::runtime_error("No journalling operation started");
    }
}


static void FzDocument_insert_pdf(
        mupdf::FzDocument& doc,
        mupdf::FzDocument& src,
        int from_page,
        int to_page,
        int start_at,
        int rotate,
        int links,
        int annots,
        int show_progress,
        int final,
        mupdf::PdfGraftMap& graft_map
        )
{
    //std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "\n";
    mupdf::PdfDocument pdfout = mupdf::pdf_specifics(doc);
    mupdf::PdfDocument pdfsrc = mupdf::pdf_specifics(src);
    int outCount = mupdf::fz_count_pages(doc);
    int srcCount = mupdf::fz_count_pages(src);

    // local copies of page numbers
    int fp = from_page;
    int tp = to_page;
    int sa = start_at;

    // normalize page numbers
    fp = std::max(fp, 0);               // -1 = first page
    fp = std::min(fp, srcCount - 1);    // but do not exceed last page

    if (tp < 0) tp = srcCount - 1;      // -1 = last page
    tp = std::min(tp, srcCount - 1);    // but do not exceed last page

    if (sa < 0) sa = outCount;          // -1 = behind last page
    sa = std::min(sa, outCount);        // but that is also the limit

    if (!pdfout.m_internal || !pdfsrc.m_internal)
    {
        throw std::runtime_error("source or target not a PDF");
    }
    JM_ensure_operation(pdfout);
    JM_merge_range(pdfout, pdfsrc, fp, tp, sa, rotate, links, annots, show_progress, graft_map);
}

static int page_xref(mupdf::FzDocument& this_doc, int pno)
{
    int page_count = mupdf::fz_count_pages(this_doc);
    int n = pno;
    while (n < 0)
    {
        n += page_count;
    }
    mupdf::PdfDocument pdf = mupdf::pdf_specifics(this_doc);
    assert(pdf.m_internal);
    int xref = 0;
    if (n >= page_count)
    {
        throw std::runtime_error(MSG_BAD_PAGENO);//, PyExc_ValueError);
    }
    xref = mupdf::pdf_to_num(mupdf::pdf_lookup_page_obj(pdf, n));
    return xref;
}

static void _newPage(mupdf::PdfDocument& pdf, int pno=-1, float width=595, float height=842)
{
    if (!pdf.m_internal)
    {
        throw std::runtime_error("is no PDF");
    }
    mupdf::FzRect mediabox(0, 0, width, height);
    if (pno < -1)
    {
        throw std::runtime_error("bad page number(s)");  // Should somehow be Python ValueError
    }
    JM_ensure_operation(pdf);
    // create /Resources and /Contents objects
    mupdf::PdfObj resources = mupdf::pdf_add_new_dict(pdf, 1);
    mupdf::FzBuffer contents;
    mupdf::PdfObj page_obj = mupdf::pdf_add_page(pdf, mediabox, 0, resources, contents);
    mupdf::pdf_insert_page(pdf, pno, page_obj);
}

static void _newPage(mupdf::FzDocument& self, int pno=-1, float width=595, float height=842)
{
    mupdf::PdfDocument pdf = mupdf::pdf_specifics(self);
    _newPage(pdf, pno, width, height);
}


//------------------------------------------------------------------------
// return the annotation names (list of /NM entries)
//------------------------------------------------------------------------
static std::vector< std::string> JM_get_annot_id_list(mupdf::PdfPage& page)
{
    std::vector< std::string> names;
    mupdf::PdfObj annots = mupdf::pdf_dict_get(page.obj(), PDF_NAME2(Annots));
    if (!annots.m_internal) return names;
    int n = mupdf::pdf_array_len(annots);
    for (int i = 0; i < n; i++)
    {
        mupdf::PdfObj annot_obj = mupdf::pdf_array_get(annots, i);
        mupdf::PdfObj name = mupdf::pdf_dict_gets(annot_obj, "NM");
        if (name.m_internal)
        {
            names.push_back(mupdf::pdf_to_text_string(name));
        }
    }
    return names;
}


//------------------------------------------------------------------------
// Add a unique /NM key to an annotation or widget.
// Append a number to 'stem' such that the result is a unique name.
//------------------------------------------------------------------------
static void JM_add_annot_id(mupdf::PdfAnnot& annot, const char* stem)
{
    mupdf::PdfPage page = mupdf::pdf_annot_page(annot);
    mupdf::PdfObj annot_obj = mupdf::pdf_annot_obj(annot);
    std::vector< std::string> names = JM_get_annot_id_list(page);
    char* stem_id = nullptr;
    for (int i=0; ; ++i)
    {
        free(stem_id);
        asprintf(&stem_id,  "fitz-%s%d", stem, i);
        if (std::find(names.begin(), names.end(), stem_id) == names.end())
        {
            break;
        }
    }
    mupdf::PdfObj name = mupdf::pdf_new_string(stem_id, strlen(stem_id));
    free(stem_id);
    mupdf::pdf_dict_puts(annot_obj, "NM", name);
    page.m_internal->doc->resynth_required = 0;
}

//----------------------------------------------------------------
// page add_caret_annot
//----------------------------------------------------------------
static mupdf::PdfAnnot _add_caret_annot(mupdf::PdfPage& page, mupdf::FzPoint& point)
{
    mupdf::PdfAnnot annot = mupdf::pdf_create_annot(page, ::PDF_ANNOT_CARET);
    mupdf::FzPoint  p = point;
    mupdf::FzRect   r = mupdf::pdf_annot_rect(annot);
    r = mupdf::fz_make_rect(p.x, p.y, p.x + r.x1 - r.x0, p.y + r.y1 - r.y0);
    mupdf::pdf_set_annot_rect(annot, r);
    mupdf::pdf_update_annot(annot);
    JM_add_annot_id(annot, "A");
    return annot;
}

static mupdf::PdfAnnot _add_caret_annot(mupdf::FzPage& page, mupdf::FzPoint& point)
{
    mupdf::PdfPage  pdf_page = mupdf::pdf_page_from_fz_page(page);
    return _add_caret_annot(pdf_page, point);
}

static const char* Tools_parse_da(mupdf::PdfAnnot& this_annot)
{
    const char* da_str = nullptr;
    mupdf::PdfObj this_annot_obj = mupdf::pdf_annot_obj(this_annot);
    mupdf::PdfDocument pdf = mupdf::pdf_get_bound_document(this_annot_obj);
    try
    {
        mupdf::PdfObj da = mupdf::pdf_dict_get_inheritable(this_annot_obj, PDF_NAME2(DA));
        if (!da.m_internal)
        {
            mupdf::PdfObj trailer = mupdf::pdf_trailer(pdf);
            da = mupdf::pdf_dict_getl(
                    &trailer,
                    PDF_NAME(Root),
                    PDF_NAME(AcroForm),
                    PDF_NAME(DA),
                    nullptr
                    );
        }
        da_str = mupdf::pdf_to_text_string(da);
    }
    catch (std::exception&)
    {
        return nullptr;
    }
    return da_str;
}

//----------------------------------------------------------------------------
// Turn fz_buffer into a Python bytes object
//----------------------------------------------------------------------------
static PyObject* JM_BinFromBuffer(fz_buffer* buffer)
{
    if (!buffer)
    {
        return PyBytes_FromStringAndSize("", 0);
    }
    unsigned char* c = nullptr;
    size_t len = mupdf::ll_fz_buffer_storage(buffer, &c);
    return PyBytes_FromStringAndSize((const char*) c, len);
}
static PyObject* JM_BinFromBuffer(mupdf::FzBuffer& buffer)
{
    return JM_BinFromBuffer( buffer.m_internal);
}

static PyObject* Annot_getAP(mupdf::PdfAnnot& annot)
{
    mupdf::PdfObj annot_obj = mupdf::pdf_annot_obj(annot);
    mupdf::PdfObj ap = mupdf::pdf_dict_getl(
            &annot_obj,
            PDF_NAME(AP),
            PDF_NAME(N),
            nullptr
            );
    if (mupdf::pdf_is_stream(ap))
    {
        mupdf::FzBuffer res = mupdf::pdf_load_stream(ap);
        return JM_BinFromBuffer(res);
    }
    return PyBytes_FromStringAndSize("", 0);
}

void Tools_update_da(mupdf::PdfAnnot& this_annot, const char* da_str)
{
    mupdf::PdfObj this_annot_obj = mupdf::pdf_annot_obj(this_annot);
    mupdf::pdf_dict_put_text_string(this_annot_obj, PDF_NAME2(DA), da_str);
    mupdf::pdf_dict_del(this_annot_obj, PDF_NAME2(DS)); /* not supported */
    mupdf::pdf_dict_del(this_annot_obj, PDF_NAME2(RC)); /* not supported */
}

static int
jm_float_item(PyObject* obj, Py_ssize_t idx, double* result)
{
    PyObject* temp = PySequence_ITEM(obj, idx);
    if (!temp) return 1;
    *result = PyFloat_AsDouble(temp);
    Py_DECREF(temp);
    if (PyErr_Occurred())
    {
        PyErr_Clear();
        return 1;
    }
    return 0;
}


static mupdf::FzPoint JM_point_from_py(PyObject* p)
{
    fz_point p0 = fz_make_point(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT);
    if (!p || !PySequence_Check(p) || PySequence_Size(p) != 2)
    {
        return p0;
    }
    double x;
    double y;
    if (jm_float_item(p, 0, &x) == 1) return p0;
    if (jm_float_item(p, 1, &y) == 1) return p0;
    if (x < FZ_MIN_INF_RECT) x = FZ_MIN_INF_RECT;
    if (y < FZ_MIN_INF_RECT) y = FZ_MIN_INF_RECT;
    if (x > FZ_MAX_INF_RECT) x = FZ_MAX_INF_RECT;
    if (y > FZ_MAX_INF_RECT) y = FZ_MAX_INF_RECT;

    return fz_make_point(x, y);
}

static int s_list_append_drop(PyObject* list, PyObject* item)
{
    if (!list || !PyList_Check(list) || !item)
    {
        return -2;
    }
    int rc = PyList_Append(list, item);
    Py_DECREF(item);
    return rc;
}

static int LIST_APPEND_DROP(PyObject *list, PyObject *item)
{
    if (!list || !PyList_Check(list) || !item) return -2;
    int rc = PyList_Append(list, item);
    Py_DECREF(item);
    return rc;
}

static int LIST_APPEND(PyObject *list, PyObject *item)
{
    if (!list || !PyList_Check(list) || !item) return -2;
    int rc = PyList_Append(list, item);
    return rc;
}

static int DICT_SETITEM_DROP(PyObject *dict, PyObject *key, PyObject *value)
{
    if (!dict || !PyDict_Check(dict) || !key || !value) return -2;
    int rc = PyDict_SetItem(dict, key, value);
    Py_DECREF(value);
    return rc;
}

static int DICT_SETITEMSTR_DROP(PyObject *dict, const char *key, PyObject *value)
{
    if (!dict || !PyDict_Check(dict) || !key || !value) return -2;
    int rc = PyDict_SetItemString(dict, key, value);
    Py_DECREF(value);
    return rc;
}


//-----------------------------------------------------------------------------
// Functions converting between PySequences and pymupdf geometry objects
//-----------------------------------------------------------------------------
static int
jm_init_item(PyObject* obj, Py_ssize_t idx, int* result)
{
    PyObject* temp = PySequence_ITEM(obj, idx);
    if (!temp)
    {
        return 1;
    }
    if (PyLong_Check(temp))
    {
        *result = (int) PyLong_AsLong(temp);
        Py_DECREF(temp);
    }
    else if (PyFloat_Check(temp))
    {
        *result = (int) PyFloat_AsDouble(temp);
        Py_DECREF(temp);
    }
    else
    {
        Py_DECREF(temp);
        return 1;
    }
    if (PyErr_Occurred())
    {
        PyErr_Clear();
        return 1;
    }
    return 0;
}

// TODO: ------------------------------------------------------------------
// This is a temporary solution and should be replaced by a C++ extension:
// There is no way in Python specify an array of fz_point - as is required
// for function pdf_set_annot_callout_line().
static void JM_set_annot_callout_line(mupdf::PdfAnnot& annot, PyObject *callout, int count)
{
    fz_point points[3];
    mupdf::FzPoint p;
    for (int i = 0; i < count; i++)
    {
        p = JM_point_from_py(PyTuple_GetItem(callout, (Py_ssize_t) i));
        points[i] = fz_make_point(p.x, p.y);
    }
    mupdf::pdf_set_annot_callout_line(annot, points, count);
}


//----------------------------------------------------------------------------
// Return list of outline xref numbers. Recursive function. Arguments:
// 'obj' first OL item
// 'xrefs' empty Python list
//----------------------------------------------------------------------------
static PyObject* JM_outline_xrefs(mupdf::PdfObj obj, PyObject* xrefs)
{
    if (!obj.m_internal)
    {
        return xrefs;
    }
    PyObject* newxref = nullptr;
    mupdf::PdfObj thisobj = obj;
    while (thisobj.m_internal)
    {
        int nxr = mupdf::pdf_to_num(thisobj);
        newxref = PyLong_FromLong((long) nxr);
        if (PySequence_Contains(xrefs, newxref)
                or mupdf::pdf_dict_get(thisobj, PDF_NAME2(Type)).m_internal
                )
        {
            // circular ref or top of chain: terminate
            Py_DECREF(newxref);
            break;
        }
        s_list_append_drop(xrefs, newxref);
        mupdf::PdfObj first = mupdf::pdf_dict_get(thisobj, PDF_NAME2(First));  // try go down
        if (mupdf::pdf_is_dict(first))
        {
            xrefs = JM_outline_xrefs(first, xrefs);
        }
        thisobj = mupdf::pdf_dict_get(thisobj, PDF_NAME2(Next));  // try go next
        mupdf::PdfObj parent = mupdf::pdf_dict_get(thisobj, PDF_NAME2(Parent));  // get parent
        if (!mupdf::pdf_is_dict(thisobj))
        {
            thisobj = parent;
        }
    }
    return xrefs;
}


PyObject* dictkey_align = NULL;
PyObject* dictkey_ascender = NULL;
PyObject* dictkey_bidi = NULL;
PyObject* dictkey_bbox = NULL;
PyObject* dictkey_blocks = NULL;
PyObject* dictkey_bpc = NULL;
PyObject* dictkey_c = NULL;
PyObject* dictkey_chars = NULL;
PyObject* dictkey_color = NULL;
PyObject* dictkey_colorspace = NULL;
PyObject* dictkey_content = NULL;
PyObject* dictkey_creationDate = NULL;
PyObject* dictkey_cs_name = NULL;
PyObject* dictkey_da = NULL;
PyObject* dictkey_dashes = NULL;
PyObject* dictkey_desc = NULL;
PyObject* dictkey_descender = NULL;
PyObject* dictkey_dir = NULL;
PyObject* dictkey_effect = NULL;
PyObject* dictkey_ext = NULL;
PyObject* dictkey_filename = NULL;
PyObject* dictkey_fill = NULL;
PyObject* dictkey_flags = NULL;
PyObject* dictkey_char_bidi = NULL;
PyObject* dictkey_char_flags = NULL;
PyObject* dictkey_font = NULL;
PyObject* dictkey_glyph = NULL;
PyObject* dictkey_height = NULL;
PyObject* dictkey_id = NULL;
PyObject* dictkey_image = NULL;
PyObject* dictkey_items = NULL;
PyObject* dictkey_length = NULL;
PyObject* dictkey_lines = NULL;
PyObject* dictkey_matrix = NULL;
PyObject* dictkey_modDate = NULL;
PyObject* dictkey_name = NULL;
PyObject* dictkey_number = NULL;
PyObject* dictkey_origin = NULL;
PyObject* dictkey_rect = NULL;
PyObject* dictkey_size = NULL;
PyObject* dictkey_smask = NULL;
PyObject* dictkey_spans = NULL;
PyObject* dictkey_stroke = NULL;
PyObject* dictkey_style = NULL;
PyObject* dictkey_subject = NULL;
PyObject* dictkey_text = NULL;
PyObject* dictkey_title = NULL;
PyObject* dictkey_type = NULL;
PyObject* dictkey_ufilename = NULL;
PyObject* dictkey_width = NULL;
PyObject* dictkey_wmode = NULL;
PyObject* dictkey_xref = NULL;
PyObject* dictkey_xres = NULL;
PyObject* dictkey_yres = NULL;

static int dict_setitem_drop(PyObject* dict, PyObject* key, PyObject* value)
{
    if (!dict || !PyDict_Check(dict) || !key || !value)
    {
        return -2;
    }
    int rc = PyDict_SetItem(dict, key, value);
    Py_DECREF(value);
    return rc;
}

static int dict_setitemstr_drop(PyObject* dict, const char* key, PyObject* value)
{
    if (!dict || !PyDict_Check(dict) || !key || !value)
    {
        return -2;
    }
    int rc = PyDict_SetItemString(dict, key, value);
    Py_DECREF(value);
    return rc;
}


static void Document_extend_toc_items(mupdf::PdfDocument& pdf, PyObject* items)
{
    PyObject* item=nullptr;
    PyObject* itemdict=nullptr;
    PyObject* xrefs=nullptr;
    
    PyObject* bold = PyUnicode_FromString("bold");
    PyObject* italic = PyUnicode_FromString("italic");
    PyObject* collapse = PyUnicode_FromString("collapse");
    PyObject* zoom = PyUnicode_FromString("zoom");
    
    try
    {
        /* Need to define these things early because later code uses
        `goto`; otherwise we get compiler warnings 'jump bypasses variable
        initialization' */
        int xref = 0;
        mupdf::PdfObj   root;
        mupdf::PdfObj   olroot;
        mupdf::PdfObj   first;
        Py_ssize_t  n;
        Py_ssize_t  m;
        
        root = mupdf::pdf_dict_get(mupdf::pdf_trailer(pdf), PDF_NAME2(Root));
        if (!root.m_internal) goto end;
        
        olroot = mupdf::pdf_dict_get(root, PDF_NAME2(Outlines));
        if (!olroot.m_internal) goto end;
        
        first = mupdf::pdf_dict_get(olroot, PDF_NAME2(First));
        if (!first.m_internal) goto end;
        
        xrefs = PyList_New(0);  // pre-allocate an empty list
        xrefs = JM_outline_xrefs(first, xrefs);
        n = PySequence_Size(xrefs);
        m = PySequence_Size(items);
        if (!n) goto end;
        
        if (n != m)
        {
            throw std::runtime_error("internal error finding outline xrefs");
        }

        // update all TOC item dictionaries
        for (int i = 0; i < n; i++)
        {
            jm_init_item(xrefs, i, &xref);
            item = PySequence_ITEM(items, i);
            itemdict = PySequence_ITEM(item, 3);
            if (!itemdict || !PyDict_Check(itemdict))
            {
                throw std::runtime_error("need non-simple TOC format");
            }
            PyDict_SetItem(itemdict, dictkey_xref, PySequence_ITEM(xrefs, i));
            mupdf::PdfObj bm = mupdf::pdf_load_object(pdf, xref);
            int flags = mupdf::pdf_to_int(mupdf::pdf_dict_get(bm, PDF_NAME2(F)));
            if (flags == 1)
            {
                PyDict_SetItem(itemdict, italic, Py_True);
            }
            else if (flags == 2)
            {
                PyDict_SetItem(itemdict, bold, Py_True);
            }
            else if (flags == 3)
            {
                PyDict_SetItem(itemdict, italic, Py_True);
                PyDict_SetItem(itemdict, bold, Py_True);
            }
            int count = mupdf::pdf_to_int(mupdf::pdf_dict_get(bm, PDF_NAME2(Count)));
            if (count < 0)
            {
                PyDict_SetItem(itemdict, collapse, Py_True);
            }
            else if (count > 0)
            {
                PyDict_SetItem(itemdict, collapse, Py_False);
            }
            mupdf::PdfObj col = mupdf::pdf_dict_get(bm, PDF_NAME2(C));
            if (mupdf::pdf_is_array(col) && mupdf::pdf_array_len(col) == 3)
            {
                PyObject* color = PyTuple_New(3);
                PyTuple_SET_ITEM(color, 0, Py_BuildValue("f", mupdf::pdf_to_real(mupdf::pdf_array_get(col, 0))));
                PyTuple_SET_ITEM(color, 1, Py_BuildValue("f", mupdf::pdf_to_real(mupdf::pdf_array_get(col, 1))));
                PyTuple_SET_ITEM(color, 2, Py_BuildValue("f", mupdf::pdf_to_real(mupdf::pdf_array_get(col, 2))));
                dict_setitem_drop(itemdict, dictkey_color, color);
            }
            float z=0;
            mupdf::PdfObj obj = mupdf::pdf_dict_get(bm, PDF_NAME2(Dest));
            if (!obj.m_internal || !mupdf::pdf_is_array(obj))
            {
                obj = mupdf::pdf_dict_getl(&bm, PDF_NAME(A), PDF_NAME(D), nullptr);
            }
            if (mupdf::pdf_is_array(obj) && mupdf::pdf_array_len(obj) == 5)
            {
                z = mupdf::pdf_to_real(mupdf::pdf_array_get(obj, 4));
            }
            dict_setitem_drop(itemdict, zoom, Py_BuildValue("f", z));
            PyList_SetItem(item, 3, itemdict);
            PyList_SetItem(items, i, item);
        }
        end:;
    }
    catch (std::exception&)
    {
    }
    Py_CLEAR(xrefs);
    Py_CLEAR(bold);
    Py_CLEAR(italic);
    Py_CLEAR(collapse);
    Py_CLEAR(zoom);
}

static void Document_extend_toc_items(mupdf::FzDocument& document, PyObject* items)
{
    mupdf::PdfDocument  pdf = mupdf::pdf_document_from_fz_document(document);
    return Document_extend_toc_items(pdf, items);
}

//-----------------------------------------------------------------------------
// PySequence from fz_rect
//-----------------------------------------------------------------------------
static PyObject* JM_py_from_rect(fz_rect r)
{
    return Py_BuildValue("ffff", r.x0, r.y0, r.x1, r.y1);
}
static PyObject* JM_py_from_rect(mupdf::FzRect r)
{
    return JM_py_from_rect(*r.internal());
}

//-----------------------------------------------------------------------------
// PySequence from fz_point
//-----------------------------------------------------------------------------
static PyObject* JM_py_from_point(fz_point p)
{
    return Py_BuildValue("ff", p.x, p.y);
}

//-----------------------------------------------------------------------------
// PySequence from fz_quad.
//-----------------------------------------------------------------------------
static PyObject *
JM_py_from_quad(fz_quad q)
{
    return Py_BuildValue("((f,f),(f,f),(f,f),(f,f))",
                          q.ul.x, q.ul.y, q.ur.x, q.ur.y,
                          q.ll.x, q.ll.y, q.lr.x, q.lr.y);
}

//----------------------------------------------------------------
// annotation rectangle
//----------------------------------------------------------------
static mupdf::FzRect Annot_rect(mupdf::PdfAnnot& annot)
{
    mupdf::FzRect rect = mupdf::pdf_bound_annot(annot);
    return rect;
}

static PyObject* Annot_rect3(mupdf::PdfAnnot& annot)
{
    fz_rect rect = mupdf::ll_pdf_bound_annot(annot.m_internal);
    return JM_py_from_rect(rect);
}

//-----------------------------------------------------------------------------
// PySequence to fz_rect. Default: infinite rect
//-----------------------------------------------------------------------------
static fz_rect JM_rect_from_py(PyObject* r)
{
    if (!r || !PySequence_Check(r) || PySequence_Size(r) != 4)
    {
        return *mupdf::FzRect(mupdf::FzRect::Fixed_INFINITE).internal();// fz_infinite_rect;
    }
    double f[4];
    for (int i = 0; i < 4; i++)
    {
        if (jm_float_item(r, i, &f[i]) == 1)
        {
            return *mupdf::FzRect(mupdf::FzRect::Fixed_INFINITE).internal();
        }
        if (f[i] < FZ_MIN_INF_RECT) f[i] = FZ_MIN_INF_RECT;
        if (f[i] > FZ_MAX_INF_RECT) f[i] = FZ_MAX_INF_RECT;
    }
    return mupdf::ll_fz_make_rect(
            (float) f[0],
            (float) f[1],
            (float) f[2],
            (float) f[3]
            );
}

//-----------------------------------------------------------------------------
// PySequence to fz_matrix. Default: fz_identity
//-----------------------------------------------------------------------------
static fz_matrix JM_matrix_from_py(PyObject* m)
{
    double a[6];

    if (!m || !PySequence_Check(m) || PySequence_Size(m) != 6)
    {
        return fz_identity;
    }
    for (int i = 0; i < 6; i++)
    {
        if (jm_float_item(m, i, &a[i]) == 1)
        {
            return *mupdf::FzMatrix().internal();
        }
    }
    return mupdf::ll_fz_make_matrix(
            (float) a[0],
            (float) a[1],
            (float) a[2],
            (float) a[3],
            (float) a[4],
            (float) a[5]
            );
}

PyObject* util_transform_rect(PyObject* rect, PyObject* matrix)
{
    return JM_py_from_rect(
            mupdf::ll_fz_transform_rect(
                JM_rect_from_py(rect),
                JM_matrix_from_py(matrix)
                )
            );
}

//----------------------------------------------------------------------------
// return normalized /Rotate value:one of 0, 90, 180, 270
//----------------------------------------------------------------------------
static int JM_norm_rotation(int rotate)
{
    while (rotate < 0) rotate += 360;
    while (rotate >= 360) rotate -= 360;
    if (rotate % 90 != 0) return 0;
    return rotate;
}


//----------------------------------------------------------------------------
// return a PDF page's /Rotate value: one of (0, 90, 180, 270)
//----------------------------------------------------------------------------
static int JM_page_rotation(mupdf::PdfPage& page)
{
    int rotate = 0;
    rotate = mupdf::pdf_to_int(
            mupdf::pdf_dict_get_inheritable(page.obj(), PDF_NAME2(Rotate))
            );
    rotate = JM_norm_rotation(rotate);
    return rotate;
}


//----------------------------------------------------------------------------
// return a PDF page's MediaBox
//----------------------------------------------------------------------------
static mupdf::FzRect JM_mediabox(mupdf::PdfObj& page_obj)
{
    mupdf::FzRect mediabox = mupdf::pdf_to_rect(
            mupdf::pdf_dict_get_inheritable(page_obj, PDF_NAME2(MediaBox))
            );
    if (mupdf::fz_is_empty_rect(mediabox) || mupdf::fz_is_infinite_rect(mediabox))
    {
        mediabox.x0 = 0;
        mediabox.y0 = 0;
        mediabox.x1 = 612;
        mediabox.y1 = 792;
    }
    mupdf::FzRect   page_mediabox;
    page_mediabox.x0 = mupdf::fz_min(mediabox.x0, mediabox.x1);
    page_mediabox.y0 = mupdf::fz_min(mediabox.y0, mediabox.y1);
    page_mediabox.x1 = mupdf::fz_max(mediabox.x0, mediabox.x1);
    page_mediabox.y1 = mupdf::fz_max(mediabox.y0, mediabox.y1);
    if (0
            || page_mediabox.x1 - page_mediabox.x0 < 1
            || page_mediabox.y1 - page_mediabox.y0 < 1
            )
    {
        page_mediabox = *mupdf::FzRect(mupdf::FzRect::Fixed_UNIT).internal(); //fz_unit_rect;
    }
    return page_mediabox;
}


//----------------------------------------------------------------------------
// return a PDF page's CropBox
//----------------------------------------------------------------------------
mupdf::FzRect JM_cropbox(mupdf::PdfObj& page_obj)
{
    mupdf::FzRect mediabox = JM_mediabox(page_obj);
    mupdf::FzRect cropbox = mupdf::pdf_to_rect(
                mupdf::pdf_dict_get_inheritable(page_obj, PDF_NAME2(CropBox))
                );
    if (mupdf::fz_is_infinite_rect(cropbox) || mupdf::fz_is_empty_rect(cropbox))
    {
        cropbox = mediabox;
    }
    float y0 = mediabox.y1 - cropbox.y1;
    float y1 = mediabox.y1 - cropbox.y0;
    cropbox.y0 = y0;
    cropbox.y1 = y1;
    return cropbox;
}


//----------------------------------------------------------------------------
// calculate width and height of the UNROTATED page
//----------------------------------------------------------------------------
static mupdf::FzPoint JM_cropbox_size(mupdf::PdfObj& page_obj)
{
    mupdf::FzPoint size;
    mupdf::FzRect rect = JM_cropbox(page_obj);
    float w = (rect.x0 < rect.x1) ? rect.x1 - rect.x0 : rect.x0 - rect.x1;
    float h = (rect.y0 < rect.y1) ? rect.y1 - rect.y0 : rect.y0 - rect.y1;
    size = fz_make_point(w, h);
    return size;
}


//----------------------------------------------------------------------------
// calculate page rotation matrices
//----------------------------------------------------------------------------
static mupdf::FzMatrix JM_rotate_page_matrix(mupdf::PdfPage& page)
{
    if (!page.m_internal)
    {
        return *mupdf::FzMatrix().internal();  // no valid pdf page given
    }
    int rotation = JM_page_rotation(page);
    if (rotation == 0)
    {
        return *mupdf::FzMatrix().internal();  // no rotation
    }
    auto po = page.obj();
    mupdf::FzPoint cb_size = JM_cropbox_size(po);
    float w = cb_size.x;
    float h = cb_size.y;
    mupdf::FzMatrix m;
    if (rotation == 90)
    {
        m = mupdf::fz_make_matrix(0, 1, -1, 0, h, 0);
    }
    else if (rotation == 180)
    {
        m = mupdf::fz_make_matrix(-1, 0, 0, -1, w, h);
    }
    else
    {
        m = mupdf::fz_make_matrix(0, -1, 1, 0, 0, w);
    }
    return m;
}


static mupdf::FzMatrix JM_derotate_page_matrix(mupdf::PdfPage& page)
{  // just the inverse of rotation
    return mupdf::fz_invert_matrix(JM_rotate_page_matrix(page));
}

//-----------------------------------------------------------------------------
// PySequence from fz_matrix
//-----------------------------------------------------------------------------
static PyObject* JM_py_from_matrix(mupdf::FzMatrix m)
{
    return Py_BuildValue("ffffff", m.a, m.b, m.c, m.d, m.e, m.f);
}

static mupdf::FzMatrix Page_derotate_matrix(mupdf::PdfPage& pdfpage)
{
    if (!pdfpage.m_internal)
    {
        return mupdf::FzMatrix();
    }
    return JM_derotate_page_matrix(pdfpage);
}

static mupdf::FzMatrix Page_derotate_matrix(mupdf::FzPage& page)
{
    mupdf::PdfPage pdf_page = mupdf::pdf_page_from_fz_page(page);
    return Page_derotate_matrix(pdf_page);
}


static PyObject *lll_JM_get_annot_xref_list(pdf_obj *page_obj)
{
    fz_context* ctx = mupdf::internal_context_get();
    PyObject *names = PyList_New(0);
    pdf_obj *id, *subtype, *annots, *annot_obj;
    int xref, type, i, n;
    fz_try(ctx) {
        annots = pdf_dict_get(ctx, page_obj, PDF_NAME(Annots));
        n = pdf_array_len(ctx, annots);
        for (i = 0; i < n; i++) {
            annot_obj = pdf_array_get(ctx, annots, i);
            xref = pdf_to_num(ctx, annot_obj);
            subtype = pdf_dict_get(ctx, annot_obj, PDF_NAME(Subtype));
            if (!subtype) {
                continue;  // subtype is required
            }
            type = pdf_annot_type_from_string(ctx, pdf_to_name(ctx, subtype));
            if (type == PDF_ANNOT_UNKNOWN) {
                continue;  // only accept valid annot types
            }
            id = pdf_dict_gets(ctx, annot_obj, "NM");
            LIST_APPEND_DROP(names, Py_BuildValue("iis", xref, type, pdf_to_text_string(ctx, id)));
        }
    }
    fz_catch(ctx) {
        return names;
    }
    return names;
}
//------------------------------------------------------------------------
// return the xrefs and /NM ids of a page's annots, links and fields
//------------------------------------------------------------------------
static PyObject* JM_get_annot_xref_list(const mupdf::PdfObj& page_obj)
{
    if (!page_obj.m_internal)
    {
        PyObject* names = PyList_New(0);
        return names;
    }
    return lll_JM_get_annot_xref_list( page_obj.m_internal);
}

static mupdf::FzBuffer JM_object_to_buffer(const mupdf::PdfObj& what, int compress, int ascii)
{
    mupdf::FzBuffer res = mupdf::fz_new_buffer(512);
    mupdf::FzOutput out(res);
    mupdf::pdf_print_obj(out, what, compress, ascii);
    out.fz_close_output();
    mupdf::fz_terminate_buffer(res);
    return res;
}

static PyObject* JM_EscapeStrFromBuffer(mupdf::FzBuffer& buff)
{
    if (!buff.m_internal)
    {
        return PyUnicode_FromString("");
    }
    unsigned char* s = nullptr;
    size_t len = mupdf::fz_buffer_storage(buff, &s);
    PyObject* val = PyUnicode_DecodeRawUnicodeEscape((const char*) s, (Py_ssize_t) len, "replace");
    if (!val)
    {
        val = PyUnicode_FromString("");
        PyErr_Clear();
    }
    return val;
}

static PyObject* xref_object(mupdf::PdfDocument& pdf, int xref, int compressed=0, int ascii=0)
{
    if (!pdf.m_internal)
    {
        throw std::runtime_error(MSG_IS_NO_PDF);
    }
    int xreflen = mupdf::pdf_xref_len(pdf);
    if ((xref < 1 || xref >= xreflen) and xref != -1) 
    {
        throw std::runtime_error(MSG_BAD_XREF);
    }
    mupdf::PdfObj obj = (xref > 0) ? mupdf::pdf_load_object(pdf, xref) : mupdf::pdf_trailer(pdf);
    mupdf::FzBuffer res = JM_object_to_buffer(mupdf::pdf_resolve_indirect(obj), compressed, ascii);
    PyObject* text = JM_EscapeStrFromBuffer(res);
    return text;
}

static PyObject* xref_object(mupdf::FzDocument& document, int xref, int compressed=0, int ascii=0)
{
    mupdf::PdfDocument pdf = mupdf::pdf_document_from_fz_document(document);
    return xref_object(pdf, xref, compressed, ascii);
}


//-------------------------------------
// fz_output for Python file objects
//-------------------------------------

static PyObject* Link_is_external(mupdf::FzLink& this_link)
{
    const char* uri = this_link.m_internal->uri;
    if (!uri)
    {
        return PyBool_FromLong(0);
    }
    bool ret = mupdf::fz_is_external_link(uri);
    return PyBool_FromLong((long) ret);
}

static mupdf::FzLink Link_next(mupdf::FzLink& this_link)
{
    return this_link.next();
}


//-----------------------------------------------------------------------------
// create PDF object from given string
//-----------------------------------------------------------------------------
static pdf_obj *lll_JM_pdf_obj_from_str(fz_context *ctx, pdf_document *doc, const char *src)
{
    pdf_obj *result = NULL;
    pdf_lexbuf lexbuf;
    fz_stream *stream = fz_open_memory(ctx, (unsigned char *)src, strlen(src));

    pdf_lexbuf_init(ctx, &lexbuf, PDF_LEXBUF_SMALL);

    fz_try(ctx) {
        result = pdf_parse_stm_obj(ctx, doc, stream, &lexbuf);
    }

    fz_always(ctx) {
        pdf_lexbuf_fin(ctx, &lexbuf);
        fz_drop_stream(ctx, stream);
    }

    fz_catch(ctx) {
        mupdf::internal_throw_exception(ctx);
    }

    return result;

}

/*********************************************************************/
// Page._addAnnot_FromString
// Add new links provided as an array of string object definitions.
/*********************************************************************/
PyObject* Page_addAnnot_FromString(mupdf::PdfPage& page, PyObject* linklist)
{
    PyObject* txtpy = nullptr;
    int lcount = (int) PySequence_Size(linklist); // link count
    //printf("Page_addAnnot_FromString(): lcount=%i\n", lcount);
    if (lcount < 1)
    {
        Py_RETURN_NONE;
    }
    try
    {
        // insert links from the provided sources
        if (!page.m_internal)
        {
            throw std::runtime_error(MSG_IS_NO_PDF);
        }
        if (!mupdf::pdf_dict_get(page.obj(), PDF_NAME2(Annots)).m_internal)
        {
            mupdf::pdf_dict_put_array(page.obj(), PDF_NAME2(Annots), lcount);
        }
        mupdf::PdfObj annots = mupdf::pdf_dict_get(page.obj(), PDF_NAME2(Annots));
        mupdf::PdfDocument doc = page.doc();
        //printf("lcount=%i\n", lcount);
        fz_context* ctx = mupdf::internal_context_get();
        for (int i = 0; i < lcount; i++)
        {
            const char* text = nullptr;
            txtpy = PySequence_ITEM(linklist, (Py_ssize_t) i);
            text = PyUnicode_AsUTF8(txtpy);
            Py_CLEAR(txtpy);
            if (!text)
            {
                messagef("skipping bad link / annot item %i.", i);
                continue;
            }
            try
            {
                pdf_obj* obj = lll_JM_pdf_obj_from_str(ctx, doc.m_internal, text);
                pdf_obj* annot = pdf_add_object_drop(
                        ctx,
                        doc.m_internal,
                        obj
                        );
                pdf_obj* ind_obj = pdf_new_indirect(ctx, doc.m_internal, pdf_to_num(ctx, annot), 0);
                pdf_array_push_drop(ctx, annots.m_internal, ind_obj);
                pdf_drop_obj(ctx, annot);
             }
            catch (std::exception&)
            {
                messagef("skipping bad link / annot item %i.", i);
            }
        }
    }
    catch (std::exception&)
    {
        PyErr_Clear();
        return nullptr;
    }
    Py_RETURN_NONE;
}

PyObject* Page_addAnnot_FromString(mupdf::FzPage& page, PyObject* linklist)
{
    mupdf::PdfPage pdf_page = mupdf::pdf_page_from_fz_page(page);
    return Page_addAnnot_FromString(pdf_page, linklist);
}

static int page_count_fz2(void* document)
{
    mupdf::FzDocument* document2 = (mupdf::FzDocument*) document;
    return mupdf::fz_count_pages(*document2);
}

static int page_count_fz(mupdf::FzDocument& document)
{
    return mupdf::fz_count_pages(document);
}

static int page_count_pdf(mupdf::PdfDocument& pdf)
{
    mupdf::FzDocument document = pdf.super();
    return page_count_fz(document);
}

static int page_count(mupdf::FzDocument& document)
{
    return mupdf::fz_count_pages(document);
}

static int page_count(mupdf::PdfDocument& pdf)
{
    mupdf::FzDocument document = pdf.super();
    return page_count(document);
}

static PyObject* page_annot_xrefs(mupdf::FzDocument& document, mupdf::PdfDocument& pdf, int pno)
{
    int page_count = mupdf::fz_count_pages(document);
    int n = pno;
    while (n < 0)
    {
        n += page_count;
    }
    PyObject* annots = nullptr;
    if (n >= page_count)
    {
        throw std::runtime_error(MSG_BAD_PAGENO);
    }
    if (!pdf.m_internal)
    {
        throw std::runtime_error(MSG_IS_NO_PDF);
    }
    annots = JM_get_annot_xref_list(mupdf::pdf_lookup_page_obj(pdf, n));
    return annots;
}

static PyObject* page_annot_xrefs(mupdf::FzDocument& document, int pno)
{
    mupdf::PdfDocument pdf = mupdf::pdf_specifics(document);
    return page_annot_xrefs(document, pdf, pno);
}

static PyObject* page_annot_xrefs(mupdf::PdfDocument& pdf, int pno)
{
    mupdf::FzDocument document = pdf.super();
    return page_annot_xrefs(document, pdf, pno);
}

static bool Outline_is_external(mupdf::FzOutline* outline)
{
    if (!outline->m_internal->uri)
    {
        return false;
    }
    return mupdf::ll_fz_is_external_link(outline->m_internal->uri);
}

int ll_fz_absi(int i)
{
    return mupdf::ll_fz_absi(i);
}

enum
{
    TEXT_FONT_SUPERSCRIPT = 1,
    TEXT_FONT_ITALIC = 2,
    TEXT_FONT_SERIFED = 4,
    TEXT_FONT_MONOSPACED = 8,
    TEXT_FONT_BOLD = 16,
};

int g_skip_quad_corrections = 0;
int g_subset_fontnames = 0;
int g_small_glyph_heights = 0;

void set_skip_quad_corrections(int on)
{
    g_skip_quad_corrections = on;
}

void set_subset_fontnames(int on)
{
    g_subset_fontnames = on;
}

void set_small_glyph_heights(int on)
{
    g_small_glyph_heights = on;
}

struct jm_lineart_device
{
    fz_device super;
    
    PyObject* out = {};
    PyObject* method = {};
    PyObject* pathdict = {};
    PyObject* scissors = {};
    float pathfactor = {};
    fz_matrix ctm = {};
    fz_matrix ptm = {};
    fz_matrix rot = {};
    fz_point lastpoint = {};
    fz_point firstpoint = {};
    int havemove = 0;
    fz_rect pathrect = {};
    int clips = {};
    int linecount = {};
    int path_type = {};
    long depth = {};
    size_t seqno = {};
    char* layer_name;
};


static void jm_lineart_drop_device(fz_context *ctx, fz_device *dev_)
{
    jm_lineart_device *dev = (jm_lineart_device *)dev_;
    if (PyList_Check(dev->out)) {
        Py_CLEAR(dev->out);
    }
    Py_CLEAR(dev->method);
    Py_CLEAR(dev->scissors);
    mupdf::ll_fz_free(dev->layer_name);
    dev->layer_name = nullptr;
}

typedef jm_lineart_device jm_tracedraw_device;

// need own versions of ascender / descender
static float JM_font_ascender(fz_font* font)
{
    if (g_skip_quad_corrections)
    {
        return 0.8f;
    }
    return mupdf::ll_fz_font_ascender(font);
}

static float JM_font_descender(fz_font* font)
{
    if (g_skip_quad_corrections)
    {
        return -0.2f;
    }
    return mupdf::ll_fz_font_descender(font);
}


//----------------------------------------------------------------
// Return true if character is considered to be a word delimiter
//----------------------------------------------------------------
static int 
JM_is_word_delimiter(int c, PyObject *delimiters)
{
    if (c <= 32 || c == 160) return 1;  // a standard delimiter
    if (0x202a <= c && c <= 0x202e)
    {
        return 1; // change between writing directions
    }

    // extra delimiters must be a non-empty sequence
    if (!delimiters || PyObject_Not(delimiters) || !PySequence_Check(delimiters)) {  
        return 0;
    }

    // convert to tuple for easier looping
    PyObject *delims = PySequence_Tuple(delimiters);
    if (!delims) {
        PyErr_Clear();
        return 0;
    }

    // Make 1-char PyObject from character given as integer
    PyObject *cchar = Py_BuildValue("C", c);  // single character PyObject
    Py_ssize_t i, len = PyTuple_Size(delims);
    for (i = 0; i < len; i++) {
        int rc = PyUnicode_Compare(cchar, PyTuple_GET_ITEM(delims, i));
        if (rc == 0) {  // equal to a delimiter character
            Py_DECREF(cchar);
            Py_DECREF(delims);
            PyErr_Clear();
            return 1;
        }
    }

    Py_DECREF(delims);
    PyErr_Clear();
    return 0;
}

static int 
JM_is_rtl_char(int c)
{
    if (c < 0x590 || c > 0x900) return 0;
    return 1;
}

static const char* JM_font_name(fz_font* font)
{
    const char* name = mupdf::ll_fz_font_name(font);
    const char* s = strchr(name, '+');
    if (g_subset_fontnames || !s || s-name != 6)
    {
        return name;
    }
    return s + 1;
}

static void jm_trace_text_span(
        jm_tracedraw_device* dev,
        fz_text_span* span,
        int type,
        fz_matrix ctm,
        fz_colorspace* colorspace,
        const float* color,
        float alpha,
        size_t seqno,
        const fz_stroke_state* stroke
        )
{
    //printf("extra.jm_trace_text_span(): seqno=%zi\n", seqno);
    //fz_matrix join = mupdf::ll_fz_concat(span->trm, ctm);
    //double fsize = sqrt(fabs((double) span->trm.a * (double) span->trm.d));
    fz_matrix mat = mupdf::ll_fz_concat(span->trm, ctm); // text transformation matrix
    fz_point dir = mupdf::ll_fz_transform_vector(mupdf::ll_fz_make_point(1, 0), mat); // writing direction
    double fsize = sqrt(dir.x * dir.x + dir.y * dir.y); // font size

    dir = mupdf::ll_fz_normalize_vector(dir);

    // compute effective ascender / descender
    double asc = (double) JM_font_ascender(span->font);
    double dsc = (double) JM_font_descender(span->font);
    if (asc < 1e-3) {  // probably Tesseract font
        dsc = -0.1;
        asc = 0.9;
    }

    double ascsize = asc * fsize / (asc - dsc);
    double dscsize = dsc * fsize / (asc - dsc);
    int fflags = 0; // font flags
    int mono = mupdf::ll_fz_font_is_monospaced(span->font);
    fflags += mono * TEXT_FONT_MONOSPACED;
    fflags += mupdf::ll_fz_font_is_italic(span->font) * TEXT_FONT_ITALIC;
    fflags += mupdf::ll_fz_font_is_serif(span->font) * TEXT_FONT_SERIFED;
    fflags += mupdf::ll_fz_font_is_bold(span->font) * TEXT_FONT_BOLD;

    // walk through characters of span
    fz_matrix rot = mupdf::ll_fz_make_matrix(dir.x, dir.y, -dir.y, dir.x, 0, 0);
    if (dir.x == -1)
    {
        // left-right flip
        rot.d = 1;
    }
    PyObject* chars = PyTuple_New(span->len);
    double space_adv = 0;
    double last_adv = 0;
    fz_rect span_bbox;
    
    for (int i = 0; i < span->len; i++)
    {
        double adv = 0;
        if (span->items[i].gid >= 0)
        {
            adv = (double) mupdf::ll_fz_advance_glyph(span->font, span->items[i].gid, span->wmode);
        }
        adv *= fsize;
        last_adv = adv;
        if (span->items[i].ucs == 32)
        {
            space_adv = adv;
        }
        fz_point char_orig;
        char_orig = fz_make_point(span->items[i].x, span->items[i].y);
        char_orig = fz_transform_point(char_orig, ctm);
        fz_matrix m1 = mupdf::ll_fz_make_matrix(1, 0, 0, 1, -char_orig.x, -char_orig.y);
        m1 = mupdf::ll_fz_concat(m1, rot);
        m1 = mupdf::ll_fz_concat(m1, mupdf::ll_fz_make_matrix(1, 0, 0, 1, char_orig.x, char_orig.y));
        float x0 = char_orig.x;
        float x1 = x0 + adv;
        float y0;
        float y1;
        if (
                (mat.d > 0 && (dir.x == 1 || dir.x == -1))
                ||
                (mat.b !=0 && mat.b == -mat.c)
                )   // up-down flip
        {
            // up-down flip
            y0 = char_orig.y + dscsize;
            y1 = char_orig.y + ascsize;
        }
        else
        {
            y0 = char_orig.y - ascsize;
            y1 = char_orig.y - dscsize;
        }
        fz_rect char_bbox = mupdf::ll_fz_make_rect(x0, y0, x1, y1);
        char_bbox = mupdf::ll_fz_transform_rect(char_bbox, m1);
        PyTuple_SET_ITEM(
                chars,
                (Py_ssize_t) i,
                Py_BuildValue(
                    "ii(ff)(ffff)",
                    span->items[i].ucs,
                    span->items[i].gid,
                    char_orig.x,
                    char_orig.y,
                    char_bbox.x0,
                    char_bbox.y0,
                    char_bbox.x1,
                    char_bbox.y1
                    )
                );
        if (i > 0)
        {
            span_bbox = mupdf::ll_fz_union_rect(span_bbox, char_bbox);
        }
        else
        {
            span_bbox = char_bbox;
        }
    }
    if (!space_adv)
    {
        if (!(fflags & TEXT_FONT_MONOSPACED))
        {
            fz_font* out_font = nullptr;
            space_adv = mupdf::ll_fz_advance_glyph(
                    span->font,
                    mupdf::ll_fz_encode_character_with_fallback(span->font, 32, 0, 0, &out_font),
                    span->wmode
                    );
            space_adv *= fsize;
            if (!space_adv)
            {
                space_adv = last_adv;
            }
        }
        else
        {
            space_adv = last_adv; // for mono any char width suffices
        }
    }
    // make the span dictionary
    PyObject* span_dict = PyDict_New();
    dict_setitemstr_drop(span_dict, "dir", JM_py_from_point(dir));
    dict_setitem_drop(span_dict, dictkey_font, JM_EscapeStrFromStr(JM_font_name(span->font)));
    dict_setitem_drop(span_dict, dictkey_wmode, PyLong_FromLong((long) span->wmode));
    dict_setitem_drop(span_dict, dictkey_flags, PyLong_FromLong((long) fflags));
    dict_setitemstr_drop(span_dict, "bidi_lvl", PyLong_FromLong((long) span->bidi_level));
    dict_setitemstr_drop(span_dict, "bidi_dir", PyLong_FromLong((long) span->markup_dir));
    dict_setitem_drop(span_dict, dictkey_ascender, PyFloat_FromDouble(asc));
    dict_setitem_drop(span_dict, dictkey_descender, PyFloat_FromDouble(dsc));
    dict_setitem_drop(span_dict, dictkey_colorspace, PyLong_FromLong(3));
    float rgb[3];
    if (colorspace)
    {
        mupdf::ll_fz_convert_color(
                colorspace,
                color,
                mupdf::ll_fz_device_rgb(),
                rgb,
                nullptr,
                fz_default_color_params
                );
    }
    else
    {
        rgb[0] = rgb[1] = rgb[2] = 0;
    }
    if (0)
    {
        std::cout << " fsize=" << fsize;
        if (stroke)
        {
            std::cout  << " linewidth=" << stroke->linewidth;
        }
        std::cout << "\n";
    }
    dict_setitem_drop(span_dict, dictkey_color, Py_BuildValue("fff", rgb[0], rgb[1], rgb[2]));
    dict_setitem_drop(span_dict, dictkey_size, PyFloat_FromDouble(fsize));
    dict_setitemstr_drop(span_dict, "opacity", PyFloat_FromDouble((double) alpha));
    if (stroke)
        dict_setitemstr_drop(span_dict, "linewidth", PyFloat_FromDouble((double) stroke->linewidth));
    else
    {
        Py_INCREF(Py_None);
        dict_setitemstr_drop(span_dict, "linewidth", Py_None);
    }
    dict_setitemstr_drop(span_dict, "spacewidth", PyFloat_FromDouble(space_adv));
    dict_setitem_drop(span_dict, dictkey_type, PyLong_FromLong((long) type));
    dict_setitem_drop(span_dict, dictkey_bbox, JM_py_from_rect(span_bbox));
    dict_setitemstr_drop(span_dict, "layer", JM_UnicodeFromStr(dev->layer_name));
    dict_setitemstr_drop(span_dict, "seqno", PyLong_FromSize_t(seqno));
    dict_setitem_drop(span_dict, dictkey_chars, chars);
    //std::cout << "span_dict=" << repr(span_dict) << "\n";
    s_list_append_drop(dev->out, span_dict);
}

static inline void jm_increase_seqno(fz_context* ctx, fz_device* dev_)
{
    jm_tracedraw_device* dev = (jm_tracedraw_device*) dev_;
    dev->seqno += 1;
}

static void jm_fill_path(
        fz_context* ctx,
        fz_device* dev,
        const fz_path*,
        int even_odd,
        fz_matrix,
        fz_colorspace*,
        const float* color,
        float alpha,
        fz_color_params
        )
{
    jm_increase_seqno(ctx, dev);
}

static void jm_fill_shade(
        fz_context* ctx,
        fz_device* dev,
        fz_shade* shd,
        fz_matrix ctm,
        float alpha,
        fz_color_params color_params
        )
{
    jm_increase_seqno(ctx, dev);
}

static void jm_fill_image(
        fz_context* ctx,
        fz_device* dev,
        fz_image* img,
        fz_matrix ctm,
        float alpha,
        fz_color_params color_params
        )
{
    jm_increase_seqno(ctx, dev);
}

static void jm_fill_image_mask(
        fz_context* ctx,
        fz_device* dev,
        fz_image* img,
        fz_matrix ctm,
        fz_colorspace* cs,
        const float* color,
        float alpha,
        fz_color_params color_params
        )
{
    jm_increase_seqno(ctx, dev);
}

static void jm_stroke_path(
        fz_context* ctx,
        fz_device* dev_,
        const fz_path* path,
        const fz_stroke_state* stroke,
        fz_matrix ctm,
        fz_colorspace* colorspace,
        const float* color,
        float alpha,
        fz_color_params color_params
        )
{
    jm_increase_seqno(ctx, dev_);
}

static void jm_trace_text(
        jm_tracedraw_device* dev,
        const fz_text* text,
        int type,
        fz_matrix ctm,
        fz_colorspace* colorspace,
        const float* color,
        float alpha,
        size_t seqno,
        const fz_stroke_state* stroke
        )
{
    fz_text_span* span;
    for (span = text->head; span; span = span->next)
    {
        jm_trace_text_span(dev, span, type, ctm, colorspace, color, alpha, seqno, stroke);
    }
}

/*---------------------------------------------------------
There are 3 text trace types:
0 - fill text (PDF Tr 0)
1 - stroke text (PDF Tr 1)
3 - ignore text (PDF Tr 3)
---------------------------------------------------------*/
static void
jm_tracedraw_fill_text(
        fz_context* ctx,
        fz_device* dev_,
        const fz_text* text,
        fz_matrix ctm,
        fz_colorspace* colorspace,
        const float* color,
        float alpha,
        fz_color_params color_params
        )
{
    jm_tracedraw_device* dev = (jm_tracedraw_device*) dev_;
    jm_trace_text(dev, text, 0, ctm, colorspace, color, alpha, dev->seqno, NULL);
    dev->seqno += 1;
}

static void
jm_tracedraw_stroke_text(
        fz_context* ctx,
        fz_device* dev_,
        const fz_text* text,
        const fz_stroke_state* stroke,
        fz_matrix ctm,
        fz_colorspace* colorspace,
        const float* color,
        float alpha,
        fz_color_params color_params
        )
{
    jm_tracedraw_device* dev = (jm_tracedraw_device*) dev_;
    jm_trace_text(dev, text, 1, ctm, colorspace, color, alpha, dev->seqno, stroke);
    dev->seqno += 1;
}


static void
jm_tracedraw_ignore_text(
        fz_context* ctx,
        fz_device* dev_,
        const fz_text* text,
        fz_matrix ctm
        )
{
    jm_tracedraw_device* dev = (jm_tracedraw_device*) dev_;
    jm_trace_text(dev, text, 3, ctm, nullptr, nullptr, 1, dev->seqno, NULL);
    dev->seqno += 1;
}

static void
jm_lineart_begin_layer(fz_context *ctx, fz_device *dev_, const char *name)
{
    jm_tracedraw_device* dev = (jm_tracedraw_device*) dev_;
    mupdf::ll_fz_free(dev->layer_name);
    dev->layer_name = mupdf::ll_fz_strdup(name);
}

static void
jm_lineart_end_layer(fz_context *ctx, fz_device *dev_)
{
    jm_tracedraw_device* dev = (jm_tracedraw_device*) dev_;
    mupdf::ll_fz_free(dev->layer_name);
    dev->layer_name = nullptr;
}


mupdf::FzDevice JM_new_texttrace_device(PyObject* out)
{
    mupdf::FzDevice device(sizeof(jm_tracedraw_device));
    jm_tracedraw_device* dev = (jm_tracedraw_device*) device.m_internal;
    
    dev->super.close_device = nullptr;    
    dev->super.drop_device = jm_lineart_drop_device;    
    dev->super.fill_path = jm_fill_path;
    dev->super.stroke_path = jm_stroke_path;
    dev->super.clip_path = nullptr;
    dev->super.clip_stroke_path = nullptr;

    dev->super.fill_text = jm_tracedraw_fill_text;
    dev->super.stroke_text = jm_tracedraw_stroke_text;
    dev->super.clip_text = nullptr;
    dev->super.clip_stroke_text = nullptr;
    dev->super.ignore_text = jm_tracedraw_ignore_text;

    dev->super.fill_shade = jm_fill_shade;
    dev->super.fill_image = jm_fill_image;
    dev->super.fill_image_mask = jm_fill_image_mask;
    dev->super.clip_image_mask = nullptr;

    dev->super.pop_clip = nullptr;

    dev->super.begin_mask = nullptr;
    dev->super.end_mask = nullptr;
    dev->super.begin_group = nullptr;
    dev->super.end_group = nullptr;

    dev->super.begin_tile = nullptr;
    dev->super.end_tile = nullptr;

    dev->super.begin_layer = jm_lineart_begin_layer;
    dev->super.end_layer = jm_lineart_end_layer;

    dev->super.begin_structure = nullptr;
    dev->super.end_structure = nullptr;

    dev->super.begin_metatext = nullptr;
    dev->super.end_metatext = nullptr;

    dev->super.render_flags = nullptr;
    dev->super.set_default_colorspaces = nullptr;

    if (PyList_Check(out)) {
        Py_INCREF(out);
    }
    Py_INCREF(Py_None);
    dev->out = out;
    dev->method = Py_None;
    dev->seqno = 0;
    return device;
}


static fz_quad
JM_char_quad(fz_stext_line *line, fz_stext_char *ch)
{
    if (g_skip_quad_corrections) {  // no special handling
        return ch->quad;
    }
    if (line->wmode) {  // never touch vertical write mode
        return ch->quad;
    }
    fz_font *font = ch->font;
    float asc = JM_font_ascender(font);
    float dsc = JM_font_descender(font);
    float c, s, fsize = ch->size;
    float asc_dsc = asc - dsc + FLT_EPSILON;
    if (asc_dsc >= 1 && g_small_glyph_heights == 0) {  // no problem
       return ch->quad;
    }
    if (asc < 1e-3) {  // probably Tesseract glyphless font
        dsc = -0.1f;
        asc = 0.9f;
        asc_dsc = 1.0f;
    }

    if (g_small_glyph_heights || asc_dsc < 1) {
        dsc = dsc / asc_dsc;
        asc = asc / asc_dsc;
    }
    asc_dsc = asc - dsc;
    asc = asc * fsize / asc_dsc;
    dsc = dsc * fsize / asc_dsc;

    /* ------------------------------
    Re-compute quad with the adjusted ascender / descender values:
    Move ch->origin to (0,0) and de-rotate quad, then adjust the corners,
    re-rotate and move back to ch->origin location.
    ------------------------------ */
    fz_matrix trm1, trm2, xlate1, xlate2;
    fz_quad quad;
    c = line->dir.x;  // cosine
    s = line->dir.y;  // sine
    trm1 = mupdf::ll_fz_make_matrix(c, -s, s, c, 0, 0);  // derotate
    trm2 = mupdf::ll_fz_make_matrix(c, s, -s, c, 0, 0);  // rotate
    if (c == -1) {  // left-right flip
        trm1.d = 1;
        trm2.d = 1;
    }
    xlate1 = mupdf::ll_fz_make_matrix(1, 0, 0, 1, -ch->origin.x, -ch->origin.y);
    xlate2 = mupdf::ll_fz_make_matrix(1, 0, 0, 1, ch->origin.x, ch->origin.y);

    quad = mupdf::ll_fz_transform_quad(ch->quad, xlate1);  // move origin to (0,0)
    quad = mupdf::ll_fz_transform_quad(quad, trm1);  // de-rotate corners

    // adjust vertical coordinates
    if (c == 1 && quad.ul.y > 0) {  // up-down flip
        quad.ul.y = asc;
        quad.ur.y = asc;
        quad.ll.y = dsc;
        quad.lr.y = dsc;
    } else {
        quad.ul.y = -asc;
        quad.ur.y = -asc;
        quad.ll.y = -dsc;
        quad.lr.y = -dsc;
    }

    // adjust horizontal coordinates that are too crazy:
    // (1) left x must be >= 0
    // (2) if bbox width is 0, lookup char advance in font.
    if (quad.ll.x < 0) {
        quad.ll.x = 0;
        quad.ul.x = 0;
    }
    float cwidth = quad.lr.x - quad.ll.x;
    if (cwidth < FLT_EPSILON) {
        int glyph = mupdf::ll_fz_encode_character( font, ch->c);
        if (glyph) {
            float fwidth = mupdf::ll_fz_advance_glyph( font, glyph, line->wmode);
            quad.lr.x = quad.ll.x + fwidth * fsize;
            quad.ur.x = quad.lr.x;
        }
    }

    quad = mupdf::ll_fz_transform_quad(quad, trm2);  // rotate back
    quad = mupdf::ll_fz_transform_quad(quad, xlate2);  // translate back
    return quad;
}


static fz_rect JM_char_bbox(fz_stext_line* line, fz_stext_char* ch)
{
    fz_rect r = mupdf::ll_fz_rect_from_quad(JM_char_quad( line, ch));
    if (!line->wmode) {
        return r;
    }
    if (r.y1 < r.y0 + ch->size) {
        r.y0 = r.y1 - ch->size;
    }
    return r;
}

fz_rect JM_char_bbox(const mupdf::FzStextLine& line, const mupdf::FzStextChar& ch)
{
    return JM_char_bbox( line.m_internal, ch.m_internal);
}

static int JM_rects_overlap(const fz_rect a, const fz_rect b)
{
    if (0
            || a.x0 >= b.x1
            || a.y0 >= b.y1
            || a.x1 <= b.x0
            || a.y1 <= b.y0
            )
        return 0;
    return 1;
}

//
void JM_append_rune(fz_buffer *buff, int ch);

//-----------------------------------------------------------------------------
// Plain text output. An identical copy of fz_print_stext_page_as_text,
// but lines within a block are concatenated by space instead a new-line
// character (which else leads to 2 new-lines).
//-----------------------------------------------------------------------------
void _as_text(fz_stext_block *block, mupdf::FzBuffer& res, mupdf::FzStextPage& page)
{
    /*
    Recursive function for output by blocks as identified by the
    MuPDF SEGMENT logic.
    The recursion happens when we encounter a structure block.
    */
    fz_rect rect = page.m_internal->mediabox;
    int last_char;
    fz_stext_line *line;
    fz_stext_char *ch;
    while (block)
    {
        switch (block->type)
        {
            case FZ_STEXT_BLOCK_STRUCT:
                if (block->u.s.down)
                {
                    _as_text(block->u.s.down->first_block, res, page);
                }
                break;

            case FZ_STEXT_BLOCK_TEXT:
                last_char = 0;
                for (line = block->u.t.first_line; line; line = line->next)
                {
                    for (ch = line->first_char; ch; ch = ch->next)
                    {
                        fz_rect chbbox = JM_char_bbox( line, ch);
                        if (mupdf::ll_fz_is_infinite_rect(rect) || JM_rects_overlap(rect, chbbox))
                        {
                            last_char = ch->c;
                            JM_append_rune(res.m_internal, last_char);
                        }
                    }
                    if (last_char != 10 && last_char > 0)
                    {
                        mupdf::ll_fz_append_string(res.m_internal, "\n");
                        last_char = 10;
                    }
                }
                if (last_char != 10 && last_char > 0)
                {
                    mupdf::ll_fz_append_string(res.m_internal, "\n");
                    last_char = 10;
                }
                break;
        }
        block = block->next;
    }
}

void JM_print_stext_page_as_text(mupdf::FzBuffer& res, mupdf::FzStextPage& page)
{
    fz_stext_block *block = page.m_internal->first_block;
    _as_text(block, res, page);
}



// path_type is one of:
#define FILL_PATH 1
#define STROKE_PATH 2
#define CLIP_PATH 3
#define CLIP_STROKE_PATH 4

// Every scissor of a clip is a sub rectangle of the preceding clip scissor if
// the clip level is larger.
static fz_rect compute_scissor(jm_lineart_device *dev)
{
    PyObject *last_scissor = NULL;
    fz_rect scissor;
    if (!dev->scissors) {
        dev->scissors = PyList_New(0);
    }
    Py_ssize_t num_scissors = PyList_Size(dev->scissors);
    if (num_scissors > 0) {
        last_scissor = PyList_GET_ITEM(dev->scissors, num_scissors-1);
        scissor = JM_rect_from_py(last_scissor);
        scissor = fz_intersect_rect(scissor, dev->pathrect);
    } else {
        scissor = dev->pathrect;
    }
    LIST_APPEND_DROP(dev->scissors, JM_py_from_rect(scissor));
    return scissor;
}


/*
--------------------------------------------------------------------------
Check whether the last 4 lines represent a quad.
Because of how we count, the lines are a polyline already, i.e. last point
of a line equals 1st point of next line.
So we check for a polygon (last line's end point equals start point).
If not true we return 0.
--------------------------------------------------------------------------
*/
static int
jm_checkquad(jm_lineart_device* dev)
{
    PyObject *items = PyDict_GetItem(dev->pathdict, dictkey_items);
    Py_ssize_t i, len = PyList_Size(items);
    float f[8]; // coordinates of the 4 corners
    mupdf::FzPoint temp, lp; // line = (temp, lp)
    PyObject *rect;
    PyObject *line;
    // fill the 8 floats in f, start from items[-4:]
    for (i = 0; i < 4; i++) {  // store line start points
        line = PyList_GET_ITEM(items, len - 4 + i);
        temp = JM_point_from_py(PyTuple_GET_ITEM(line, 1));
        f[i * 2] = temp.x;
        f[i * 2 + 1] = temp.y;
        lp = JM_point_from_py(PyTuple_GET_ITEM(line, 2));
    }
    if (lp.x != f[0] || lp.y != f[1]) {
        // not a polygon!
        //dev_linecount -= 1;
        return 0;
    }

    // we have detected a quad
    dev->linecount = 0;  // reset this
    // a quad item is ("qu", (ul, ur, ll, lr)), where the tuple items
    // are pairs of floats representing a quad corner each.
    rect = PyTuple_New(2);
    PyTuple_SET_ITEM(rect, 0, PyUnicode_FromString("qu"));
    /* ----------------------------------------------------
    * relationship of float array to quad points:
    * (0, 1) = ul, (2, 3) = ll, (6, 7) = ur, (4, 5) = lr
    ---------------------------------------------------- */
    fz_quad q = fz_make_quad(f[0], f[1], f[6], f[7], f[2], f[3], f[4], f[5]);
    PyTuple_SET_ITEM(rect, 1, JM_py_from_quad(q));
    PyList_SetItem(items, len - 4, rect); // replace item -4 by rect
    PyList_SetSlice(items, len - 3, len, NULL); // delete remaining 3 items
    return 1;
}


/*
--------------------------------------------------------------------------
Check whether the last 3 path items represent a rectangle.
Line 1 and 3 must be horizontal, line 2 must be vertical.
Returns 1 if we have modified the path, otherwise 0.
--------------------------------------------------------------------------
*/
static int
jm_checkrect(jm_lineart_device* dev)
{
    dev->linecount = 0; // reset line count
    long orientation = 0; // area orientation of rectangle
    mupdf::FzPoint ll, lr, ur, ul;
    mupdf::FzRect r;
    PyObject *rect;
    PyObject *line0, *line2;
    PyObject *items = PyDict_GetItem(dev->pathdict, dictkey_items);
    Py_ssize_t len = PyList_Size(items);

    line0 = PyList_GET_ITEM(items, len - 3);
    ll = JM_point_from_py(PyTuple_GET_ITEM(line0, 1));
    lr = JM_point_from_py(PyTuple_GET_ITEM(line0, 2));
    // no need to extract "line1"!
    line2 = PyList_GET_ITEM(items, len - 1);
    ur = JM_point_from_py(PyTuple_GET_ITEM(line2, 1));
    ul = JM_point_from_py(PyTuple_GET_ITEM(line2, 2));

    /*
    ---------------------------------------------------------------------
    Assumption:
    When decomposing rects, MuPDF always starts with a horizontal line,
    followed by a vertical line, followed by a horizontal line.
    First line: (ll, lr), third line: (ul, ur).
    If 1st line is below 3rd line, we record anti-clockwise (+1), else
    clockwise (-1) orientation.
    ---------------------------------------------------------------------
    */
    if (ll.y != lr.y ||
        ll.x != ul.x ||
        ur.y != ul.y ||
        ur.x != lr.x) {
        goto drop_out;  // not a rectangle
    }

    // we have a rect, replace last 3 "l" items by one "re" item.
    if (ul.y < lr.y) {
        r = fz_make_rect(ul.x, ul.y, lr.x, lr.y);
        orientation = 1;
    } else {
        r = fz_make_rect(ll.x, ll.y, ur.x, ur.y);
        orientation = -1;
    }
    rect = PyTuple_New(3);
    PyTuple_SET_ITEM(rect, 0, PyUnicode_FromString("re"));
    PyTuple_SET_ITEM(rect, 1, JM_py_from_rect(r));
    PyTuple_SET_ITEM(rect, 2, PyLong_FromLong(orientation));
    PyList_SetItem(items, len - 3, rect); // replace item -3 by rect
    PyList_SetSlice(items, len - 2, len, NULL); // delete remaining 2 items
    return 1;
    drop_out:;
    return 0;
}

static PyObject *
jm_lineart_color(fz_colorspace *colorspace, const float *color)
{
    float rgb[3];
    if (colorspace) {
        mupdf::ll_fz_convert_color(colorspace, color, mupdf::ll_fz_device_rgb(),
                         rgb, NULL, fz_default_color_params);
        return Py_BuildValue("fff", rgb[0], rgb[1], rgb[2]);
    }
    return PyTuple_New(0);
}

static void
trace_moveto(fz_context *ctx, void *dev_, float x, float y)
{
    jm_lineart_device* dev = (jm_lineart_device*) dev_;
    dev->lastpoint = mupdf::ll_fz_transform_point(fz_make_point(x, y), dev->ctm);
    if (mupdf::ll_fz_is_infinite_rect(dev->pathrect))
    {
        dev->pathrect = mupdf::ll_fz_make_rect(
                dev->lastpoint.x,
                dev->lastpoint.y,
                dev->lastpoint.x,
                dev->lastpoint.y
                );
    }
    dev->firstpoint = dev->lastpoint;
    dev->havemove = 1;
    dev->linecount = 0;  // reset # of consec. lines
}

static void
trace_lineto(fz_context *ctx, void *dev_, float x, float y)
{
    jm_lineart_device* dev = (jm_lineart_device*) dev_;
    fz_point p1 = fz_transform_point(fz_make_point(x, y), dev->ctm);
    dev->pathrect = fz_include_point_in_rect(dev->pathrect, p1);
    PyObject *list = PyTuple_New(3);
    PyTuple_SET_ITEM(list, 0, PyUnicode_FromString("l"));
    PyTuple_SET_ITEM(list, 1, JM_py_from_point(dev->lastpoint));
    PyTuple_SET_ITEM(list, 2, JM_py_from_point(p1));
    dev->lastpoint = p1;
    PyObject *items = PyDict_GetItem(dev->pathdict, dictkey_items);
    LIST_APPEND_DROP(items, list);
    dev->linecount += 1;  // counts consecutive lines
    if (dev->linecount == 4 && dev->path_type != FILL_PATH) {  // shrink to "re" or "qu" item
        jm_checkquad(dev);
    }
}

static void
trace_curveto(fz_context *ctx, void *dev_, float x1, float y1, float x2, float y2, float x3, float y3)
{
    jm_lineart_device* dev = (jm_lineart_device*) dev_;
    dev->linecount = 0;  // reset # of consec. lines
    fz_point p1 = fz_make_point(x1, y1);
    fz_point p2 = fz_make_point(x2, y2);
    fz_point p3 = fz_make_point(x3, y3);
    p1 = fz_transform_point(p1, dev->ctm);
    p2 = fz_transform_point(p2, dev->ctm);
    p3 = fz_transform_point(p3, dev->ctm);
    dev->pathrect = fz_include_point_in_rect(dev->pathrect, p1);
    dev->pathrect = fz_include_point_in_rect(dev->pathrect, p2);
    dev->pathrect = fz_include_point_in_rect(dev->pathrect, p3);

    PyObject *list = PyTuple_New(5);
    PyTuple_SET_ITEM(list, 0, PyUnicode_FromString("c"));
    PyTuple_SET_ITEM(list, 1, JM_py_from_point(dev->lastpoint));
    PyTuple_SET_ITEM(list, 2, JM_py_from_point(p1));
    PyTuple_SET_ITEM(list, 3, JM_py_from_point(p2));
    PyTuple_SET_ITEM(list, 4, JM_py_from_point(p3));
    dev->lastpoint = p3;
    PyObject *items = PyDict_GetItem(dev->pathdict, dictkey_items);
    LIST_APPEND_DROP(items, list);
}

static void
trace_close(fz_context *ctx, void *dev_)
{
    jm_lineart_device* dev = (jm_lineart_device*) dev_;
    if (dev->linecount == 3) {
        if (jm_checkrect(dev)) {
            return;
        }
    }
    dev->linecount = 0;  // reset # of consec. lines
	if (dev->havemove) {
		if (dev->firstpoint.x != dev->lastpoint.x || dev->firstpoint.y != dev->lastpoint.y) {
			PyObject *list = PyTuple_New(3);
			PyTuple_SET_ITEM(list, 0, PyUnicode_FromString("l"));
			PyTuple_SET_ITEM(list, 1, JM_py_from_point(dev->lastpoint));
			PyTuple_SET_ITEM(list, 2, JM_py_from_point(dev->firstpoint));
			dev->lastpoint = dev->firstpoint;
			PyObject *items = PyDict_GetItem(dev->pathdict, dictkey_items);
			LIST_APPEND_DROP(items, list);
		}
		dev->havemove = 0;
		DICT_SETITEMSTR_DROP(dev->pathdict, "closePath", JM_BOOL(0));
	} else {
		DICT_SETITEMSTR_DROP(dev->pathdict, "closePath", JM_BOOL(1));
	}
}

static const fz_path_walker trace_path_walker =
    {
        trace_moveto,
        trace_lineto,
        trace_curveto,
        trace_close
    };

/*
---------------------------------------------------------------------
Create the "items" list of the path dictionary
* either create or empty the path dictionary
* reset the end point of the path
* reset count of consecutive lines
* invoke fz_walk_path(), which create the single items
* if no items detected, empty path dict again
---------------------------------------------------------------------
*/
static void
jm_lineart_path(jm_lineart_device *dev, const fz_path *path)
{
    dev->pathrect = fz_infinite_rect;
    dev->linecount = 0;
    dev->lastpoint = fz_make_point(0, 0);
    dev->firstpoint = fz_make_point(0, 0);
    if (dev->pathdict) {
        Py_CLEAR(dev->pathdict);
    }
    dev->pathdict = PyDict_New();
    DICT_SETITEM_DROP(dev->pathdict, dictkey_items, PyList_New(0));
    mupdf::ll_fz_walk_path(path, &trace_path_walker, dev);
    // Check if any items were added ...
    if (!PyDict_GetItem(dev->pathdict, dictkey_items) || !PyList_Size(PyDict_GetItem(dev->pathdict, dictkey_items)))
    {
        Py_CLEAR(dev->pathdict);
    }
}

//---------------------------------------------------------------------------
// Append current path to list or merge into last path of the list.
// (1) Append if first path, different item lists or not a 'stroke' version
//     of previous path
// (2) If new path has the same items, merge its content into previous path
//     and change path["type"] to "fs".
// (3) If "out" is callable, skip the previous and pass dictionary to it.
//---------------------------------------------------------------------------
static void
// todo: remove `method` arg - it is dev->method.
jm_append_merge(jm_lineart_device *dev)
{
    Py_ssize_t len;
    int rc;
    PyObject *prev;
    PyObject *previtems;
    PyObject *thisitems;
    const char *thistype;
    const char *prevtype;
    if (PyCallable_Check(dev->out) || dev->method != Py_None) {  // function or method
        goto callback;
    }
    len = PyList_Size(dev->out);  // len of output list so far
    if (len == 0) {  // always append first path 
        goto append;
    }
    thistype = PyUnicode_AsUTF8(PyDict_GetItem(dev->pathdict, dictkey_type));
    if (strcmp(thistype, "s") != 0) {  // if not stroke, then append
        goto append;
    }
    prev = PyList_GET_ITEM(dev->out, len - 1);  // get prev path
    prevtype = PyUnicode_AsUTF8(PyDict_GetItem(prev, dictkey_type));
    if (strcmp(prevtype, "f") != 0) {  // if previous not fill, append
        goto append;
    }
    // last check: there must be the same list of items for "f" and "s".
    previtems = PyDict_GetItem(prev, dictkey_items);
    thisitems = PyDict_GetItem(dev->pathdict, dictkey_items);
    if (PyObject_RichCompareBool(previtems, thisitems, Py_NE)) {
        goto append;
    }
    rc = PyDict_Merge(prev, dev->pathdict, 0);  // merge, do not override
    if (rc == 0) {
        DICT_SETITEM_DROP(prev, dictkey_type, PyUnicode_FromString("fs"));
        goto postappend;
    } else {
        messagef("could not merge stroke and fill path");
        goto append;
    }
    append:;
    //printf("Appending to dev->out. len(dev->out)=%zi\n", PyList_Size(dev->out));
    PyList_Append(dev->out, dev->pathdict);
    postappend:;
    Py_CLEAR(dev->pathdict);
    return;

    callback:;  // callback function or method
    PyObject *resp = NULL;
    if (dev->method == Py_None) {
        resp = PyObject_CallFunctionObjArgs(dev->out, dev->pathdict, NULL);
    } else {
        resp = PyObject_CallMethodObjArgs(dev->out, dev->method, dev->pathdict, NULL);
    }
    if (resp) {
        Py_DECREF(resp);
    } else {
        messagef("calling cdrawings callback function/method failed!");
        PyErr_Clear();
    }
    Py_CLEAR(dev->pathdict);
    return;
}

static void
jm_lineart_fill_path(fz_context *ctx, fz_device *dev_, const fz_path *path,
                int even_odd, fz_matrix ctm, fz_colorspace *colorspace,
                const float *color, float alpha, fz_color_params color_params)
{
    jm_lineart_device *dev = (jm_lineart_device *) dev_;
    //printf("extra.jm_lineart_fill_path(): dev->seqno=%zi\n", dev->seqno);
    dev->ctm = ctm; //fz_concat(ctm, trace_device_ptm);
    dev->path_type = FILL_PATH;
    jm_lineart_path(dev, path);
    if (!dev->pathdict) {
        return;
    }
    DICT_SETITEM_DROP(dev->pathdict, dictkey_type, PyUnicode_FromString("f"));
    DICT_SETITEMSTR_DROP(dev->pathdict, "even_odd", JM_BOOL(even_odd));
    DICT_SETITEMSTR_DROP(dev->pathdict, "fill_opacity", Py_BuildValue("f", alpha));
    DICT_SETITEMSTR_DROP(dev->pathdict, "fill", jm_lineart_color(colorspace, color));
    DICT_SETITEM_DROP(dev->pathdict, dictkey_rect, JM_py_from_rect(dev->pathrect));
    DICT_SETITEMSTR_DROP(dev->pathdict, "seqno", PyLong_FromSize_t(dev->seqno));
    DICT_SETITEMSTR_DROP(dev->pathdict, "layer", JM_UnicodeFromStr(dev->layer_name));
    if (dev->clips)    {
        DICT_SETITEMSTR_DROP(dev->pathdict, "level", PyLong_FromLong(dev->depth));
    }
    jm_append_merge(dev);
    dev->seqno += 1;
}

static void
jm_lineart_stroke_path(fz_context *ctx, fz_device *dev_, const fz_path *path,
                const fz_stroke_state *stroke, fz_matrix ctm,
                fz_colorspace *colorspace, const float *color, float alpha,
                fz_color_params color_params)
{
    jm_lineart_device *dev = (jm_lineart_device *)dev_;
    //printf("extra.jm_lineart_stroke_path(): dev->seqno=%zi\n", dev->seqno);
    int i;
    dev->pathfactor = sqrtf(fabsf(ctm.a * ctm.d - ctm.b * ctm.c));
    dev->ctm = ctm; // fz_concat(ctm, trace_device_ptm);
    dev->path_type = STROKE_PATH;

    jm_lineart_path(dev, path);
    if (!dev->pathdict) {
        return;
    }
    DICT_SETITEM_DROP(dev->pathdict, dictkey_type, PyUnicode_FromString("s"));
    DICT_SETITEMSTR_DROP(dev->pathdict, "stroke_opacity", Py_BuildValue("f", alpha));
    DICT_SETITEMSTR_DROP(dev->pathdict, "color", jm_lineart_color(colorspace, color));
    DICT_SETITEM_DROP(dev->pathdict, dictkey_width, Py_BuildValue("f", dev->pathfactor * stroke->linewidth));
    DICT_SETITEMSTR_DROP(dev->pathdict, "lineCap", Py_BuildValue("iii", stroke->start_cap, stroke->dash_cap, stroke->end_cap));
    DICT_SETITEMSTR_DROP(dev->pathdict, "lineJoin", Py_BuildValue("f", (float)stroke->linejoin));
    if (!PyDict_GetItemString(dev->pathdict, "closePath")) {
        DICT_SETITEMSTR_DROP(dev->pathdict, "closePath", JM_BOOL(0));
    }

    // output the "dashes" string
    if (stroke->dash_len) {
        mupdf::FzBuffer buff(256);
        mupdf::fz_append_string(buff, "[ ");  // left bracket
        for (i = 0; i < stroke->dash_len; i++) {
            fz_append_printf(ctx, buff.m_internal, "%g ", dev->pathfactor * stroke->dash_list[i]);
        }
        fz_append_printf(ctx, buff.m_internal, "] %g", dev->pathfactor * stroke->dash_phase);
        DICT_SETITEMSTR_DROP(dev->pathdict, "dashes", JM_EscapeStrFromBuffer(buff));
    } else {
        DICT_SETITEMSTR_DROP(dev->pathdict, "dashes", PyUnicode_FromString("[] 0"));
    }

    DICT_SETITEM_DROP(dev->pathdict, dictkey_rect, JM_py_from_rect(dev->pathrect));
    DICT_SETITEMSTR_DROP(dev->pathdict, "layer", JM_UnicodeFromStr(dev->layer_name));
    DICT_SETITEMSTR_DROP(dev->pathdict, "seqno", PyLong_FromSize_t(dev->seqno));
    if (dev->clips) {
        DICT_SETITEMSTR_DROP(dev->pathdict, "level", PyLong_FromLong(dev->depth));
    }
    // output the dict - potentially merging it with a previous fill_path twin
    jm_append_merge(dev);
    dev->seqno += 1;
}

static void
jm_lineart_clip_path(fz_context *ctx, fz_device *dev_, const fz_path *path, int even_odd, fz_matrix ctm, fz_rect scissor)
{
    jm_lineart_device *dev = (jm_lineart_device *)dev_;
    if (!dev->clips) return;
    dev->ctm = ctm; //fz_concat(ctm, trace_device_ptm);
    dev->path_type = CLIP_PATH;
    jm_lineart_path(dev, path);
	if (!dev->pathdict) {
		return;
	}
    DICT_SETITEM_DROP(dev->pathdict, dictkey_type, PyUnicode_FromString("clip"));
    DICT_SETITEMSTR_DROP(dev->pathdict, "even_odd", JM_BOOL(even_odd));
    if (!PyDict_GetItemString(dev->pathdict, "closePath")) {
        DICT_SETITEMSTR_DROP(dev->pathdict, "closePath", JM_BOOL(0));
    }
    DICT_SETITEMSTR_DROP(dev->pathdict, "scissor", JM_py_from_rect(compute_scissor(dev)));
    DICT_SETITEMSTR_DROP(dev->pathdict, "level", PyLong_FromLong(dev->depth));
    DICT_SETITEMSTR_DROP(dev->pathdict, "layer", JM_UnicodeFromStr(dev->layer_name));
    jm_append_merge(dev);
    dev->depth++;
}

static void
jm_lineart_clip_stroke_path(fz_context *ctx, fz_device *dev_, const fz_path *path, const fz_stroke_state *stroke, fz_matrix ctm, fz_rect scissor)
{
    jm_lineart_device *dev = (jm_lineart_device *)dev_;
    if (!dev->clips) return;
    dev->ctm = ctm; //fz_concat(ctm, trace_device_ptm);
    dev->path_type = CLIP_STROKE_PATH;
    jm_lineart_path(dev, path);
	if (!dev->pathdict) {
		return;
	}
    DICT_SETITEM_DROP(dev->pathdict, dictkey_type, PyUnicode_FromString("clip"));
    DICT_SETITEMSTR_DROP(dev->pathdict, "even_odd", Py_BuildValue("s", NULL));
    if (!PyDict_GetItemString(dev->pathdict, "closePath")) {
        DICT_SETITEMSTR_DROP(dev->pathdict, "closePath", JM_BOOL(0));
    }
    DICT_SETITEMSTR_DROP(dev->pathdict, "scissor", JM_py_from_rect(compute_scissor(dev)));
    DICT_SETITEMSTR_DROP(dev->pathdict, "level", PyLong_FromLong(dev->depth));
    DICT_SETITEMSTR_DROP(dev->pathdict, "layer", JM_UnicodeFromStr(dev->layer_name));
    jm_append_merge(dev);
    dev->depth++;
}


static void
jm_lineart_clip_stroke_text(fz_context *ctx, fz_device *dev_, const fz_text *text, const fz_stroke_state *stroke, fz_matrix ctm, fz_rect scissor)
{
   jm_lineart_device *dev = (jm_lineart_device *)dev_;
   if (!dev->clips) return;
   compute_scissor(dev);
   dev->depth++;
}

static void
jm_lineart_clip_text(fz_context *ctx, fz_device *dev_, const fz_text *text, fz_matrix ctm, fz_rect scissor)
{
   jm_lineart_device *dev = (jm_lineart_device *)dev_;
   if (!dev->clips) return;
   compute_scissor(dev);
   dev->depth++;
}

static void
jm_lineart_clip_image_mask(fz_context *ctx, fz_device *dev_, fz_image *image, fz_matrix ctm, fz_rect scissor)
{
   jm_lineart_device *dev = (jm_lineart_device *)dev_;
   if (!dev->clips) return;
   compute_scissor(dev);
   dev->depth++;
}
 
static void
jm_lineart_pop_clip(fz_context *ctx, fz_device *dev_)
{
    jm_lineart_device *dev = (jm_lineart_device *)dev_;
    if (!dev->clips) return;
    if (!dev->scissors) return;
    Py_ssize_t len = PyList_Size(dev->scissors);
    if (len < 1) return;
    PyList_SetSlice(dev->scissors, len - 1, len, NULL);
    dev->depth--;
}


static void
jm_lineart_begin_group(fz_context *ctx, fz_device *dev_, fz_rect bbox, fz_colorspace *cs, int isolated, int knockout, int blendmode, float alpha)
{
    jm_lineart_device *dev = (jm_lineart_device *)dev_;
    if (!dev->clips) return;
    dev->pathdict = Py_BuildValue("{s:s,s:N,s:N,s:N,s:s,s:f,s:i,s:N}",
                        "type", "group",
                        "rect", JM_py_from_rect(bbox),
                        "isolated", JM_BOOL(isolated),
                        "knockout", JM_BOOL(knockout),
                        "blendmode", fz_blendmode_name(blendmode),
                        "opacity", alpha,
                        "level", dev->depth,
                        "layer", JM_UnicodeFromStr(dev->layer_name)
                    );
    jm_append_merge(dev);
    dev->depth++;
}

static void
jm_lineart_end_group(fz_context *ctx, fz_device *dev_)
{
    jm_lineart_device *dev = (jm_lineart_device *)dev_;
    if (!dev->clips) return;
    dev->depth--;
}

static void jm_lineart_fill_text(fz_context *ctx, fz_device *dev, const fz_text *, fz_matrix, fz_colorspace *, const float *color, float alpha, fz_color_params)
{
    jm_increase_seqno(ctx, dev);
}

static void jm_lineart_stroke_text(fz_context *ctx, fz_device *dev, const fz_text *, const fz_stroke_state *, fz_matrix, fz_colorspace *, const float *color, float alpha, fz_color_params)
{
    jm_increase_seqno(ctx, dev);
}

static void jm_lineart_fill_shade(fz_context *ctx, fz_device *dev, fz_shade *shd, fz_matrix ctm, float alpha, fz_color_params color_params)
{
    jm_increase_seqno(ctx, dev);
}

static void jm_lineart_fill_image(fz_context *ctx, fz_device *dev, fz_image *img, fz_matrix ctm, float alpha, fz_color_params color_params)
{
    jm_increase_seqno(ctx, dev);
}

static void jm_lineart_fill_image_mask(fz_context *ctx, fz_device *dev, fz_image *img, fz_matrix ctm, fz_colorspace *, const float *color, float alpha, fz_color_params color_params)
{
    jm_increase_seqno(ctx, dev);
}

static void jm_lineart_ignore_text(fz_context *ctx, fz_device *dev, const fz_text *, fz_matrix)
{
    jm_increase_seqno(ctx, dev);
}


//-------------------------------------------------------------------
// LINEART device for Python method Page.get_cdrawings()
//-------------------------------------------------------------------
mupdf::FzDevice JM_new_lineart_device(PyObject *out, int clips, PyObject *method)
{
    //printf("extra.JM_new_lineart_device()\n");
    jm_lineart_device* dev = (jm_lineart_device*) mupdf::ll_fz_new_device_of_size(sizeof(jm_lineart_device));

    dev->super.close_device = NULL;
    dev->super.drop_device = jm_lineart_drop_device;
    dev->super.fill_path = jm_lineart_fill_path;
    dev->super.stroke_path = jm_lineart_stroke_path;
    dev->super.clip_path = jm_lineart_clip_path;
    dev->super.clip_stroke_path = jm_lineart_clip_stroke_path;

    dev->super.fill_text = jm_lineart_fill_text;
    dev->super.stroke_text = jm_lineart_stroke_text;
    dev->super.clip_text = jm_lineart_clip_text;
    dev->super.clip_stroke_text = jm_lineart_clip_stroke_text;
    dev->super.ignore_text = jm_lineart_ignore_text;

    dev->super.fill_shade = jm_lineart_fill_shade;
    dev->super.fill_image = jm_lineart_fill_image;
    dev->super.fill_image_mask = jm_lineart_fill_image_mask;
    dev->super.clip_image_mask = jm_lineart_clip_image_mask;

    dev->super.pop_clip = jm_lineart_pop_clip;

    dev->super.begin_mask = NULL;
    dev->super.end_mask = NULL;
    dev->super.begin_group = jm_lineart_begin_group;
    dev->super.end_group = jm_lineart_end_group;

    dev->super.begin_tile = NULL;
    dev->super.end_tile = NULL;

    dev->super.begin_layer = jm_lineart_begin_layer;
    dev->super.end_layer = jm_lineart_end_layer;

    dev->super.begin_structure = NULL;
    dev->super.end_structure = NULL;

    dev->super.begin_metatext = NULL;
    dev->super.end_metatext = NULL;

    dev->super.render_flags = NULL;
    dev->super.set_default_colorspaces = NULL;

    if (PyList_Check(out)) {
        Py_INCREF(out);
    }
    Py_INCREF(method);
    dev->out = out;
    dev->seqno = 0;
    dev->depth = 0;
    dev->clips = clips;
    dev->method = method;
    dev->pathdict = nullptr;

    return mupdf::FzDevice(&dev->super);
}

PyObject* get_cdrawings(mupdf::FzPage& page, PyObject *extended=NULL, PyObject *callback=NULL, PyObject *method=NULL)
{
    //fz_page *page = (fz_page *) $self;
    //fz_device *dev = NULL;
    PyObject *rc = NULL;
    int clips = PyObject_IsTrue(extended);

    mupdf::FzDevice dev;
    if (PyCallable_Check(callback) || method != Py_None) {
        dev = JM_new_lineart_device(callback, clips, method);
    } else {
        rc = PyList_New(0);
        dev = JM_new_lineart_device(rc, clips, method);
    }
    mupdf::FzRect prect = mupdf::fz_bound_page(page);
    ((jm_lineart_device*) dev.m_internal)->ptm = mupdf::ll_fz_make_matrix(1, 0, 0, -1, 0, prect.y1);
    
    mupdf::FzCookie cookie;
    mupdf::FzMatrix identity;
    mupdf::fz_run_page( page, dev, *identity.internal(), cookie);
    mupdf::fz_close_device( dev);
    if (PyCallable_Check(callback) || method != Py_None)
    {
        Py_RETURN_NONE;
    }
    return rc;
}


static int detect_super_script(fz_stext_line *line, fz_stext_char *ch)
{
    if (line->wmode == 0 && line->dir.x == 1 && line->dir.y == 0)
    {
        return ch->origin.y < line->first_char->origin.y - ch->size * 0.1f;
    }
    return 0;
}

static int JM_char_font_flags(fz_font *font, fz_stext_line *line, fz_stext_char *ch)
{
    int flags = detect_super_script(line, ch);
    flags += mupdf::ll_fz_font_is_italic(font) * TEXT_FONT_ITALIC;
    flags += mupdf::ll_fz_font_is_serif(font) * TEXT_FONT_SERIFED;
    flags += mupdf::ll_fz_font_is_monospaced(font) * TEXT_FONT_MONOSPACED;
    flags += mupdf::ll_fz_font_is_bold(font) * TEXT_FONT_BOLD;
    return flags;
}

//---------------------------------------------------------------------------
// APPEND non-ascii runes in unicode escape format to fz_buffer
//---------------------------------------------------------------------------
void JM_append_rune(fz_buffer *buff, int ch)
{
    char text[32];
    if (ch == 92)  // prevent accidental "\u", "\U" sequences
    {
        mupdf::ll_fz_append_string(buff, "\\u005c");
    }
    else if ((ch >= 32 && ch <= 127) || ch == 10)
    {
        mupdf::ll_fz_append_byte(buff, ch);
    }
    else if (ch >= 0xd800 && ch <= 0xdfff)  // orphaned surrogate Unicodes
    {
        mupdf::ll_fz_append_string(buff, "\\ufffd");
    }
    else if (ch <= 0xffff)
    {
        // 4 hex digits
        snprintf(text, sizeof(text), "\\u%04x", ch);
        mupdf::ll_fz_append_string(buff, text);
    }
    else
    {
        // 8 hex digits
        snprintf(text, sizeof(text), "\\U%08x", ch);
        mupdf::ll_fz_append_string(buff, text);
    }
}


mupdf::FzRect JM_make_spanlist(
        PyObject *line_dict,
        mupdf::FzStextLine& line,
        int raw,
        mupdf::FzBuffer& buff,
        mupdf::FzRect& tp_rect
        )
{
    PyObject *span = NULL, *char_list = NULL, *char_dict;
    PyObject *span_list = PyList_New(0);
    mupdf::fz_clear_buffer(buff);
    fz_rect span_rect = fz_empty_rect;
    fz_rect line_rect = fz_empty_rect;
    fz_point span_origin = {0, 0};
    struct char_style
    {
        float size = -1;
        unsigned flags = 0;
        
        /* From mupdf:include/mupdf/fitz/structured-text.h:fz_stext_char::flags, which
        uses anonymous enum values:
        FZ_STEXT_STRIKEOUT = 1,
        FZ_STEXT_UNDERLINE = 2,
        FZ_STEXT_SYNTHETIC = 4,
        FZ_STEXT_FILLED = 16,
        FZ_STEXT_STROKED = 32,
        FZ_STEXT_CLIPPED = 64
        */
        unsigned char_flags = 0;
        
        const char *font = "";
        unsigned argb = 0;
        float asc = 0;
        float desc = 0;
        uint16_t bidi = 0;
    };
    char_style old_style;
    char_style style;

    for (mupdf::FzStextChar ch: line)
    {
        fz_rect r = JM_char_bbox(line, ch);
        if (!JM_rects_overlap(*tp_rect.internal(), r) && !fz_is_infinite_rect(tp_rect))
        {
            continue;
        }
        /* Info from:
        detect_super_script()
        fz_font_is_italic()
        fz_font_is_serif()
        fz_font_is_monospaced()
        fz_font_is_bold()
        */
        int flags = JM_char_font_flags( ch.m_internal->font, line.m_internal, ch.m_internal);
        fz_point origin = ch.m_internal->origin;
        style.size = ch.m_internal->size;
        style.flags = flags;
        /* FZ_STEXT_SYNTHETIC is per-char, not per-span. */
        style.char_flags = ch.m_internal->flags & ~FZ_STEXT_SYNTHETIC;
        style.font = JM_font_name(ch.m_internal->font);
        style.argb = ch.m_internal->argb;
        style.asc = JM_font_ascender(ch.m_internal->font);
        style.desc = JM_font_descender(ch.m_internal->font);

        if (0
                || style.size != old_style.size
                || style.flags != old_style.flags
                || style.char_flags != old_style.char_flags
                || style.argb != old_style.argb
                || strcmp(style.font, old_style.font) != 0
                || style.bidi != old_style.bidi
                )
        {
            if (old_style.size >= 0)
            {
                // not first one, output previous
                if (raw)
                {
                    // put character list in the span
                    DICT_SETITEM_DROP(span, dictkey_chars, char_list);
                    char_list = NULL;
                }
                else
                {
                    // put text string in the span
                    DICT_SETITEM_DROP(span, dictkey_text, JM_EscapeStrFromBuffer(buff));
                    mupdf::fz_clear_buffer(buff);
                }

                DICT_SETITEM_DROP(span, dictkey_origin, JM_py_from_point(span_origin));
                DICT_SETITEM_DROP(span, dictkey_bbox, JM_py_from_rect(span_rect));
                line_rect = mupdf::ll_fz_union_rect(line_rect, span_rect);
                LIST_APPEND_DROP(span_list, span);
                span = NULL;
            }

            span = PyDict_New();
            float asc = style.asc, desc = style.desc;
            if (style.asc < 1e-3)
            {
                asc = 0.9f;
                desc = -0.1f;
            }

            DICT_SETITEM_DROP(span, dictkey_size, Py_BuildValue("f", style.size));
            DICT_SETITEM_DROP(span, dictkey_flags, Py_BuildValue("I", style.flags));
            DICT_SETITEM_DROP(span, dictkey_bidi, Py_BuildValue("I", style.bidi));
            DICT_SETITEM_DROP(span, dictkey_char_flags, Py_BuildValue("I", style.char_flags));
            DICT_SETITEM_DROP(span, dictkey_font, JM_EscapeStrFromStr(style.font));
            DICT_SETITEM_DROP(span, dictkey_color, Py_BuildValue("I", style.argb & 0xffffff));
            DICT_SETITEMSTR_DROP(span, "alpha", Py_BuildValue("I", style.argb >> 24));
            DICT_SETITEMSTR_DROP(span, "ascender", Py_BuildValue("f", asc));
            DICT_SETITEMSTR_DROP(span, "descender", Py_BuildValue("f", desc));

            old_style = style;
            span_rect = r;
            span_origin = origin;

        }
        span_rect = mupdf::ll_fz_union_rect(span_rect, r);

        if (raw)
        {
            // make and append a char dict
            char_dict = PyDict_New();
            DICT_SETITEM_DROP(char_dict, dictkey_origin, JM_py_from_point(ch.m_internal->origin));

            DICT_SETITEM_DROP(char_dict, dictkey_bbox, JM_py_from_rect(r));

            DICT_SETITEM_DROP(char_dict, dictkey_c, Py_BuildValue("C", ch.m_internal->c));
            DICT_SETITEMSTR_DROP(char_dict, "synthetic", Py_BuildValue("O", (ch.m_internal->flags & FZ_STEXT_SYNTHETIC) ? Py_True : Py_False));
            if (!char_list)
            {
                char_list = PyList_New(0);
            }
            LIST_APPEND_DROP(char_list, char_dict);
        }
        else
        {
            // add character byte to buffer
            JM_append_rune(buff.m_internal, ch.m_internal->c);
        }
    }
    // all characters processed, now flush remaining span
    if (span)
    {
        if (raw)
        {
            DICT_SETITEM_DROP(span, dictkey_chars, char_list);
            char_list = NULL;
        }
        else
        {
            DICT_SETITEM_DROP(span, dictkey_text, JM_EscapeStrFromBuffer(buff));
            mupdf::fz_clear_buffer(buff);
        }
        DICT_SETITEM_DROP(span, dictkey_origin, JM_py_from_point(span_origin));
        DICT_SETITEM_DROP(span, dictkey_bbox, JM_py_from_rect(span_rect));

        if (!fz_is_empty_rect(span_rect))
        {
            LIST_APPEND_DROP(span_list, span);
            line_rect = fz_union_rect(line_rect, span_rect);
        }
        else
        {
            Py_DECREF(span);
        }
        span = NULL;
    }
    if (!mupdf::fz_is_empty_rect(line_rect))
    {
        DICT_SETITEM_DROP(line_dict, dictkey_spans, span_list);
    }
    else
    {
        DICT_SETITEM_DROP(line_dict, dictkey_spans, span_list);
    }
    return line_rect;
}

//-----------------------------------------------------------------------------
// Functions for wordlist output
//-----------------------------------------------------------------------------
int JM_append_word(
        PyObject* lines,
        fz_buffer* buff,
        fz_rect* wbbox,
        int block_n,
        int line_n,
        int word_n
        )
{
    PyObject* s = JM_EscapeStrFromBuffer(buff);
    PyObject* litem = Py_BuildValue(
            "ffffOiii",
            wbbox->x0,
            wbbox->y0,
            wbbox->x1,
            wbbox->y1,
            s,
            block_n,
            line_n,
            word_n
            );
    LIST_APPEND_DROP(lines, litem);
    Py_DECREF(s);
    *wbbox = fz_empty_rect;
    return word_n + 1;  // word counter
}

int _as_words(fz_stext_block *block, mupdf::FzBuffer& buff, fz_rect tp_rect, PyObject *lines, int block_n, PyObject *delimiters)
{
    /* 'buff' is intermediate storage for composing a word. Used as parameter only for
    avoiding repeated allocation of an FzBuffer.*/
    int line_n;
    fz_stext_line *line;
    fz_stext_char *ch;
    fz_rect wbbox, blockrect;
    while (block)
    {
        switch (block->type)
        {
            case FZ_STEXT_BLOCK_STRUCT:
                if (block->u.s.down)
                {
                    block_n = _as_words(block->u.s.down->first_block, buff, tp_rect, lines, block_n, delimiters);
                }
                break;

            case FZ_STEXT_BLOCK_TEXT:
                block_n++;
                blockrect = block->bbox;
                wbbox = fz_empty_rect;
                line_n = -1;
                for (line = block->u.t.first_line; line; line = line->next)
                {
                    line_n++;
                    int word_n = 0;                 // word counter per line
                    mupdf::fz_clear_buffer(buff);   // reset word buffer
                    int last_char_rtl = 0;          // was last character RTL?
                            for (ch = line->first_char; ch; ch = ch->next)
                    {
                        mupdf::FzRect cbbox = JM_char_bbox(line, ch);
                        if (!JM_rects_overlap(tp_rect, *cbbox.internal()) && !fz_is_infinite_rect(tp_rect))
                        {
                            continue;
                        }
                        // prevent Unicode ZWJ 0x200d to start a word
                        if (mupdf::fz_buffer_storage(buff, NULL) == 0 && ch->c == 0x200d)
                        {
                            continue;
                        }
                        int word_delimiter = JM_is_word_delimiter(ch->c, delimiters);
                        int this_char_rtl = JM_is_rtl_char(ch->c);
                        if (word_delimiter || this_char_rtl != last_char_rtl)
                        {
                            if (mupdf::fz_buffer_storage(buff, NULL) == 0 && word_delimiter)
                            {
                                continue;  // skip delimiters at line start
                            }
                            if (!fz_is_empty_rect(wbbox))
                            {
                                word_n = JM_append_word(
                                        lines,
                                        buff.m_internal,
                                        &wbbox,
                                        block_n,
                                        line_n,
                                        word_n
                                        );
                            }
                            mupdf::fz_clear_buffer(buff);
                            if (word_delimiter) continue;
                        }
                        // append one unicode character to the word
                        JM_append_rune(buff.m_internal, ch->c);
                        last_char_rtl = this_char_rtl;
                        // enlarge word bbox
                        wbbox = fz_union_rect(wbbox, JM_char_bbox(line, ch));
                    }
                    if (mupdf::fz_buffer_storage(buff, NULL) && !fz_is_empty_rect(wbbox))
                    {
                        word_n = JM_append_word(
                                lines,
                                buff.m_internal,
                                &wbbox,
                                block_n,
                                line_n,
                                word_n
                                );
                    }
                    mupdf::fz_clear_buffer(buff);
                }
                break;
        }
        block = block->next;     
    }
    return block_n;
}


PyObject* extractWORDS(mupdf::FzStextPage& this_tpage, PyObject *delimiters)
{
    int block_n = -1;
    fz_rect tp_rect = this_tpage.m_internal->mediabox;
    PyObject *lines = NULL;
    mupdf::FzBuffer buff = mupdf::fz_new_buffer(64);
    lines = PyList_New(0);
    mupdf::FzStextBlock block = this_tpage.m_internal->first_block;
    block_n = _as_words(block.m_internal, buff, tp_rect, lines, block_n, delimiters);
    return lines;
}


struct ScopedPyObject
/* PyObject* wrapper, destructor calls Py_CLEAR() unless `release()` has been
called. */
{
    ScopedPyObject(PyObject* rhs=nullptr)
    :
    m_pyobject(rhs)
    {}
    
    PyObject*& get()
    {
        return m_pyobject;
    }
    
    ScopedPyObject& operator= (PyObject* rhs)
    {
        Py_CLEAR(m_pyobject);
        m_pyobject = rhs;
        return *this;
    }
    
    PyObject* release()
    {
        PyObject* ret = m_pyobject;
        m_pyobject = nullptr;
        return ret;
    }
    ~ScopedPyObject()
    {
        Py_CLEAR(m_pyobject);
    }
    
    PyObject*   m_pyobject = nullptr;
};

int _as_blocks(fz_stext_block *block, fz_rect tp_rect, PyObject *lines, int block_n)
{
    /*
    Recursive function for output by blocks as identified by the
    MuPDF SEGMENT logic.
    Recursion happens on encountering a structure block.
    In addition to the previous support of text and image, we now also support
    vector blocks.
    */
    PyObject *text = NULL;
    fz_rect blockrect;
    mupdf::FzBuffer res;
    int last_char;
    while (block)
    {
        switch (block->type)
        {
            case FZ_STEXT_BLOCK_STRUCT:
                if (block->u.s.down)
                {
                    block_n = _as_blocks(block->u.s.down->first_block, tp_rect, lines, block_n);
                }
                break;

            case FZ_STEXT_BLOCK_TEXT:
                blockrect = fz_empty_rect;
                res = mupdf::fz_new_buffer(1024);
                last_char = 10;
                for (fz_stext_line* line = block->u.t.first_line; line; line = line->next)
                {
                    fz_rect linerect = fz_empty_rect;
                    for (fz_stext_char* ch = line->first_char; ch; ch = ch->next)
                    {
                        fz_rect cbbox = JM_char_bbox(line, ch);
                        if (!JM_rects_overlap(tp_rect, cbbox) && !fz_is_infinite_rect(tp_rect))
                        {
                            continue;
                        }
                        JM_append_rune(res.m_internal, ch->c);
                        last_char = ch->c;
                        linerect = fz_union_rect(linerect, cbbox);
                    }
                    if (last_char != 10 && !fz_is_empty_rect(linerect))
                    {
                            JM_append_rune(res.m_internal, 10);
                    }
                    blockrect = fz_union_rect(blockrect, linerect);
                }
                text = JM_EscapeStrFromBuffer(res);
                break;

            case FZ_STEXT_BLOCK_IMAGE:
                if (fz_contains_rect(tp_rect, block->bbox) || fz_is_infinite_rect(tp_rect))
                {
                    blockrect = block->bbox;
                    fz_image *img = block->u.i.image;
                    fz_colorspace *cs = img->colorspace;
                    text = PyUnicode_FromFormat(
                                    "<image: %s, width: %d, height: %d, bpc: %d>\n",
                            mupdf::ll_fz_colorspace_name(cs),
                            img->w,
                            img->h,
                            img->bpc
                            );
                }
                break;

            case FZ_STEXT_BLOCK_VECTOR:
                if (JM_rects_overlap(tp_rect, block->bbox) || fz_is_infinite_rect(tp_rect))
                {
                    blockrect = block->bbox;
                    int alpha = (int) (block->u.v.argb >> 24);
                    int color = (int) (block->u.v.argb & 0xffffff);
                    text = PyUnicode_FromFormat(
                            "\n<vector %s, color: #%06x, alpha: %i, is-rect: %s, continues: %s>\n",
                            (block->u.v.flags & FZ_STEXT_VECTOR_IS_STROKED) ? "stroked" : "filled",
                            color,
                            alpha,
                            (block->u.v.flags & FZ_STEXT_VECTOR_IS_RECTANGLE) ? "true":"false",
                            (block->u.v.flags & FZ_STEXT_VECTOR_CONTINUES) ? "true":"false");
                }
                break;
        }

        if (text)
        {
            block_n += 1;
            PyObject *litem = PyTuple_New(7);
            PyTuple_SET_ITEM(litem, 0, Py_BuildValue("f", blockrect.x0));
            PyTuple_SET_ITEM(litem, 1, Py_BuildValue("f", blockrect.y0));
            PyTuple_SET_ITEM(litem, 2, Py_BuildValue("f", blockrect.x1));
            PyTuple_SET_ITEM(litem, 3, Py_BuildValue("f", blockrect.y1));
            PyTuple_SET_ITEM(litem, 4, Py_BuildValue("O", text));
            PyTuple_SET_ITEM(litem, 5, Py_BuildValue("i", block_n));
            PyTuple_SET_ITEM(litem, 6, Py_BuildValue("i", block->type));
            LIST_APPEND(lines, litem);
        }
        text = NULL;
        block = block->next;
        }
    return block_n;
    }

PyObject* extractBLOCKS(mupdf::FzStextPage& self)
{
    fz_stext_page *this_tpage = self.m_internal;
    fz_rect tp_rect = this_tpage->mediabox;
    ScopedPyObject lines(PyList_New(0));
    int block_n = -1;
    fz_stext_block *block = this_tpage->first_block;
    block_n = _as_blocks(block, tp_rect, lines.get(), block_n);
    return lines.release();
}

#define EMPTY_STRING PyUnicode_FromString("")

static PyObject *JM_UnicodeFromStr(const char *c)
{
    if (!c) return EMPTY_STRING;
    PyObject *val = Py_BuildValue("s", c);
    if (!val) {
        val = EMPTY_STRING;
        PyErr_Clear();
    }
    return val;
}

PyObject* link_uri(mupdf::FzLink& link)
{
    return JM_UnicodeFromStr( link.m_internal->uri);
}

fz_stext_page* page_get_textpage(
        mupdf::FzPage& self,
        PyObject* clip,
        int flags,
        PyObject* matrix
        )
{
    fz_context* ctx = mupdf::internal_context_get();
    fz_stext_page *tpage=NULL;
    fz_page *page = self.m_internal;
    fz_device *dev = NULL;
    fz_stext_options options;
    memset(&options, 0, sizeof options);
    options.flags = flags;
    fz_try(ctx) {
        // Default to page's rect if `clip` not specified, for #2048.
        fz_rect rect = (clip==Py_None) ? fz_bound_page(ctx, page) : JM_rect_from_py(clip);
        fz_matrix ctm = JM_matrix_from_py(matrix);
        tpage = fz_new_stext_page(ctx, rect);
        dev = fz_new_stext_device(ctx, tpage, &options);
        fz_run_page(ctx, page, dev, ctm, NULL);
        fz_close_device(ctx, dev);
    }
    fz_always(ctx) {
        fz_drop_device(ctx, dev);
    }
    fz_catch(ctx) {
        mupdf::internal_throw_exception(ctx);
    }
    return tpage;
}

// return extension for pymupdf image type
const char *JM_image_extension(int type)
{
    switch (type) {
        case(FZ_IMAGE_RAW): return "raw";
        case(FZ_IMAGE_FLATE): return "flate";
        case(FZ_IMAGE_LZW): return "lzw";
        case(FZ_IMAGE_RLD): return "rld";
        case(FZ_IMAGE_BMP): return "bmp";
        case(FZ_IMAGE_GIF): return "gif";
        case(FZ_IMAGE_JBIG2): return "jb2";
        case(FZ_IMAGE_JPEG): return "jpeg";
        case(FZ_IMAGE_JPX): return "jpx";
        case(FZ_IMAGE_JXR): return "jxr";
        case(FZ_IMAGE_PNG): return "png";
        case(FZ_IMAGE_PNM): return "pnm";
        case(FZ_IMAGE_TIFF): return "tiff";
        default: return "n/a";
    }
}

void JM_make_image_block(fz_stext_block *block, PyObject *block_dict)
{
    fz_context* ctx = mupdf::internal_context_get();
    fz_image *image = block->u.i.image;
    fz_buffer *buf = NULL, *freebuf = NULL, *mask_buf = NULL;
    fz_compressed_buffer *buffer = fz_compressed_image_buffer(ctx, image);
    fz_var(buf);
    fz_var(freebuf);
    fz_var(mask_buf);
    int n = fz_colorspace_n(ctx, image->colorspace);
    int w = image->w;
    int h = image->h;
    const char *ext = "";
    int type = FZ_IMAGE_UNKNOWN;
    if (buffer) {
        type = buffer->params.type;
        ext = JM_image_extension(type);
    }
    if (type < FZ_IMAGE_BMP || type == FZ_IMAGE_JBIG2)
        type = FZ_IMAGE_UNKNOWN;
    PyObject *bytes = NULL;
    fz_var(bytes);
    PyObject *mask_bytes = NULL;
    fz_var(mask_bytes);
    fz_try(ctx) {
        if (!buffer || type == FZ_IMAGE_UNKNOWN)
        {
            buf = freebuf = fz_new_buffer_from_image_as_png(ctx, image, fz_default_color_params);
            ext = "png";
        }
        else if (n == 4 && strcmp(ext, "jpeg") == 0) // JPEG CMYK needs another step
        {
            buf = freebuf = fz_new_buffer_from_image_as_jpeg(ctx, image, fz_default_color_params, 95, 1);        
        }
        else
        {
            buf = buffer->buffer;
        } 
        bytes = JM_BinFromBuffer(buf);
        if (image->mask) {
            mask_buf = fz_new_buffer_from_image_as_png(ctx, image->mask, fz_default_color_params);
            mask_bytes = JM_BinFromBuffer(mask_buf);
        } else {
            mask_bytes = Py_BuildValue("s", NULL);
        }
    }
    fz_always(ctx) {
        if (!bytes)
            bytes = PyBytes_FromString("");
        DICT_SETITEM_DROP(block_dict, dictkey_width,
                        Py_BuildValue("i", w));
        DICT_SETITEM_DROP(block_dict, dictkey_height,
                        Py_BuildValue("i", h));
        DICT_SETITEM_DROP(block_dict, dictkey_ext,
                        Py_BuildValue("s", ext));
        DICT_SETITEM_DROP(block_dict, dictkey_colorspace,
                        Py_BuildValue("i", n));
        DICT_SETITEM_DROP(block_dict, dictkey_xres,
                        Py_BuildValue("i", image->xres));
        DICT_SETITEM_DROP(block_dict, dictkey_yres,
                        Py_BuildValue("i", image->xres));
        DICT_SETITEM_DROP(block_dict, dictkey_bpc,
                        Py_BuildValue("i", (int) image->bpc));
        DICT_SETITEM_DROP(block_dict, dictkey_matrix,
                        JM_py_from_matrix(block->u.i.transform));
        DICT_SETITEM_DROP(block_dict, dictkey_size,
                        Py_BuildValue("n", PyBytes_Size(bytes)));
        DICT_SETITEM_DROP(block_dict, dictkey_image, bytes);
        DICT_SETITEMSTR_DROP(block_dict, "mask", mask_bytes);
        fz_drop_buffer(ctx, mask_buf);
        fz_drop_buffer(ctx, freebuf);
    }
    fz_catch(ctx)
    {
        fz_ignore_error(ctx);
    }
    return;
}


void JM_make_vector_block(fz_stext_block *block, PyObject *block_dict)
{
    DICT_SETITEM_DROP(block_dict, dictkey_bbox, JM_py_from_rect(block->bbox));
    DICT_SETITEMSTR_DROP(block_dict, "stroked", JM_BOOL(block->u.v.flags & FZ_STEXT_VECTOR_IS_STROKED));
    DICT_SETITEMSTR_DROP(block_dict, "isrect", JM_BOOL(block->u.v.flags & FZ_STEXT_VECTOR_IS_RECTANGLE));
    DICT_SETITEMSTR_DROP(block_dict, "continues", JM_BOOL(block->u.v.flags & FZ_STEXT_VECTOR_CONTINUES));
    int color = (int) block->u.v.argb & 0xffffff;  // extract color components
    int alpha = block->u.v.argb >> 24;  // extract alpha value
    DICT_SETITEM_DROP(block_dict, dictkey_color, Py_BuildValue("i", color));
    DICT_SETITEMSTR_DROP(block_dict, "alpha", Py_BuildValue("i", alpha));
    return;
}

void JM_make_grid_block(fz_stext_block *block, PyObject *block_dict)
{
    Py_ssize_t i;
    PyObject *pos;

    DICT_SETITEM_DROP(block_dict, dictkey_bbox, JM_py_from_rect(block->bbox));

    DICT_SETITEM_DROP(block_dict, dictkey_type, Py_BuildValue("i", block->type));

    DICT_SETITEMSTR_DROP(block_dict, "max_uncertain", Py_BuildValue("ii",
        block->u.b.xs->max_uncertainty,
        block->u.b.ys->max_uncertainty));

    // x coordinates with uncertainties
    pos = PyList_New((size_t) block->u.b.xs->len);
    for (i = 0; i <  block->u.b.xs->len; i++)
    {
        PyList_SetItem(pos, i, Py_BuildValue("fi",
            block->u.b.xs->list[i].pos,
            block->u.b.xs->list[i].uncertainty));
    }
    DICT_SETITEMSTR_DROP(block_dict, "xpos", pos);

    // y coordinates with uncertainties
    pos = PyList_New((size_t) block->u.b.ys->len);
    for (i = 0; i <  block->u.b.ys->len; i++)
    {
        PyList_SetItem(pos, i, Py_BuildValue("fi",
            block->u.b.ys->list[i].pos,
            block->u.b.ys->list[i].uncertainty));
    }
    DICT_SETITEMSTR_DROP(block_dict, "ypos", pos);
    
    return;
}


void make_table_dict(fz_stext_page *tp, PyObject *table_dict, PyObject *bbox)
{
    fz_rect bounds = JM_rect_from_py(bbox);
    fz_stext_block *block;

    try
    {
#if MUPDF_VERSION_GE(1, 28, 1)
      block = mupdf::ll_fz_find_table_within_bounds(tp, bounds, NULL);
#else
      block = mupdf::ll_fz_find_table_within_bounds(tp, bounds);
#endif
    }
    catch (std::exception&)
    {
        /* Ignore failure to find a table structure. */
        return;
    }

    if (!block)
    {
        /* No table structure found. */
        return;
    }
    // Check if a table structure was found
    if (block->type == FZ_STEXT_BLOCK_GRID)
    {
        JM_make_grid_block(block, table_dict);
        return;
    }
    if (block->type == FZ_STEXT_BLOCK_STRUCT &&
        block->u.s.down &&
        block->u.s.down->first_block &&
        block->u.s.down->first_block->type == FZ_STEXT_BLOCK_GRID)
    {
        JM_make_grid_block(block->u.s.down->first_block, table_dict);
    }

}


static void JM_make_text_block(fz_stext_block *block, PyObject *block_dict, int raw, fz_buffer *buff, fz_rect tp_rect)
{
    fz_stext_line *line;
    PyObject *line_list = PyList_New(0), *line_dict;
    fz_rect block_rect = fz_empty_rect;
    for (line = block->u.t.first_line; line; line = line->next) {
        if (fz_is_empty_rect(fz_intersect_rect(tp_rect, line->bbox)) &&
            !fz_is_infinite_rect(tp_rect)) {
            continue;
        }
        line_dict = PyDict_New();
        mupdf::FzStextLine line2(line);
        mupdf::FzBuffer buff2( mupdf::ll_fz_keep_buffer( buff));
        mupdf::FzRect tp_rect2( tp_rect);
        mupdf::FzRect line_rect2 = JM_make_spanlist(
                line_dict,
                line2,
                raw,
                buff2,
                tp_rect2
                );
        fz_rect& line_rect = *line_rect2.internal();
        block_rect = fz_union_rect(block_rect, line_rect);
        DICT_SETITEM_DROP(line_dict, dictkey_wmode,
                    Py_BuildValue("i", line->wmode));
        DICT_SETITEM_DROP(line_dict, dictkey_dir, JM_py_from_point(line->dir));
        DICT_SETITEM_DROP(line_dict, dictkey_bbox,
                    JM_py_from_rect(line_rect));
        LIST_APPEND_DROP(line_list, line_dict);
    }
    DICT_SETITEM_DROP(block_dict, dictkey_bbox, JM_py_from_rect(block_rect));
    DICT_SETITEM_DROP(block_dict, dictkey_lines, line_list);
    return;
}


void JM_make_struct_block(fz_stext_block *block, PyObject *block_dict)
{
    DICT_SETITEMSTR_DROP(block_dict, "index", Py_BuildValue("i",block->u.s.index));
    if (block->u.s.down)
    {
        DICT_SETITEMSTR_DROP(block_dict, "raw", Py_BuildValue("s",block->u.s.down->raw));
        DICT_SETITEMSTR_DROP(block_dict, "std", Py_BuildValue("s",fz_structure_to_string(block->u.s.down->standard)));
    }
    
}


int _as_dict(PyObject *block_list, fz_stext_block *block, fz_buffer *text_buffer, int raw, fz_rect tp_rect, int block_n)
{
    /*
    Recursive function for output by blocks as identified by the
    MuPDF SEGMENT logic.
    */
    PyObject *block_dict;
    while (block)
    {
        switch (block->type)
        {
            case FZ_STEXT_BLOCK_STRUCT:
                if (block->u.s.down && block->u.s.down->first_block)
                {
                    block_n++;
                    block_dict = PyDict_New();
                    DICT_SETITEM_DROP(block_dict, dictkey_type, Py_BuildValue("i", block->type));
                    DICT_SETITEM_DROP(block_dict, dictkey_number, Py_BuildValue("i", block_n));
                    DICT_SETITEM_DROP(block_dict, dictkey_bbox, JM_py_from_rect(block->bbox));
                    JM_make_struct_block(block, block_dict);
                    PyObject *subblocks = PyList_New(0);
                    block_n = _as_dict(subblocks, block->u.s.down->first_block, text_buffer, raw, tp_rect, block_n);
                    DICT_SETITEM_DROP(block_dict, dictkey_blocks, subblocks);
                    LIST_APPEND_DROP(block_list, block_dict);
                }
            break;

            case FZ_STEXT_BLOCK_TEXT:
                if (JM_rects_overlap(tp_rect, block->bbox) || fz_is_infinite_rect(tp_rect))
                {
                    block_dict = PyDict_New();
                    block_n++;
                    DICT_SETITEM_DROP(block_dict, dictkey_type, Py_BuildValue("i", block->type));
                    DICT_SETITEM_DROP(block_dict, dictkey_number, Py_BuildValue("i", block_n));
                    DICT_SETITEMSTR_DROP(block_dict, "flags", Py_BuildValue("i", block->u.t.flags));
                    JM_make_text_block(block, block_dict, raw, text_buffer, tp_rect);
                    LIST_APPEND_DROP(block_list, block_dict);
                }
            break;

            case FZ_STEXT_BLOCK_IMAGE:
                if (fz_contains_rect(tp_rect, block->bbox) || fz_is_infinite_rect(tp_rect))
                {
                    block_dict = PyDict_New();
                    block_n++;
                    DICT_SETITEM_DROP(block_dict, dictkey_type, Py_BuildValue("i", block->type));
                    DICT_SETITEM_DROP(block_dict, dictkey_number, Py_BuildValue("i", block_n));
                    DICT_SETITEM_DROP(block_dict, dictkey_bbox, JM_py_from_rect(block->bbox));
                    JM_make_image_block(block, block_dict);
                    LIST_APPEND_DROP(block_list, block_dict);
                }
            break;

            case FZ_STEXT_BLOCK_VECTOR:
                if (JM_rects_overlap(tp_rect, block->bbox) || fz_is_infinite_rect(tp_rect))
                {
                    block_dict = PyDict_New();
                    block_n++;
                    DICT_SETITEM_DROP(block_dict, dictkey_type, Py_BuildValue("i", block->type));
                    DICT_SETITEM_DROP(block_dict, dictkey_number, Py_BuildValue("i", block_n));
                    JM_make_vector_block(block, block_dict);
                    LIST_APPEND_DROP(block_list, block_dict);
                }
            break;

            case FZ_STEXT_BLOCK_GRID:
                if (JM_rects_overlap(tp_rect, block->bbox) || fz_is_infinite_rect(tp_rect))
                {
                    block_dict = PyDict_New();
                    block_n++;
                    DICT_SETITEM_DROP(block_dict, dictkey_type, Py_BuildValue("i", block->type));
                    DICT_SETITEM_DROP(block_dict, dictkey_number, Py_BuildValue("i", block_n));
                    JM_make_grid_block(block, block_dict);
                    LIST_APPEND_DROP(block_list, block_dict);
                }
            break;
        }
        block = block->next;
    }
    return block_n;
}

void JM_make_textpage_dict(fz_stext_page *tp, PyObject *page_dict, int raw)
{
    fz_context* ctx = mupdf::internal_context_get();
    fz_stext_block *block;
    fz_buffer *text_buffer = fz_new_buffer(ctx, 128);
    PyObject *block_list = PyList_New(0);
    fz_rect tp_rect = tp->mediabox;
    block = tp->first_block;
    int block_n = -1;
    block_n = _as_dict(block_list, block, text_buffer, raw, tp_rect, block_n);
    DICT_SETITEM_DROP(page_dict, dictkey_blocks, block_list);
    fz_drop_buffer(ctx, text_buffer);
}

//-----------------------------------------------------------------
// get one pixel as a list
//-----------------------------------------------------------------
PyObject *pixmap_pixel(fz_pixmap* pm, int x, int y)
{
    fz_context* ctx = mupdf::internal_context_get();
    PyObject *p = NULL;
    if (0
            || x < 0
            || x >= pm->w
            || y < 0
            || y >= pm->h
            )
    {
        throw std::range_error( MSG_PIXEL_OUTSIDE);
    }
    int n = pm->n;
    int stride = fz_pixmap_stride(ctx, pm);
    int i = stride * y + n * x;
    p = PyTuple_New(n);
    for (int j = 0; j < n; j++)
    {
        PyTuple_SET_ITEM(p, j, Py_BuildValue("i", pm->samples[i + j]));
    }
    return p;
}

int pixmap_n(mupdf::FzPixmap& pixmap)
{
    return mupdf::fz_pixmap_components( pixmap);
}

static int
JM_INT_ITEM(PyObject *obj, Py_ssize_t idx, int *result)
{
    PyObject *temp = PySequence_ITEM(obj, idx);
    if (!temp) return 1;
    if (PyLong_Check(temp)) {
        *result = (int) PyLong_AsLong(temp);
        Py_DECREF(temp);
    } else if (PyFloat_Check(temp)) {
        *result = (int) PyFloat_AsDouble(temp);
        Py_DECREF(temp);
    } else {
        Py_DECREF(temp);
        return 1;
    }
    if (PyErr_Occurred()) {
        PyErr_Clear();
        return 1;
    }
    return 0;
}

PyObject *set_pixel(fz_pixmap* pm, int x, int y, PyObject *color)
{
    fz_context* ctx = mupdf::internal_context_get();
    if (0
            || x < 0
            || x >= pm->w
            || y < 0
            || y >= pm->h
            )
    {
        throw std::range_error( MSG_PIXEL_OUTSIDE);
    }
    int n = pm->n;
    if (!PySequence_Check(color) || PySequence_Size(color) != n) {
        throw std::range_error(MSG_BAD_COLOR_SEQ);
    }
    int i, j;
    unsigned char c[5];
    for (j = 0; j < n; j++) {
        if (JM_INT_ITEM(color, j, &i) == 1) {
            throw std::range_error(MSG_BAD_COLOR_SEQ);
        }
        if (i < 0 or i >= 256) {
            throw std::range_error(MSG_BAD_COLOR_SEQ);
        }
        c[j] = (unsigned char) i;
    }
    int stride = fz_pixmap_stride(ctx, pm);
    i = stride * y + n * x;
    for (j = 0; j < n; j++) {
        pm->samples[i + j] = c[j];
    }
    Py_RETURN_NONE;
}
//-------------------------------------------
// make a buffer from an stext_page's text
//-------------------------------------------
fz_buffer *
JM_new_buffer_from_stext_page(fz_stext_page *page)
{
    fz_context* ctx = mupdf::internal_context_get();
    fz_stext_block *block;
    fz_stext_line *line;
    fz_stext_char *ch;
    fz_rect rect = page->mediabox;
    fz_buffer *buf = NULL;

    fz_try(ctx)
    {
        buf = fz_new_buffer(ctx, 256);
        for (block = page->first_block; block; block = block->next) {
            if (block->type == FZ_STEXT_BLOCK_TEXT) {
                for (line = block->u.t.first_line; line; line = line->next) {
                    for (ch = line->first_char; ch; ch = ch->next) {
                        if (!JM_rects_overlap(rect, JM_char_bbox(line, ch)) &&
                            !fz_is_infinite_rect(rect)) {
                            continue;
                        }
                        fz_append_rune(ctx, buf, ch->c);
                    }
                    fz_append_byte(ctx, buf, '\n');
                }
                fz_append_byte(ctx, buf, '\n');
            }
        }
    }
    fz_catch(ctx) {
        fz_drop_buffer(ctx, buf);
        mupdf::internal_throw_exception(ctx);
    }
    return buf;
}

static inline int canon(int c)
{
    /* TODO: proper unicode case folding */
    /* TODO: character equivalence (a matches ä, etc) */
    if (c == 0xA0 || c == 0x2028 || c == 0x2029)
        return ' ';
    if (c == '\r' || c == '\n' || c == '\t')
        return ' ';
    if (c >= 'A' && c <= 'Z')
        return c - 'A' + 'a';
    return c;
}

static inline int chartocanon(int *c, const char *s)
{
    int n = fz_chartorune(c, s);
    *c = canon(*c);
    return n;
}

static const char *match_string(const char *h, const char *n)
{
    int hc, nc;
    const char *e = h;
    h += chartocanon(&hc, h);
    n += chartocanon(&nc, n);
    while (hc == nc)
    {
        e = h;
        if (hc == ' ')
            do
                h += chartocanon(&hc, h);
            while (hc == ' ');
        else
            h += chartocanon(&hc, h);
        if (nc == ' ')
            do
                n += chartocanon(&nc, n);
            while (nc == ' ');
        else
            n += chartocanon(&nc, n);
    }
    return nc == 0 ? e : NULL;
}


static const char *find_string(const char *s, const char *needle, const char **endp)
{
    const char *end;
    while (*s)
    {
        end = match_string(s, needle);
        if (end)
        {
            *endp = end;
            return s;
        }
        ++s;
    }
    *endp = NULL;
    return NULL;
}

struct highlight
{
    Py_ssize_t len;
    PyObject *quads;
    float hfuzz, vfuzz;
};


static int
JM_FLOAT_ITEM(PyObject *obj, Py_ssize_t idx, double *result)
{
    PyObject *temp = PySequence_ITEM(obj, idx);
    if (!temp) return 1;
    *result = PyFloat_AsDouble(temp);
    Py_DECREF(temp);
    if (PyErr_Occurred()) {
        PyErr_Clear();
        return 1;
    }
    return 0;
}


//-----------------------------------------------------------------------------
// fz_quad from PySequence. Four floats are treated as rect.
// Else must be four pairs of floats.
//-----------------------------------------------------------------------------
static fz_quad
JM_quad_from_py(PyObject *r)
{
    fz_quad q = fz_make_quad(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT,
                             FZ_MAX_INF_RECT, FZ_MIN_INF_RECT,
                             FZ_MIN_INF_RECT, FZ_MAX_INF_RECT,
                             FZ_MAX_INF_RECT, FZ_MAX_INF_RECT);
    fz_point p[4];
    double test, x, y;
    Py_ssize_t i;
    PyObject *obj = NULL;

    if (!r || !PySequence_Check(r) || PySequence_Size(r) != 4)
        return q;

    if (JM_FLOAT_ITEM(r, 0, &test) == 0)
        return fz_quad_from_rect(JM_rect_from_py(r));

    for (i = 0; i < 4; i++) {
        obj = PySequence_ITEM(r, i);  // next point item
        if (!obj || !PySequence_Check(obj) || PySequence_Size(obj) != 2)
            goto exit_result;  // invalid: cancel the rest

        if (JM_FLOAT_ITEM(obj, 0, &x) == 1) goto exit_result;
        if (JM_FLOAT_ITEM(obj, 1, &y) == 1) goto exit_result;
        if (x < FZ_MIN_INF_RECT) x = FZ_MIN_INF_RECT;
        if (y < FZ_MIN_INF_RECT) y = FZ_MIN_INF_RECT;
        if (x > FZ_MAX_INF_RECT) x = FZ_MAX_INF_RECT;
        if (y > FZ_MAX_INF_RECT) y = FZ_MAX_INF_RECT;
        p[i] = fz_make_point((float) x, (float) y);

        Py_CLEAR(obj);
    }
    q.ul = p[0];
    q.ur = p[1];
    q.ll = p[2];
    q.lr = p[3];
    return q;

    exit_result:;
    Py_CLEAR(obj);
    return q;
}

static float hdist(fz_point *dir, fz_point *a, fz_point *b)
{
    float dx = b->x - a->x;
    float dy = b->y - a->y;
    return fz_abs(dx * dir->x + dy * dir->y);
}

static float vdist(fz_point *dir, fz_point *a, fz_point *b)
{
    float dx = b->x - a->x;
    float dy = b->y - a->y;
    return fz_abs(dx * dir->y + dy * dir->x);
}

static void on_highlight_char(fz_context *ctx, void *arg, fz_stext_line *line, fz_stext_char *ch)
{
    struct highlight* hits = (struct highlight*) arg;
    float vfuzz = ch->size * hits->vfuzz;
    float hfuzz = ch->size * hits->hfuzz;
    fz_quad ch_quad = JM_char_quad(line, ch);
    if (hits->len > 0) {
        PyObject *quad = PySequence_ITEM(hits->quads, hits->len - 1);
        fz_quad end = JM_quad_from_py(quad);
        Py_DECREF(quad);
        if (hdist(&line->dir, &end.lr, &ch_quad.ll) < hfuzz
            && vdist(&line->dir, &end.lr, &ch_quad.ll) < vfuzz
            && hdist(&line->dir, &end.ur, &ch_quad.ul) < hfuzz
            && vdist(&line->dir, &end.ur, &ch_quad.ul) < vfuzz)
        {
            end.ur = ch_quad.ur;
            end.lr = ch_quad.lr;
            quad = JM_py_from_quad(end);
            PyList_SetItem(hits->quads, hits->len - 1, quad);
            return;
        }
    }
    LIST_APPEND_DROP(hits->quads, JM_py_from_quad(ch_quad));
    hits->len++;
}


PyObject* JM_search_stext_page(fz_stext_page *page, const char *needle)
{
    fz_context* ctx = mupdf::internal_context_get();
    struct highlight hits;
    fz_stext_block *block;
    fz_stext_line *line;
    fz_stext_char *ch;
    fz_buffer *buffer = NULL;
    const char *haystack, *begin, *end;
    fz_rect rect = page->mediabox;
    int c, inside;

    if (strlen(needle) == 0) Py_RETURN_NONE;
    PyObject *quads = PyList_New(0);
    hits.len = 0;
    hits.quads = quads;
    hits.hfuzz = 0.2f; /* merge kerns but not large gaps */
    hits.vfuzz = 0.1f;

    fz_try(ctx) {
        buffer = JM_new_buffer_from_stext_page( page);
        haystack = fz_string_from_buffer(ctx, buffer);
        begin = find_string(haystack, needle, &end);
        if (!begin) goto no_more_matches;

        inside = 0;
        for (block = page->first_block; block; block = block->next) {
            if (block->type != FZ_STEXT_BLOCK_TEXT) {
                continue;
            }
            for (line = block->u.t.first_line; line; line = line->next) {
                for (ch = line->first_char; ch; ch = ch->next) {
                    if (!fz_is_infinite_rect(rect) &&
                        !JM_rects_overlap(rect, JM_char_bbox(line, ch))) {
                            goto next_char;
                        }
try_new_match:
                    if (!inside) {
                        if (haystack >= begin) inside = 1;
                    }
                    if (inside) {
                        if (haystack < end) {
                            on_highlight_char(ctx, &hits, line, ch);
                        } else {
                            inside = 0;
                            begin = find_string(haystack, needle, &end);
                            if (!begin) goto no_more_matches;
                            else goto try_new_match;
                        }
                    }
                    haystack += fz_chartorune(&c, haystack);
next_char:;
                }
                assert(*haystack == '\n');
                ++haystack;
            }
            assert(*haystack == '\n');
            ++haystack;
        }
no_more_matches:;
    }
    fz_always(ctx)
        fz_drop_buffer(ctx, buffer);
    fz_catch(ctx)
        mupdf::internal_throw_exception(ctx);

    return quads;
}

void pixmap_copy( fz_pixmap* pm, const fz_pixmap* src, int n)
{
    assert(pm->w == src->w);
    assert(pm->h == src->h);
    assert(n <= pm->n);
    assert(n <= src->n);

    if (pm->n == src->n)
    {
        // identical samples
        assert(pm->stride == src->stride);
        memcpy(pm->samples, src->samples, pm->w * pm->h * pm->n);
    }
    else
    {
        int nn;
        int do_alpha;
        if (pm->n > src->n)
        {
            assert(pm->n == src->n + 1);
            nn = src->n;
            assert(!src->alpha);
            assert(pm->alpha);
            do_alpha = 1;
        }
        else
        {
            assert(src->n == pm->n + 1);
            nn = pm->n;
            assert(src->alpha);
            assert(!pm->alpha);
            do_alpha = 0;
        }
        for (int y=0; y<pm->h; ++y)
        {
            for (int x=0; x<pm->w; ++x)
            {
                memcpy(
                        pm->samples + pm->stride * y + pm->n * x,
                        src->samples + src->stride * y + src->n * x,
                        nn
                        );
                if (do_alpha)
                {
                    pm->samples[pm->stride * y + pm->n * x + pm->n-1] = 255;
                }
            }
        }
    }
}


PyObject* ll_JM_color_count(fz_pixmap *pm, PyObject *clip)
{
    fz_context* ctx = mupdf::internal_context_get();
    PyObject* rc = PyDict_New();
    fz_irect irect = fz_pixmap_bbox(ctx, pm);
    irect = fz_intersect_irect(irect, fz_round_rect(JM_rect_from_py(clip)));
    if (fz_is_empty_irect(irect))
    {
        return rc;
    }
    size_t stride = pm->stride;
    size_t width = irect.x1 - irect.x0;
    size_t height = irect.y1 - irect.y0;
    size_t n = (size_t) pm->n;
    size_t substride = width * n;
    unsigned char* s = pm->samples + stride * (irect.y0 - pm->y) + n * (irect.x0 - pm->x);
    // Cache previous pixel.
    char oldpix[10];
    assert(n <= sizeof(oldpix));
    memcpy(oldpix, s, n);
    long cnt = 0;
    for (size_t i = 0; i < height; i++)
    {
        for (size_t j = 0; j < substride; j += n)
        {
            const char* newpix = (const char*) s + j;
            if (memcmp(oldpix, newpix, n))
            {
                /* Pixel differs from previous pixel, so update results with
                last run of pixels. We get a PyObject representation of pixel
                so we can look up in Python dict <rc>. */
                PyObject* pixel = PyBytes_FromStringAndSize(&oldpix[0], n);
                PyObject* c = PyDict_GetItem(rc, pixel);
                if (c) cnt += PyLong_AsLong(c);
                DICT_SETITEM_DROP(rc, pixel, PyLong_FromLong(cnt));
                Py_DECREF(pixel);
                /* Start next run of identical pixels. */
                cnt = 1;
                memcpy(oldpix, newpix, n);
            }
            else
            {
                cnt += 1;
            }
        }
        s += stride;
    }
    /* Update results with last pixel. */
    PyObject* pixel = PyBytes_FromStringAndSize(&oldpix[0], n);
    PyObject* c = PyDict_GetItem(rc, pixel);
    if (c) cnt += PyLong_AsLong(c);
    DICT_SETITEM_DROP(rc, pixel, PyLong_FromLong(cnt));
    Py_DECREF(pixel);
    PyErr_Clear();
    return rc;
}



#include <limits.h>
#if !defined(SWIG_NO_LLONG_MAX)
# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__)
#   define LLONG_MAX __LONG_LONG_MAX__
#   define LLONG_MIN (-LLONG_MAX - 1LL)
#   define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)
# endif
#endif


SWIGINTERN int
SWIG_AsVal_double (PyObject *obj, double *val)
{
  int res = SWIG_TypeError;
  if (PyFloat_Check(obj)) {
    if (val) *val = PyFloat_AsDouble(obj);
    return SWIG_OK;
  } else if (PyLong_Check(obj)) {
    double v = PyLong_AsDouble(obj);
    if (!PyErr_Occurred()) {
      if (val) *val = v;
      return SWIG_OK;
    } else {
      PyErr_Clear();
    }
  }
#ifdef SWIG_PYTHON_CAST_MODE
  {
    int dispatch = 0;
    double d = PyFloat_AsDouble(obj);
    if (!PyErr_Occurred()) {
      if (val) *val = d;
      return SWIG_AddCast(SWIG_OK);
    } else {
      PyErr_Clear();
    }
    if (!dispatch) {
      long v = PyLong_AsLong(obj);
      if (!PyErr_Occurred()) {
	if (val) *val = v;
	return SWIG_AddCast(SWIG_AddCast(SWIG_OK));
      } else {
	PyErr_Clear();
      }
    }
  }
#endif
  return res;
}


#include <errno.h>


#include <float.h>


#include <math.h>


SWIGINTERNINLINE int
SWIG_CanCastAsInteger(double *d, double min, double max) {
  double x = *d;
  if ((min <= x && x <= max)) {
   double fx, cx, rd;
   errno = 0;
   fx = floor(x);
   cx = ceil(x);
   rd =  ((x - fx) < 0.5) ? fx : cx; /* simple rint */
   if ((errno == EDOM) || (errno == ERANGE)) {
     errno = 0;
   } else {
     double summ, reps, diff;
     if (rd < x) {
       diff = x - rd;
     } else if (rd > x) {
       diff = rd - x;
     } else {
       return 1;
     }
     summ = rd + x;
     reps = diff/summ;
     if (reps < 8*DBL_EPSILON) {
       *d = rd;
       return 1;
     }
   }
  }
  return 0;
}


SWIGINTERN int
SWIG_AsVal_long (PyObject *obj, long* val)
{
  if (PyLong_Check(obj)) {
    long v = PyLong_AsLong(obj);
    if (!PyErr_Occurred()) {
      if (val) *val = v;
      return SWIG_OK;
    } else {
      PyErr_Clear();
      return SWIG_OverflowError;
    }
  }
#ifdef SWIG_PYTHON_CAST_MODE
  {
    int dispatch = 0;
    long v = PyLong_AsLong(obj);
    if (!PyErr_Occurred()) {
      if (val) *val = v;
      return SWIG_AddCast(SWIG_OK);
    } else {
      PyErr_Clear();
    }
    if (!dispatch) {
      double d;
      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));
      // Largest double not larger than LONG_MAX (not portably calculated easily)
      // Note that double(LONG_MAX) is stored in a double rounded up by one (for 64-bit long)
      // 0x7ffffffffffffc00LL == (int64_t)std::nextafter(double(__uint128_t(LONG_MAX)+1), double(0))
      const double long_max = sizeof(long) == 8 ? 0x7ffffffffffffc00LL : LONG_MAX;
      // No equivalent needed for 64-bit double(LONG_MIN) is exactly LONG_MIN
      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, long_max)) {
	if (val) *val = (long)(d);
	return res;
      }
    }
  }
#endif
  return SWIG_TypeError;
}


SWIGINTERN int
SWIG_AsVal_int (PyObject * obj, int *val)
{
  long v;
  int res = SWIG_AsVal_long (obj, &v);
  if (SWIG_IsOK(res)) {
    if ((v < INT_MIN || v > INT_MAX)) {
      return SWIG_OverflowError;
    } else {
      if (val) *val = static_cast< int >(v);
    }
  }  
  return res;
}


SWIGINTERNINLINE PyObject*
  SWIG_From_int  (int value)
{
  return PyLong_FromLong((long) value);
}


/* Getting isfinite working pre C99 across multiple platforms is non-trivial. Users can provide SWIG_isfinite on older platforms. */
#ifndef SWIG_isfinite
/* isfinite() is a macro for C99 */
# if defined(isfinite)
#  define SWIG_isfinite(X) (isfinite(X))
# elif defined(__cplusplus) && __cplusplus >= 201103L
/* Use a template so that this works whether isfinite() is std::isfinite() or
 * in the global namespace.  The reality seems to vary between compiler
 * versions.
 *
 * Make sure namespace std exists to avoid compiler warnings.
 *
 * extern "C++" is required as this fragment can end up inside an extern "C" { } block
 */
namespace std { }
extern "C++" template<typename T>
inline int SWIG_isfinite_func(T x) {
  using namespace std;
  return isfinite(x);
}
#  define SWIG_isfinite(X) (SWIG_isfinite_func(X))
# elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
#  define SWIG_isfinite(X) (__builtin_isfinite(X))
# elif defined(_MSC_VER)
#  define SWIG_isfinite(X) (_finite(X))
# elif defined(__sun) && defined(__SVR4)
#  include <ieeefp.h>
#  define SWIG_isfinite(X) (finite(X))
# endif
#endif


/* Accept infinite as a valid float value unless we are unable to check if a value is finite */
#ifdef SWIG_isfinite
# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX) && SWIG_isfinite(X))
#else
# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX))
#endif


SWIGINTERN int
SWIG_AsVal_float (PyObject * obj, float *val)
{
  double v;
  int res = SWIG_AsVal_double (obj, &v);
  if (SWIG_IsOK(res)) {
    if (SWIG_Float_Overflow_Check(v)) {
      return SWIG_OverflowError;
    } else {
      if (val) *val = static_cast< float >(v);
    }
  }  
  return res;
}


SWIGINTERN swig_type_info*
SWIG_pchar_descriptor(void)
{
  static swig_type_info* info = 0;
  if (!info) {
    info = SWIG_TypeQuery("_p_char");
  }
  return info;
}


/* Return string from Python obj. NOTE: obj must remain in scope in order
   to use the returned cptr (but only when alloc is set to SWIG_OLDOBJ) */
SWIGINTERN int
SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc)
{
  int use_binary = 0;       /* extract the value as raw bytes rather than as UTF-8 text */
  int is_binary = 0;        /* SWIG_BINARYSTR was passed: report the exact byte count */
  if (alloc != NULL) {
    is_binary = SWIG_IsBinaryStr(*alloc);
    use_binary = is_binary;
    *alloc = 0;
  }
#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
  use_binary = 1;
#endif
  if (use_binary ? PyBytes_Check(obj) : PyUnicode_Check(obj))
  {
    char *cstr = NULL;
    Py_ssize_t len = 0;
    PyObject *bytes = NULL;
    int ret = SWIG_OK;
    if (alloc)
      *alloc = SWIG_OLDOBJ;
    if (use_binary) {
      if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1)
        return SWIG_TypeError;
    } else {
      cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes);
      if (!cstr)
        return SWIG_TypeError;
      /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */
      if (bytes && cptr) {
        if (alloc) {
          size_t alen = (size_t)(len + 1);
          char *p = (new char[alen]());
          if (p == NULL) {
            SWIG_Py_XDECREF(bytes);
            return SWIG_MemoryError;
          }
          memcpy(p, cstr, alen);
          cstr = p;
          *alloc = SWIG_NEWOBJ;
        } else {
          /* alloc must be set in order to clean up allocated memory */
          SWIG_Py_XDECREF(bytes);
          return SWIG_RuntimeError;
        }
      }
    }
    if (cptr) *cptr = cstr;
    if (psize) *psize = is_binary ? (size_t)len : (size_t)(len + 1);
    SWIG_Py_XDECREF(bytes);
    return ret;
  } else {

    swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
    if (pchar_descriptor) {
      void* vptr = 0;
      if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) {
	if (cptr) *cptr = (char *) vptr;
	if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0;
	if (alloc) *alloc = SWIG_OLDOBJ;
	return SWIG_OK;
      }
    }
  }
  return SWIG_TypeError;
}





#define SWIG_FromCharPtrAndSize(carray, size) SWIG_FromBinaryCharPtrAndSize(carray, size, 0)
SWIGINTERNINLINE PyObject *
SWIG_FromBinaryCharPtrAndSize(const char* carray, size_t size, int flags)
{
  if (carray) {
    if (size > (size_t)PY_SSIZE_T_MAX) {
      swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
      return pchar_descriptor ? 
	SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void();
    } else {
#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
      return PyBytes_FromStringAndSize(carray, static_cast< Py_ssize_t >(size));
#else
      if (SWIG_IsBinaryStr(flags))
        return PyBytes_FromStringAndSize(carray, static_cast< Py_ssize_t >(size));
      return PyUnicode_DecodeUTF8(carray, static_cast< Py_ssize_t >(size), "surrogateescape");
#endif
    }
  } else {
    return SWIG_Py_Void();
  }
}


SWIGINTERNINLINE PyObject * 
SWIG_FromCharPtr(const char *cptr)
{ 
  return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0));
}


SWIGINTERNINLINE PyObject*
  SWIG_From_bool  (bool value)
{
  return PyBool_FromLong(value ? 1 : 0);
}

#ifdef __cplusplus
extern "C" {
#endif
SWIGINTERN PyObject *_wrap_page_merge(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  mupdf::PdfDocument *arg2 = 0 ;
  int arg3 ;
  int arg4 ;
  int arg5 ;
  int arg6 ;
  int arg7 ;
  mupdf::PdfGraftMap *arg8 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  int val4 ;
  int ecode4 = 0 ;
  int val5 ;
  int ecode5 = 0 ;
  int val6 ;
  int ecode6 = 0 ;
  int val7 ;
  int ecode7 = 0 ;
  void *argp8 = 0 ;
  int res8 = 0 ;
  PyObject *swig_obj[8] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "page_merge", 8, 8, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_merge" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_merge" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "page_merge" "', argument " "2"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_merge" "', argument " "2"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::PdfDocument * >(argp2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "page_merge" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
  if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "page_merge" "', argument " "4"" of type '" "int""'");
  } 
  arg4 = static_cast< int >(val4);
  ecode5 = SWIG_AsVal_int(swig_obj[4], &val5);
  if (!SWIG_IsOK(ecode5)) {
    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "page_merge" "', argument " "5"" of type '" "int""'");
  } 
  arg5 = static_cast< int >(val5);
  ecode6 = SWIG_AsVal_int(swig_obj[5], &val6);
  if (!SWIG_IsOK(ecode6)) {
    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "page_merge" "', argument " "6"" of type '" "int""'");
  } 
  arg6 = static_cast< int >(val6);
  ecode7 = SWIG_AsVal_int(swig_obj[6], &val7);
  if (!SWIG_IsOK(ecode7)) {
    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "page_merge" "', argument " "7"" of type '" "int""'");
  } 
  arg7 = static_cast< int >(val7);
  res8 = SWIG_ConvertPtr(swig_obj[7], &argp8, SWIGTYPE_p_mupdf__PdfGraftMap,  0 );
  if (!SWIG_IsOK(res8)) {
    SWIG_exception_fail(SWIG_ArgError(res8), "in method '" "page_merge" "', argument " "8"" of type '" "mupdf::PdfGraftMap &""'"); 
  }
  if (!argp8) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_merge" "', argument " "8"" of type '" "mupdf::PdfGraftMap &""'"); 
  }
  arg8 = reinterpret_cast< mupdf::PdfGraftMap * >(argp8);
  {
    try {
      page_merge(*arg1,*arg2,arg3,arg4,arg5,arg6,arg7,*arg8);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_merge_range(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  mupdf::PdfDocument *arg2 = 0 ;
  int arg3 ;
  int arg4 ;
  int arg5 ;
  int arg6 ;
  int arg7 ;
  int arg8 ;
  int arg9 ;
  mupdf::PdfGraftMap *arg10 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  int val4 ;
  int ecode4 = 0 ;
  int val5 ;
  int ecode5 = 0 ;
  int val6 ;
  int ecode6 = 0 ;
  int val7 ;
  int ecode7 = 0 ;
  int val8 ;
  int ecode8 = 0 ;
  int val9 ;
  int ecode9 = 0 ;
  void *argp10 = 0 ;
  int res10 = 0 ;
  PyObject *swig_obj[10] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_merge_range", 10, 10, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_merge_range" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_merge_range" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "JM_merge_range" "', argument " "2"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_merge_range" "', argument " "2"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::PdfDocument * >(argp2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "JM_merge_range" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
  if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "JM_merge_range" "', argument " "4"" of type '" "int""'");
  } 
  arg4 = static_cast< int >(val4);
  ecode5 = SWIG_AsVal_int(swig_obj[4], &val5);
  if (!SWIG_IsOK(ecode5)) {
    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "JM_merge_range" "', argument " "5"" of type '" "int""'");
  } 
  arg5 = static_cast< int >(val5);
  ecode6 = SWIG_AsVal_int(swig_obj[5], &val6);
  if (!SWIG_IsOK(ecode6)) {
    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "JM_merge_range" "', argument " "6"" of type '" "int""'");
  } 
  arg6 = static_cast< int >(val6);
  ecode7 = SWIG_AsVal_int(swig_obj[6], &val7);
  if (!SWIG_IsOK(ecode7)) {
    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "JM_merge_range" "', argument " "7"" of type '" "int""'");
  } 
  arg7 = static_cast< int >(val7);
  ecode8 = SWIG_AsVal_int(swig_obj[7], &val8);
  if (!SWIG_IsOK(ecode8)) {
    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "JM_merge_range" "', argument " "8"" of type '" "int""'");
  } 
  arg8 = static_cast< int >(val8);
  ecode9 = SWIG_AsVal_int(swig_obj[8], &val9);
  if (!SWIG_IsOK(ecode9)) {
    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "JM_merge_range" "', argument " "9"" of type '" "int""'");
  } 
  arg9 = static_cast< int >(val9);
  res10 = SWIG_ConvertPtr(swig_obj[9], &argp10, SWIGTYPE_p_mupdf__PdfGraftMap,  0 );
  if (!SWIG_IsOK(res10)) {
    SWIG_exception_fail(SWIG_ArgError(res10), "in method '" "JM_merge_range" "', argument " "10"" of type '" "mupdf::PdfGraftMap &""'"); 
  }
  if (!argp10) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_merge_range" "', argument " "10"" of type '" "mupdf::PdfGraftMap &""'"); 
  }
  arg10 = reinterpret_cast< mupdf::PdfGraftMap * >(argp10);
  {
    try {
      JM_merge_range(*arg1,*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,*arg10);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_FzDocument_insert_pdf(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  mupdf::FzDocument *arg2 = 0 ;
  int arg3 ;
  int arg4 ;
  int arg5 ;
  int arg6 ;
  int arg7 ;
  int arg8 ;
  int arg9 ;
  int arg10 ;
  mupdf::PdfGraftMap *arg11 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  int val4 ;
  int ecode4 = 0 ;
  int val5 ;
  int ecode5 = 0 ;
  int val6 ;
  int ecode6 = 0 ;
  int val7 ;
  int ecode7 = 0 ;
  int val8 ;
  int ecode8 = 0 ;
  int val9 ;
  int ecode9 = 0 ;
  int val10 ;
  int ecode10 = 0 ;
  void *argp11 = 0 ;
  int res11 = 0 ;
  PyObject *swig_obj[11] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "FzDocument_insert_pdf", 11, 11, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "FzDocument_insert_pdf" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "FzDocument_insert_pdf" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "FzDocument_insert_pdf" "', argument " "2"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "FzDocument_insert_pdf" "', argument " "2"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::FzDocument * >(argp2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "FzDocument_insert_pdf" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
  if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "FzDocument_insert_pdf" "', argument " "4"" of type '" "int""'");
  } 
  arg4 = static_cast< int >(val4);
  ecode5 = SWIG_AsVal_int(swig_obj[4], &val5);
  if (!SWIG_IsOK(ecode5)) {
    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "FzDocument_insert_pdf" "', argument " "5"" of type '" "int""'");
  } 
  arg5 = static_cast< int >(val5);
  ecode6 = SWIG_AsVal_int(swig_obj[5], &val6);
  if (!SWIG_IsOK(ecode6)) {
    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "FzDocument_insert_pdf" "', argument " "6"" of type '" "int""'");
  } 
  arg6 = static_cast< int >(val6);
  ecode7 = SWIG_AsVal_int(swig_obj[6], &val7);
  if (!SWIG_IsOK(ecode7)) {
    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "FzDocument_insert_pdf" "', argument " "7"" of type '" "int""'");
  } 
  arg7 = static_cast< int >(val7);
  ecode8 = SWIG_AsVal_int(swig_obj[7], &val8);
  if (!SWIG_IsOK(ecode8)) {
    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "FzDocument_insert_pdf" "', argument " "8"" of type '" "int""'");
  } 
  arg8 = static_cast< int >(val8);
  ecode9 = SWIG_AsVal_int(swig_obj[8], &val9);
  if (!SWIG_IsOK(ecode9)) {
    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "FzDocument_insert_pdf" "', argument " "9"" of type '" "int""'");
  } 
  arg9 = static_cast< int >(val9);
  ecode10 = SWIG_AsVal_int(swig_obj[9], &val10);
  if (!SWIG_IsOK(ecode10)) {
    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "FzDocument_insert_pdf" "', argument " "10"" of type '" "int""'");
  } 
  arg10 = static_cast< int >(val10);
  res11 = SWIG_ConvertPtr(swig_obj[10], &argp11, SWIGTYPE_p_mupdf__PdfGraftMap,  0 );
  if (!SWIG_IsOK(res11)) {
    SWIG_exception_fail(SWIG_ArgError(res11), "in method '" "FzDocument_insert_pdf" "', argument " "11"" of type '" "mupdf::PdfGraftMap &""'"); 
  }
  if (!argp11) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "FzDocument_insert_pdf" "', argument " "11"" of type '" "mupdf::PdfGraftMap &""'"); 
  }
  arg11 = reinterpret_cast< mupdf::PdfGraftMap * >(argp11);
  {
    try {
      FzDocument_insert_pdf(*arg1,*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,*arg11);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_xref(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  PyObject *swig_obj[2] ;
  int result;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "page_xref", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_xref" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_xref" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "page_xref" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  {
    try {
      result = (int)page_xref(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  float arg3 ;
  float arg4 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  float val3 ;
  int ecode3 = 0 ;
  float val4 ;
  int ecode4 = 0 ;
  
  (void)self;
  if ((nobjs < 4) || (nobjs > 4)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "_newPage" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_newPage" "', argument " "3"" of type '" "float""'");
  } 
  arg3 = static_cast< float >(val3);
  ecode4 = SWIG_AsVal_float(swig_obj[3], &val4);
  if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "_newPage" "', argument " "4"" of type '" "float""'");
  } 
  arg4 = static_cast< float >(val4);
  {
    try {
      _newPage(*arg1,arg2,arg3,arg4);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  float arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  float val3 ;
  int ecode3 = 0 ;
  
  (void)self;
  if ((nobjs < 3) || (nobjs > 3)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "_newPage" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_newPage" "', argument " "3"" of type '" "float""'");
  } 
  arg3 = static_cast< float >(val3);
  {
    try {
      _newPage(*arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_2(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "_newPage" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  {
    try {
      _newPage(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_3(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  
  (void)self;
  if ((nobjs < 1) || (nobjs > 1)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  {
    try {
      _newPage(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_4(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  int arg2 ;
  float arg3 ;
  float arg4 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  float val3 ;
  int ecode3 = 0 ;
  float val4 ;
  int ecode4 = 0 ;
  
  (void)self;
  if ((nobjs < 4) || (nobjs > 4)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "_newPage" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_newPage" "', argument " "3"" of type '" "float""'");
  } 
  arg3 = static_cast< float >(val3);
  ecode4 = SWIG_AsVal_float(swig_obj[3], &val4);
  if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "_newPage" "', argument " "4"" of type '" "float""'");
  } 
  arg4 = static_cast< float >(val4);
  {
    try {
      _newPage(*arg1,arg2,arg3,arg4);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_5(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  int arg2 ;
  float arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  float val3 ;
  int ecode3 = 0 ;
  
  (void)self;
  if ((nobjs < 3) || (nobjs > 3)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "_newPage" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_newPage" "', argument " "3"" of type '" "float""'");
  } 
  arg3 = static_cast< float >(val3);
  {
    try {
      _newPage(*arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_6(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  int arg2 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "_newPage" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  {
    try {
      _newPage(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage__SWIG_7(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  
  (void)self;
  if ((nobjs < 1) || (nobjs > 1)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_newPage" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  {
    try {
      _newPage(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__newPage(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[5] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "_newPage", 0, 4, argv))) SWIG_fail;
  --argc;
  if (argc == 1) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      return _wrap__newPage__SWIG_3(self, argc, argv);
    }
  }
  if (argc == 1) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      return _wrap__newPage__SWIG_7(self, argc, argv);
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        return _wrap__newPage__SWIG_6(self, argc, argv);
      }
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        return _wrap__newPage__SWIG_2(self, argc, argv);
      }
    }
  }
  if (argc == 3) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_float(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          return _wrap__newPage__SWIG_1(self, argc, argv);
        }
      }
    }
  }
  if (argc == 3) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_float(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          return _wrap__newPage__SWIG_5(self, argc, argv);
        }
      }
    }
  }
  if (argc == 4) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_float(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          {
            int res = SWIG_AsVal_float(argv[3], NULL);
            _v = SWIG_CheckState(res);
          }
          if (_v) {
            return _wrap__newPage__SWIG_4(self, argc, argv);
          }
        }
      }
    }
  }
  if (argc == 4) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_float(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          {
            int res = SWIG_AsVal_float(argv[3], NULL);
            _v = SWIG_CheckState(res);
          }
          if (_v) {
            return _wrap__newPage__SWIG_0(self, argc, argv);
          }
        }
      }
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function '_newPage'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    _newPage(mupdf::FzDocument &,int,float,float)\n"
    "    _newPage(mupdf::FzDocument &,int,float)\n"
    "    _newPage(mupdf::FzDocument &,int)\n"
    "    _newPage(mupdf::FzDocument &)\n"
    "    _newPage(mupdf::PdfDocument &,int,float,float)\n"
    "    _newPage(mupdf::PdfDocument &,int,float)\n"
    "    _newPage(mupdf::PdfDocument &,int)\n"
    "    _newPage(mupdf::PdfDocument &)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_JM_add_annot_id(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfAnnot *arg1 = 0 ;
  char *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int res2 ;
  char *buf2 = 0 ;
  int alloc2 = 0 ;
  PyObject *swig_obj[2] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_add_annot_id", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfAnnot,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_add_annot_id" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_add_annot_id" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfAnnot * >(argp1);
  res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2);
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "JM_add_annot_id" "', argument " "2"" of type '" "char const *""'");
  }
  arg2 = reinterpret_cast< char * >(buf2);
  {
    try {
      JM_add_annot_id(*arg1,(char const *)arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
  return resultobj;
fail:
  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_set_annot_callout_line(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfAnnot *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  int arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *swig_obj[3] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_set_annot_callout_line", 3, 3, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfAnnot,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_set_annot_callout_line" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_set_annot_callout_line" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfAnnot * >(argp1);
  arg2 = swig_obj[1];
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "JM_set_annot_callout_line" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  {
    try {
      JM_set_annot_callout_line(*arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_get_annot_id_list(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfPage *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  SwigValueWrapper< std::vector< std::string > > result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_get_annot_id_list" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_get_annot_id_list" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfPage * >(argp1);
  {
    try {
      result = JM_get_annot_id_list(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new std::vector< std::string >(result)), SWIGTYPE_p_std__vectorT_std__string_t, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__add_caret_annot__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfPage *arg1 = 0 ;
  mupdf::FzPoint *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  mupdf::PdfAnnot result;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_add_caret_annot" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_add_caret_annot" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfPage * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__FzPoint,  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_add_caret_annot" "', argument " "2"" of type '" "mupdf::FzPoint &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_add_caret_annot" "', argument " "2"" of type '" "mupdf::FzPoint &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::FzPoint * >(argp2);
  {
    try {
      result = _add_caret_annot(*arg1,*arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::PdfAnnot(result)), SWIGTYPE_p_mupdf__PdfAnnot, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__add_caret_annot__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  mupdf::FzPoint *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  mupdf::PdfAnnot result;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_add_caret_annot" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_add_caret_annot" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__FzPoint,  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_add_caret_annot" "', argument " "2"" of type '" "mupdf::FzPoint &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "_add_caret_annot" "', argument " "2"" of type '" "mupdf::FzPoint &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::FzPoint * >(argp2);
  {
    try {
      result = _add_caret_annot(*arg1,*arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::PdfAnnot(result)), SWIGTYPE_p_mupdf__PdfAnnot, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap__add_caret_annot(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[3] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "_add_caret_annot", 0, 2, argv))) SWIG_fail;
  --argc;
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      void *vptr = 0;
      int res = SWIG_ConvertPtr(argv[1], &vptr, SWIGTYPE_p_mupdf__FzPoint, SWIG_POINTER_NO_NULL);
      _v = SWIG_CheckState(res);
      if (_v) {
        return _wrap__add_caret_annot__SWIG_0(self, argc, argv);
      }
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      void *vptr = 0;
      int res = SWIG_ConvertPtr(argv[1], &vptr, SWIGTYPE_p_mupdf__FzPoint, SWIG_POINTER_NO_NULL);
      _v = SWIG_CheckState(res);
      if (_v) {
        return _wrap__add_caret_annot__SWIG_1(self, argc, argv);
      }
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function '_add_caret_annot'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    _add_caret_annot(mupdf::PdfPage &,mupdf::FzPoint &)\n"
    "    _add_caret_annot(mupdf::FzPage &,mupdf::FzPoint &)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_Tools_parse_da(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfAnnot *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  char *result = 0 ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfAnnot,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tools_parse_da" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Tools_parse_da" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfAnnot * >(argp1);
  {
    try {
      result = (char *)Tools_parse_da(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_FromCharPtr((const char *)result);
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Annot_getAP(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfAnnot *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfAnnot,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Annot_getAP" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Annot_getAP" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfAnnot * >(argp1);
  {
    try {
      result = (PyObject *)Annot_getAP(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Tools_update_da(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfAnnot *arg1 = 0 ;
  char *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int res2 ;
  char *buf2 = 0 ;
  int alloc2 = 0 ;
  PyObject *swig_obj[2] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "Tools_update_da", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfAnnot,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tools_update_da" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Tools_update_da" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfAnnot * >(argp1);
  res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2);
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Tools_update_da" "', argument " "2"" of type '" "char const *""'");
  }
  arg2 = reinterpret_cast< char * >(buf2);
  {
    try {
      Tools_update_da(*arg1,(char const *)arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
  return resultobj;
fail:
  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_point_from_py(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  PyObject *arg1 = 0 ;
  PyObject *swig_obj[1] ;
  mupdf::FzPoint result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  arg1 = swig_obj[0];
  {
    try {
      result = JM_point_from_py(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzPoint(result)), SWIGTYPE_p_mupdf__FzPoint, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Annot_rect(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfAnnot *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  mupdf::FzRect result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfAnnot,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Annot_rect" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Annot_rect" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfAnnot * >(argp1);
  {
    try {
      result = Annot_rect(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzRect(result)), SWIGTYPE_p_mupdf__FzRect, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_util_transform_rect(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  PyObject *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  PyObject *swig_obj[2] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "util_transform_rect", 2, 2, swig_obj)) SWIG_fail;
  arg1 = swig_obj[0];
  arg2 = swig_obj[1];
  {
    try {
      result = (PyObject *)util_transform_rect(arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Annot_rect3(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfAnnot *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfAnnot,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Annot_rect3" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Annot_rect3" "', argument " "1"" of type '" "mupdf::PdfAnnot &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfAnnot * >(argp1);
  {
    try {
      result = (PyObject *)Annot_rect3(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Page_derotate_matrix__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfPage *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  mupdf::FzMatrix result;
  
  (void)self;
  if ((nobjs < 1) || (nobjs > 1)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Page_derotate_matrix" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Page_derotate_matrix" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfPage * >(argp1);
  {
    try {
      result = Page_derotate_matrix(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzMatrix(result)), SWIGTYPE_p_mupdf__FzMatrix, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Page_derotate_matrix__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  mupdf::FzMatrix result;
  
  (void)self;
  if ((nobjs < 1) || (nobjs > 1)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Page_derotate_matrix" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Page_derotate_matrix" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  {
    try {
      result = Page_derotate_matrix(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzMatrix(result)), SWIGTYPE_p_mupdf__FzMatrix, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Page_derotate_matrix(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[2] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "Page_derotate_matrix", 0, 1, argv))) SWIG_fail;
  --argc;
  if (argc == 1) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      return _wrap_Page_derotate_matrix__SWIG_0(self, argc, argv);
    }
  }
  if (argc == 1) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      return _wrap_Page_derotate_matrix__SWIG_1(self, argc, argv);
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'Page_derotate_matrix'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    Page_derotate_matrix(mupdf::PdfPage &)\n"
    "    Page_derotate_matrix(mupdf::FzPage &)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_JM_get_annot_xref_list(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfObj *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfObj,  0  | 0);
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_get_annot_xref_list" "', argument " "1"" of type '" "mupdf::PdfObj const &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_get_annot_xref_list" "', argument " "1"" of type '" "mupdf::PdfObj const &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfObj * >(argp1);
  {
    try {
      result = (PyObject *)JM_get_annot_xref_list((mupdf::PdfObj const &)*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_xref_object__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  int arg2 ;
  int arg3 ;
  int arg4 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  int val4 ;
  int ecode4 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 4) || (nobjs > 4)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "xref_object" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "xref_object" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
  if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "xref_object" "', argument " "4"" of type '" "int""'");
  } 
  arg4 = static_cast< int >(val4);
  {
    try {
      result = (PyObject *)xref_object(*arg1,arg2,arg3,arg4);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_xref_object__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  int arg2 ;
  int arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 3) || (nobjs > 3)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "xref_object" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "xref_object" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  {
    try {
      result = (PyObject *)xref_object(*arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_xref_object__SWIG_2(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  int arg2 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "xref_object" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  {
    try {
      result = (PyObject *)xref_object(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_xref_object__SWIG_3(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  int arg3 ;
  int arg4 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  int val4 ;
  int ecode4 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 4) || (nobjs > 4)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "xref_object" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "xref_object" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
  if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "xref_object" "', argument " "4"" of type '" "int""'");
  } 
  arg4 = static_cast< int >(val4);
  {
    try {
      result = (PyObject *)xref_object(*arg1,arg2,arg3,arg4);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_xref_object__SWIG_4(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  int arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 3) || (nobjs > 3)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "xref_object" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "xref_object" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  {
    try {
      result = (PyObject *)xref_object(*arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_xref_object__SWIG_5(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "xref_object" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "xref_object" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  {
    try {
      result = (PyObject *)xref_object(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_xref_object(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[5] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "xref_object", 0, 4, argv))) SWIG_fail;
  --argc;
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        return _wrap_xref_object__SWIG_2(self, argc, argv);
      }
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        return _wrap_xref_object__SWIG_5(self, argc, argv);
      }
    }
  }
  if (argc == 3) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_int(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          return _wrap_xref_object__SWIG_4(self, argc, argv);
        }
      }
    }
  }
  if (argc == 3) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_int(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          return _wrap_xref_object__SWIG_1(self, argc, argv);
        }
      }
    }
  }
  if (argc == 4) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_int(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          {
            int res = SWIG_AsVal_int(argv[3], NULL);
            _v = SWIG_CheckState(res);
          }
          if (_v) {
            return _wrap_xref_object__SWIG_0(self, argc, argv);
          }
        }
      }
    }
  }
  if (argc == 4) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        {
          int res = SWIG_AsVal_int(argv[2], NULL);
          _v = SWIG_CheckState(res);
        }
        if (_v) {
          {
            int res = SWIG_AsVal_int(argv[3], NULL);
            _v = SWIG_CheckState(res);
          }
          if (_v) {
            return _wrap_xref_object__SWIG_3(self, argc, argv);
          }
        }
      }
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'xref_object'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    xref_object(mupdf::PdfDocument &,int,int,int)\n"
    "    xref_object(mupdf::PdfDocument &,int,int)\n"
    "    xref_object(mupdf::PdfDocument &,int)\n"
    "    xref_object(mupdf::FzDocument &,int,int,int)\n"
    "    xref_object(mupdf::FzDocument &,int,int)\n"
    "    xref_object(mupdf::FzDocument &,int)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_Link_is_external(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzLink *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzLink,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Link_is_external" "', argument " "1"" of type '" "mupdf::FzLink &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Link_is_external" "', argument " "1"" of type '" "mupdf::FzLink &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzLink * >(argp1);
  {
    try {
      result = (PyObject *)Link_is_external(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Page_addAnnot_FromString__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfPage *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Page_addAnnot_FromString" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Page_addAnnot_FromString" "', argument " "1"" of type '" "mupdf::PdfPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfPage * >(argp1);
  arg2 = swig_obj[1];
  {
    try {
      result = (PyObject *)Page_addAnnot_FromString(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Page_addAnnot_FromString__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Page_addAnnot_FromString" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Page_addAnnot_FromString" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  arg2 = swig_obj[1];
  {
    try {
      result = (PyObject *)Page_addAnnot_FromString(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Page_addAnnot_FromString(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[3] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "Page_addAnnot_FromString", 0, 2, argv))) SWIG_fail;
  --argc;
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      _v = (argv[1] != 0);
      if (_v) {
        return _wrap_Page_addAnnot_FromString__SWIG_0(self, argc, argv);
      }
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      _v = (argv[1] != 0);
      if (_v) {
        return _wrap_Page_addAnnot_FromString__SWIG_1(self, argc, argv);
      }
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'Page_addAnnot_FromString'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    Page_addAnnot_FromString(mupdf::PdfPage &,PyObject *)\n"
    "    Page_addAnnot_FromString(mupdf::FzPage &,PyObject *)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_Link_next(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzLink *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  mupdf::FzLink result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzLink,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Link_next" "', argument " "1"" of type '" "mupdf::FzLink &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Link_next" "', argument " "1"" of type '" "mupdf::FzLink &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzLink * >(argp1);
  {
    try {
      result = Link_next(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzLink(result)), SWIGTYPE_p_mupdf__FzLink, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_count_fz2(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  void *arg1 = 0 ;
  int res1 ;
  PyObject *swig_obj[1] ;
  int result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0],SWIG_as_voidptrptr(&arg1), 0, 0);
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_count_fz2" "', argument " "1"" of type '" "void *""'"); 
  }
  {
    try {
      result = (int)page_count_fz2(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_count_fz(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  int result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_count_fz" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_count_fz" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  {
    try {
      result = (int)page_count_fz(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_count_pdf(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  int result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_count_pdf" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_count_pdf" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  {
    try {
      result = (int)page_count_pdf(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_count__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int result;
  
  (void)self;
  if ((nobjs < 1) || (nobjs > 1)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_count" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_count" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  {
    try {
      result = (int)page_count(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_count__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int result;
  
  (void)self;
  if ((nobjs < 1) || (nobjs > 1)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_count" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_count" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  {
    try {
      result = (int)page_count(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_count(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[2] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "page_count", 0, 1, argv))) SWIG_fail;
  --argc;
  if (argc == 1) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      return _wrap_page_count__SWIG_0(self, argc, argv);
    }
  }
  if (argc == 1) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      return _wrap_page_count__SWIG_1(self, argc, argv);
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'page_count'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    page_count(mupdf::FzDocument &)\n"
    "    page_count(mupdf::PdfDocument &)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_page_annot_xrefs__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  int arg2 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_annot_xrefs" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_annot_xrefs" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "page_annot_xrefs" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  {
    try {
      result = (PyObject *)page_annot_xrefs(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_annot_xrefs__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  int arg2 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_annot_xrefs" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_annot_xrefs" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "page_annot_xrefs" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  {
    try {
      result = (PyObject *)page_annot_xrefs(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_annot_xrefs(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[3] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "page_annot_xrefs", 0, 2, argv))) SWIG_fail;
  --argc;
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        return _wrap_page_annot_xrefs__SWIG_0(self, argc, argv);
      }
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      {
        int res = SWIG_AsVal_int(argv[1], NULL);
        _v = SWIG_CheckState(res);
      }
      if (_v) {
        return _wrap_page_annot_xrefs__SWIG_1(self, argc, argv);
      }
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'page_annot_xrefs'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    page_annot_xrefs(mupdf::PdfDocument &,int)\n"
    "    page_annot_xrefs(mupdf::FzDocument &,int)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_Outline_is_external(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzOutline *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  bool result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_mupdf__FzOutline, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Outline_is_external" "', argument " "1"" of type '" "mupdf::FzOutline *""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzOutline * >(argp1);
  {
    try {
      result = (bool)Outline_is_external(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_bool(static_cast< bool >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Document_extend_toc_items__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::PdfDocument *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Document_extend_toc_items" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Document_extend_toc_items" "', argument " "1"" of type '" "mupdf::PdfDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfDocument * >(argp1);
  arg2 = swig_obj[1];
  {
    try {
      Document_extend_toc_items(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Document_extend_toc_items__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzDocument *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzDocument,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Document_extend_toc_items" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "Document_extend_toc_items" "', argument " "1"" of type '" "mupdf::FzDocument &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzDocument * >(argp1);
  arg2 = swig_obj[1];
  {
    try {
      Document_extend_toc_items(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_Document_extend_toc_items(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[3] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "Document_extend_toc_items", 0, 2, argv))) SWIG_fail;
  --argc;
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__PdfDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      _v = (argv[1] != 0);
      if (_v) {
        return _wrap_Document_extend_toc_items__SWIG_0(self, argc, argv);
      }
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzDocument, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      _v = (argv[1] != 0);
      if (_v) {
        return _wrap_Document_extend_toc_items__SWIG_1(self, argc, argv);
      }
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'Document_extend_toc_items'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    Document_extend_toc_items(mupdf::PdfDocument &,PyObject *)\n"
    "    Document_extend_toc_items(mupdf::FzDocument &,PyObject *)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_ll_fz_absi(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  int arg1 ;
  int val1 ;
  int ecode1 = 0 ;
  PyObject *swig_obj[1] ;
  int result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  ecode1 = SWIG_AsVal_int(swig_obj[0], &val1);
  if (!SWIG_IsOK(ecode1)) {
    SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ll_fz_absi" "', argument " "1"" of type '" "int""'");
  } 
  arg1 = static_cast< int >(val1);
  {
    try {
      result = (int)ll_fz_absi(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_new_texttrace_device(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  PyObject *arg1 = 0 ;
  PyObject *swig_obj[1] ;
  mupdf::FzDevice result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  arg1 = swig_obj[0];
  {
    try {
      result = JM_new_texttrace_device(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzDevice(result)), SWIGTYPE_p_mupdf__FzDevice, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_char_bbox(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzStextLine *arg1 = 0 ;
  mupdf::FzStextChar *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  PyObject *swig_obj[2] ;
  fz_rect result;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_char_bbox", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzStextLine,  0  | 0);
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_char_bbox" "', argument " "1"" of type '" "mupdf::FzStextLine const &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_char_bbox" "', argument " "1"" of type '" "mupdf::FzStextLine const &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzStextLine * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__FzStextChar,  0  | 0);
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "JM_char_bbox" "', argument " "2"" of type '" "mupdf::FzStextChar const &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_char_bbox" "', argument " "2"" of type '" "mupdf::FzStextChar const &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::FzStextChar * >(argp2);
  {
    try {
      result = JM_char_bbox((mupdf::FzStextLine const &)*arg1,(mupdf::FzStextChar const &)*arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new fz_rect(result)), SWIGTYPE_p_fz_rect, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_char_quad(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_stext_line *arg1 = 0 ;
  fz_stext_char *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  PyObject *swig_obj[2] ;
  fz_quad result;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_char_quad", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_stext_line, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_char_quad" "', argument " "1"" of type '" "fz_stext_line *""'"); 
  }
  arg1 = reinterpret_cast< fz_stext_line * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_fz_stext_char, 0 |  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "JM_char_quad" "', argument " "2"" of type '" "fz_stext_char *""'"); 
  }
  arg2 = reinterpret_cast< fz_stext_char * >(argp2);
  {
    try {
      result = JM_char_quad(arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new fz_quad(result)), SWIGTYPE_p_fz_quad, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_print_stext_page_as_text(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzBuffer *arg1 = 0 ;
  mupdf::FzStextPage *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  PyObject *swig_obj[2] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_print_stext_page_as_text", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzBuffer,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_print_stext_page_as_text" "', argument " "1"" of type '" "mupdf::FzBuffer &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_print_stext_page_as_text" "', argument " "1"" of type '" "mupdf::FzBuffer &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzBuffer * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__FzStextPage,  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "JM_print_stext_page_as_text" "', argument " "2"" of type '" "mupdf::FzStextPage &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_print_stext_page_as_text" "', argument " "2"" of type '" "mupdf::FzStextPage &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::FzStextPage * >(argp2);
  {
    try {
      JM_print_stext_page_as_text(*arg1,*arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_set_skip_quad_corrections(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  int arg1 ;
  int val1 ;
  int ecode1 = 0 ;
  PyObject *swig_obj[1] ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  ecode1 = SWIG_AsVal_int(swig_obj[0], &val1);
  if (!SWIG_IsOK(ecode1)) {
    SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "set_skip_quad_corrections" "', argument " "1"" of type '" "int""'");
  } 
  arg1 = static_cast< int >(val1);
  {
    try {
      set_skip_quad_corrections(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_set_subset_fontnames(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  int arg1 ;
  int val1 ;
  int ecode1 = 0 ;
  PyObject *swig_obj[1] ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  ecode1 = SWIG_AsVal_int(swig_obj[0], &val1);
  if (!SWIG_IsOK(ecode1)) {
    SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "set_subset_fontnames" "', argument " "1"" of type '" "int""'");
  } 
  arg1 = static_cast< int >(val1);
  {
    try {
      set_subset_fontnames(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_set_small_glyph_heights(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  int arg1 ;
  int val1 ;
  int ecode1 = 0 ;
  PyObject *swig_obj[1] ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  ecode1 = SWIG_AsVal_int(swig_obj[0], &val1);
  if (!SWIG_IsOK(ecode1)) {
    SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "set_small_glyph_heights" "', argument " "1"" of type '" "int""'");
  } 
  arg1 = static_cast< int >(val1);
  {
    try {
      set_small_glyph_heights(arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_cropbox(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::PdfObj *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  mupdf::FzRect result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__PdfObj,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_cropbox" "', argument " "1"" of type '" "mupdf::PdfObj &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_cropbox" "', argument " "1"" of type '" "mupdf::PdfObj &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::PdfObj * >(argp1);
  {
    try {
      result = JM_cropbox(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzRect(result)), SWIGTYPE_p_mupdf__FzRect, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_get_cdrawings__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  PyObject *arg3 = 0 ;
  PyObject *arg4 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 4) || (nobjs > 4)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  arg2 = swig_obj[1];
  arg3 = swig_obj[2];
  arg4 = swig_obj[3];
  {
    try {
      result = (PyObject *)get_cdrawings(*arg1,arg2,arg3,arg4);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_get_cdrawings__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  PyObject *arg3 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 3) || (nobjs > 3)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  arg2 = swig_obj[1];
  arg3 = swig_obj[2];
  {
    try {
      result = (PyObject *)get_cdrawings(*arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_get_cdrawings__SWIG_2(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 2) || (nobjs > 2)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  arg2 = swig_obj[1];
  {
    try {
      result = (PyObject *)get_cdrawings(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_get_cdrawings__SWIG_3(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *result = 0 ;
  
  (void)self;
  if ((nobjs < 1) || (nobjs > 1)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "get_cdrawings" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  {
    try {
      result = (PyObject *)get_cdrawings(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_get_cdrawings(PyObject *self, PyObject *args) {
  Py_ssize_t argc;
  PyObject *argv[5] = {
    0
  };
  
  if (!(argc = SWIG_Python_UnpackTuple(args, "get_cdrawings", 0, 4, argv))) SWIG_fail;
  --argc;
  if (argc == 1) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      return _wrap_get_cdrawings__SWIG_3(self, argc, argv);
    }
  }
  if (argc == 2) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      _v = (argv[1] != 0);
      if (_v) {
        return _wrap_get_cdrawings__SWIG_2(self, argc, argv);
      }
    }
  }
  if (argc == 3) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      _v = (argv[1] != 0);
      if (_v) {
        _v = (argv[2] != 0);
        if (_v) {
          return _wrap_get_cdrawings__SWIG_1(self, argc, argv);
        }
      }
    }
  }
  if (argc == 4) {
    int _v = 0;
    void *vptr = 0;
    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_mupdf__FzPage, SWIG_POINTER_NO_NULL);
    _v = SWIG_CheckState(res);
    if (_v) {
      _v = (argv[1] != 0);
      if (_v) {
        _v = (argv[2] != 0);
        if (_v) {
          _v = (argv[3] != 0);
          if (_v) {
            return _wrap_get_cdrawings__SWIG_0(self, argc, argv);
          }
        }
      }
    }
  }
  
fail:
  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'get_cdrawings'.\n"
    "  Possible C/C++ prototypes are:\n"
    "    get_cdrawings(mupdf::FzPage &,PyObject *,PyObject *,PyObject *)\n"
    "    get_cdrawings(mupdf::FzPage &,PyObject *,PyObject *)\n"
    "    get_cdrawings(mupdf::FzPage &,PyObject *)\n"
    "    get_cdrawings(mupdf::FzPage &)\n");
  return 0;
}


SWIGINTERN PyObject *_wrap_JM_make_spanlist(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  PyObject *arg1 = 0 ;
  mupdf::FzStextLine *arg2 = 0 ;
  int arg3 ;
  mupdf::FzBuffer *arg4 = 0 ;
  mupdf::FzRect *arg5 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  void *argp4 = 0 ;
  int res4 = 0 ;
  void *argp5 = 0 ;
  int res5 = 0 ;
  PyObject *swig_obj[5] ;
  mupdf::FzRect result;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_make_spanlist", 5, 5, swig_obj)) SWIG_fail;
  arg1 = swig_obj[0];
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_mupdf__FzStextLine,  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "JM_make_spanlist" "', argument " "2"" of type '" "mupdf::FzStextLine &""'"); 
  }
  if (!argp2) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_make_spanlist" "', argument " "2"" of type '" "mupdf::FzStextLine &""'"); 
  }
  arg2 = reinterpret_cast< mupdf::FzStextLine * >(argp2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "JM_make_spanlist" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  res4 = SWIG_ConvertPtr(swig_obj[3], &argp4, SWIGTYPE_p_mupdf__FzBuffer,  0 );
  if (!SWIG_IsOK(res4)) {
    SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "JM_make_spanlist" "', argument " "4"" of type '" "mupdf::FzBuffer &""'"); 
  }
  if (!argp4) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_make_spanlist" "', argument " "4"" of type '" "mupdf::FzBuffer &""'"); 
  }
  arg4 = reinterpret_cast< mupdf::FzBuffer * >(argp4);
  res5 = SWIG_ConvertPtr(swig_obj[4], &argp5, SWIGTYPE_p_mupdf__FzRect,  0 );
  if (!SWIG_IsOK(res5)) {
    SWIG_exception_fail(SWIG_ArgError(res5), "in method '" "JM_make_spanlist" "', argument " "5"" of type '" "mupdf::FzRect &""'"); 
  }
  if (!argp5) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "JM_make_spanlist" "', argument " "5"" of type '" "mupdf::FzRect &""'"); 
  }
  arg5 = reinterpret_cast< mupdf::FzRect * >(argp5);
  {
    try {
      result = JM_make_spanlist(arg1,*arg2,arg3,*arg4,*arg5);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj((new mupdf::FzRect(result)), SWIGTYPE_p_mupdf__FzRect, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_extractWORDS(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzStextPage *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[2] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "extractWORDS", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzStextPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "extractWORDS" "', argument " "1"" of type '" "mupdf::FzStextPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "extractWORDS" "', argument " "1"" of type '" "mupdf::FzStextPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzStextPage * >(argp1);
  arg2 = swig_obj[1];
  {
    try {
      result = (PyObject *)extractWORDS(*arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_extractBLOCKS(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzStextPage *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzStextPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "extractBLOCKS" "', argument " "1"" of type '" "mupdf::FzStextPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "extractBLOCKS" "', argument " "1"" of type '" "mupdf::FzStextPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzStextPage * >(argp1);
  {
    try {
      result = (PyObject *)extractBLOCKS(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_link_uri(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzLink *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzLink,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "link_uri" "', argument " "1"" of type '" "mupdf::FzLink &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "link_uri" "', argument " "1"" of type '" "mupdf::FzLink &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzLink * >(argp1);
  {
    try {
      result = (PyObject *)link_uri(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_page_get_textpage(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzPage *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  int arg3 ;
  PyObject *arg4 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *swig_obj[4] ;
  fz_stext_page *result = 0 ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "page_get_textpage", 4, 4, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPage,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "page_get_textpage" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "page_get_textpage" "', argument " "1"" of type '" "mupdf::FzPage &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPage * >(argp1);
  arg2 = swig_obj[1];
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "page_get_textpage" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  arg4 = swig_obj[3];
  {
    try {
      result = (fz_stext_page *)page_get_textpage(*arg1,arg2,arg3,arg4);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_fz_stext_page, 0 |  0 );
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_make_table_dict(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_stext_page *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  PyObject *arg3 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[3] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "make_table_dict", 3, 3, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_stext_page, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "make_table_dict" "', argument " "1"" of type '" "fz_stext_page *""'"); 
  }
  arg1 = reinterpret_cast< fz_stext_page * >(argp1);
  arg2 = swig_obj[1];
  arg3 = swig_obj[2];
  {
    try {
      make_table_dict(arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_make_textpage_dict(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_stext_page *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  int arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *swig_obj[3] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_make_textpage_dict", 3, 3, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_stext_page, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_make_textpage_dict" "', argument " "1"" of type '" "fz_stext_page *""'"); 
  }
  arg1 = reinterpret_cast< fz_stext_page * >(argp1);
  arg2 = swig_obj[1];
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "JM_make_textpage_dict" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  {
    try {
      JM_make_textpage_dict(arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_pixmap_pixel(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_pixmap *arg1 = 0 ;
  int arg2 ;
  int arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *swig_obj[3] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "pixmap_pixel", 3, 3, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_pixmap, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pixmap_pixel" "', argument " "1"" of type '" "fz_pixmap *""'"); 
  }
  arg1 = reinterpret_cast< fz_pixmap * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "pixmap_pixel" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "pixmap_pixel" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  {
    try {
      result = (PyObject *)pixmap_pixel(arg1,arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_pixmap_n(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  mupdf::FzPixmap *arg1 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  int result;
  
  (void)self;
  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_mupdf__FzPixmap,  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pixmap_n" "', argument " "1"" of type '" "mupdf::FzPixmap &""'"); 
  }
  if (!argp1) {
    SWIG_exception_fail(SWIG_NullReferenceError, "invalid null reference " "in method '" "pixmap_n" "', argument " "1"" of type '" "mupdf::FzPixmap &""'"); 
  }
  arg1 = reinterpret_cast< mupdf::FzPixmap * >(argp1);
  {
    try {
      result = (int)pixmap_n(*arg1);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_From_int(static_cast< int >(result));
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_JM_search_stext_page(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_stext_page *arg1 = 0 ;
  char *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int res2 ;
  char *buf2 = 0 ;
  int alloc2 = 0 ;
  PyObject *swig_obj[2] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "JM_search_stext_page", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_stext_page, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "JM_search_stext_page" "', argument " "1"" of type '" "fz_stext_page *""'"); 
  }
  arg1 = reinterpret_cast< fz_stext_page * >(argp1);
  res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2);
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "JM_search_stext_page" "', argument " "2"" of type '" "char const *""'");
  }
  arg2 = reinterpret_cast< char * >(buf2);
  {
    try {
      result = (PyObject *)JM_search_stext_page(arg1,(char const *)arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
  return resultobj;
fail:
  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
  return NULL;
}


SWIGINTERN PyObject *_wrap_set_pixel(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_pixmap *arg1 = 0 ;
  int arg2 ;
  int arg3 ;
  PyObject *arg4 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  int val2 ;
  int ecode2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *swig_obj[4] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "set_pixel", 4, 4, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_pixmap, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "set_pixel" "', argument " "1"" of type '" "fz_pixmap *""'"); 
  }
  arg1 = reinterpret_cast< fz_pixmap * >(argp1);
  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
  if (!SWIG_IsOK(ecode2)) {
    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "set_pixel" "', argument " "2"" of type '" "int""'");
  } 
  arg2 = static_cast< int >(val2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "set_pixel" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  arg4 = swig_obj[3];
  {
    try {
      result = (PyObject *)set_pixel(arg1,arg2,arg3,arg4);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_pixmap_copy(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_pixmap *arg1 = 0 ;
  fz_pixmap *arg2 = 0 ;
  int arg3 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  void *argp2 = 0 ;
  int res2 = 0 ;
  int val3 ;
  int ecode3 = 0 ;
  PyObject *swig_obj[3] ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "pixmap_copy", 3, 3, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_pixmap, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pixmap_copy" "', argument " "1"" of type '" "fz_pixmap *""'"); 
  }
  arg1 = reinterpret_cast< fz_pixmap * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_fz_pixmap, 0 |  0 );
  if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pixmap_copy" "', argument " "2"" of type '" "fz_pixmap const *""'"); 
  }
  arg2 = reinterpret_cast< fz_pixmap * >(argp2);
  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
  if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "pixmap_copy" "', argument " "3"" of type '" "int""'");
  } 
  arg3 = static_cast< int >(val3);
  {
    try {
      pixmap_copy(arg1,(fz_pixmap const *)arg2,arg3);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = SWIG_Py_Void();
  return resultobj;
fail:
  return NULL;
}


SWIGINTERN PyObject *_wrap_ll_JM_color_count(PyObject *self, PyObject *args) {
  PyObject *resultobj = 0;
  fz_pixmap *arg1 = 0 ;
  PyObject *arg2 = 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[2] ;
  PyObject *result = 0 ;
  
  (void)self;
  if (!SWIG_Python_UnpackTuple(args, "ll_JM_color_count", 2, 2, swig_obj)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_fz_pixmap, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ll_JM_color_count" "', argument " "1"" of type '" "fz_pixmap *""'"); 
  }
  arg1 = reinterpret_cast< fz_pixmap * >(argp1);
  arg2 = swig_obj[1];
  {
    try {
      result = (PyObject *)ll_JM_color_count(arg1,arg2);
    }
    
    /* this might not be ok on windows.
    catch (Swig::DirectorException &e) {
        SWIG_fail;
    }*/
    catch(std::exception& e) {
      SWIG_exception(SWIG_RuntimeError, e.what());
    }
    catch(...) {
      SWIG_exception(SWIG_RuntimeError, "Unknown exception");
    }
  }
  resultobj = result;
  if (!resultobj) SWIG_fail;
  return resultobj;
fail:
  return NULL;
}


static PyMethodDef SwigMethods[] = {
	 { "page_merge", _wrap_page_merge, METH_VARARGS, NULL},
	 { "JM_merge_range", _wrap_JM_merge_range, METH_VARARGS, NULL},
	 { "FzDocument_insert_pdf", _wrap_FzDocument_insert_pdf, METH_VARARGS, NULL},
	 { "page_xref", _wrap_page_xref, METH_VARARGS, NULL},
	 { "_newPage", _wrap__newPage, METH_VARARGS, NULL},
	 { "JM_add_annot_id", _wrap_JM_add_annot_id, METH_VARARGS, NULL},
	 { "JM_set_annot_callout_line", _wrap_JM_set_annot_callout_line, METH_VARARGS, NULL},
	 { "JM_get_annot_id_list", _wrap_JM_get_annot_id_list, METH_O, NULL},
	 { "_add_caret_annot", _wrap__add_caret_annot, METH_VARARGS, NULL},
	 { "Tools_parse_da", _wrap_Tools_parse_da, METH_O, NULL},
	 { "Annot_getAP", _wrap_Annot_getAP, METH_O, NULL},
	 { "Tools_update_da", _wrap_Tools_update_da, METH_VARARGS, NULL},
	 { "JM_point_from_py", _wrap_JM_point_from_py, METH_O, NULL},
	 { "Annot_rect", _wrap_Annot_rect, METH_O, NULL},
	 { "util_transform_rect", _wrap_util_transform_rect, METH_VARARGS, NULL},
	 { "Annot_rect3", _wrap_Annot_rect3, METH_O, NULL},
	 { "Page_derotate_matrix", _wrap_Page_derotate_matrix, METH_VARARGS, NULL},
	 { "JM_get_annot_xref_list", _wrap_JM_get_annot_xref_list, METH_O, NULL},
	 { "xref_object", _wrap_xref_object, METH_VARARGS, NULL},
	 { "Link_is_external", _wrap_Link_is_external, METH_O, NULL},
	 { "Page_addAnnot_FromString", _wrap_Page_addAnnot_FromString, METH_VARARGS, NULL},
	 { "Link_next", _wrap_Link_next, METH_O, NULL},
	 { "page_count_fz2", _wrap_page_count_fz2, METH_O, NULL},
	 { "page_count_fz", _wrap_page_count_fz, METH_O, NULL},
	 { "page_count_pdf", _wrap_page_count_pdf, METH_O, NULL},
	 { "page_count", _wrap_page_count, METH_VARARGS, NULL},
	 { "page_annot_xrefs", _wrap_page_annot_xrefs, METH_VARARGS, NULL},
	 { "Outline_is_external", _wrap_Outline_is_external, METH_O, NULL},
	 { "Document_extend_toc_items", _wrap_Document_extend_toc_items, METH_VARARGS, NULL},
	 { "ll_fz_absi", _wrap_ll_fz_absi, METH_O, NULL},
	 { "JM_new_texttrace_device", _wrap_JM_new_texttrace_device, METH_O, NULL},
	 { "JM_char_bbox", _wrap_JM_char_bbox, METH_VARARGS, NULL},
	 { "JM_char_quad", _wrap_JM_char_quad, METH_VARARGS, NULL},
	 { "JM_print_stext_page_as_text", _wrap_JM_print_stext_page_as_text, METH_VARARGS, NULL},
	 { "set_skip_quad_corrections", _wrap_set_skip_quad_corrections, METH_O, NULL},
	 { "set_subset_fontnames", _wrap_set_subset_fontnames, METH_O, NULL},
	 { "set_small_glyph_heights", _wrap_set_small_glyph_heights, METH_O, NULL},
	 { "JM_cropbox", _wrap_JM_cropbox, METH_O, NULL},
	 { "get_cdrawings", _wrap_get_cdrawings, METH_VARARGS, NULL},
	 { "JM_make_spanlist", _wrap_JM_make_spanlist, METH_VARARGS, NULL},
	 { "extractWORDS", _wrap_extractWORDS, METH_VARARGS, NULL},
	 { "extractBLOCKS", _wrap_extractBLOCKS, METH_O, NULL},
	 { "link_uri", _wrap_link_uri, METH_O, NULL},
	 { "page_get_textpage", _wrap_page_get_textpage, METH_VARARGS, NULL},
	 { "make_table_dict", _wrap_make_table_dict, METH_VARARGS, NULL},
	 { "JM_make_textpage_dict", _wrap_JM_make_textpage_dict, METH_VARARGS, NULL},
	 { "pixmap_pixel", _wrap_pixmap_pixel, METH_VARARGS, NULL},
	 { "pixmap_n", _wrap_pixmap_n, METH_O, NULL},
	 { "JM_search_stext_page", _wrap_JM_search_stext_page, METH_VARARGS, NULL},
	 { "set_pixel", _wrap_set_pixel, METH_VARARGS, NULL},
	 { "pixmap_copy", _wrap_pixmap_copy, METH_VARARGS, NULL},
	 { "ll_JM_color_count", _wrap_ll_JM_color_count, METH_VARARGS, NULL},
	 { NULL, NULL, 0, NULL }
};


/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */

static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_fz_pixmap = {"_p_fz_pixmap", "fz_pixmap *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_fz_quad = {"_p_fz_quad", "fz_quad *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_fz_rect = {"_p_fz_rect", "fz_rect *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_fz_stext_char = {"_p_fz_stext_char", "fz_stext_char *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_fz_stext_line = {"_p_fz_stext_line", "fz_stext_line *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_fz_stext_page = {"_p_fz_stext_page", "fz_stext_page *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzBuffer = {"_p_mupdf__FzBuffer", "mupdf::FzBuffer *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzDevice = {"_p_mupdf__FzDevice", "mupdf::FzDevice *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzDocument = {"_p_mupdf__FzDocument", "mupdf::FzDocument *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzLink = {"_p_mupdf__FzLink", "mupdf::FzLink *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzMatrix = {"_p_mupdf__FzMatrix", "mupdf::FzMatrix *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzOutline = {"_p_mupdf__FzOutline", "mupdf::FzOutline *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzPage = {"_p_mupdf__FzPage", "mupdf::FzPage *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzPixmap = {"_p_mupdf__FzPixmap", "mupdf::FzPixmap *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzPoint = {"_p_mupdf__FzPoint", "mupdf::FzPoint *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzRect = {"_p_mupdf__FzRect", "mupdf::FzRect *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzStextChar = {"_p_mupdf__FzStextChar", "mupdf::FzStextChar *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzStextLine = {"_p_mupdf__FzStextLine", "mupdf::FzStextLine *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__FzStextPage = {"_p_mupdf__FzStextPage", "mupdf::FzStextPage *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__PdfAnnot = {"_p_mupdf__PdfAnnot", "mupdf::PdfAnnot *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__PdfDocument = {"_p_mupdf__PdfDocument", "mupdf::PdfDocument *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__PdfGraftMap = {"_p_mupdf__PdfGraftMap", "mupdf::PdfGraftMap *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__PdfObj = {"_p_mupdf__PdfObj", "mupdf::PdfObj *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_mupdf__PdfPage = {"_p_mupdf__PdfPage", "mupdf::PdfPage *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_std__vectorT_std__string_t = {"_p_std__vectorT_std__string_t", "std::vector< std::string > *", 0, 0, (void*)0, 0};

static swig_type_info *swig_type_initial[] = {
  &_swigt__p_char,
  &_swigt__p_fz_pixmap,
  &_swigt__p_fz_quad,
  &_swigt__p_fz_rect,
  &_swigt__p_fz_stext_char,
  &_swigt__p_fz_stext_line,
  &_swigt__p_fz_stext_page,
  &_swigt__p_mupdf__FzBuffer,
  &_swigt__p_mupdf__FzDevice,
  &_swigt__p_mupdf__FzDocument,
  &_swigt__p_mupdf__FzLink,
  &_swigt__p_mupdf__FzMatrix,
  &_swigt__p_mupdf__FzOutline,
  &_swigt__p_mupdf__FzPage,
  &_swigt__p_mupdf__FzPixmap,
  &_swigt__p_mupdf__FzPoint,
  &_swigt__p_mupdf__FzRect,
  &_swigt__p_mupdf__FzStextChar,
  &_swigt__p_mupdf__FzStextLine,
  &_swigt__p_mupdf__FzStextPage,
  &_swigt__p_mupdf__PdfAnnot,
  &_swigt__p_mupdf__PdfDocument,
  &_swigt__p_mupdf__PdfGraftMap,
  &_swigt__p_mupdf__PdfObj,
  &_swigt__p_mupdf__PdfPage,
  &_swigt__p_std__vectorT_std__string_t,
};

static swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_fz_pixmap[] = {  {&_swigt__p_fz_pixmap, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_fz_quad[] = {  {&_swigt__p_fz_quad, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_fz_rect[] = {  {&_swigt__p_fz_rect, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_fz_stext_char[] = {  {&_swigt__p_fz_stext_char, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_fz_stext_line[] = {  {&_swigt__p_fz_stext_line, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_fz_stext_page[] = {  {&_swigt__p_fz_stext_page, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzBuffer[] = {  {&_swigt__p_mupdf__FzBuffer, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzDevice[] = {  {&_swigt__p_mupdf__FzDevice, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzDocument[] = {  {&_swigt__p_mupdf__FzDocument, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzLink[] = {  {&_swigt__p_mupdf__FzLink, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzMatrix[] = {  {&_swigt__p_mupdf__FzMatrix, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzOutline[] = {  {&_swigt__p_mupdf__FzOutline, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzPage[] = {  {&_swigt__p_mupdf__FzPage, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzPixmap[] = {  {&_swigt__p_mupdf__FzPixmap, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzPoint[] = {  {&_swigt__p_mupdf__FzPoint, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzRect[] = {  {&_swigt__p_mupdf__FzRect, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzStextChar[] = {  {&_swigt__p_mupdf__FzStextChar, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzStextLine[] = {  {&_swigt__p_mupdf__FzStextLine, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__FzStextPage[] = {  {&_swigt__p_mupdf__FzStextPage, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__PdfAnnot[] = {  {&_swigt__p_mupdf__PdfAnnot, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__PdfDocument[] = {  {&_swigt__p_mupdf__PdfDocument, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__PdfGraftMap[] = {  {&_swigt__p_mupdf__PdfGraftMap, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__PdfObj[] = {  {&_swigt__p_mupdf__PdfObj, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_mupdf__PdfPage[] = {  {&_swigt__p_mupdf__PdfPage, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_std__vectorT_std__string_t[] = {  {&_swigt__p_std__vectorT_std__string_t, 0, 0, 0},{0, 0, 0, 0}};

static swig_cast_info *swig_cast_initial[] = {
  _swigc__p_char,
  _swigc__p_fz_pixmap,
  _swigc__p_fz_quad,
  _swigc__p_fz_rect,
  _swigc__p_fz_stext_char,
  _swigc__p_fz_stext_line,
  _swigc__p_fz_stext_page,
  _swigc__p_mupdf__FzBuffer,
  _swigc__p_mupdf__FzDevice,
  _swigc__p_mupdf__FzDocument,
  _swigc__p_mupdf__FzLink,
  _swigc__p_mupdf__FzMatrix,
  _swigc__p_mupdf__FzOutline,
  _swigc__p_mupdf__FzPage,
  _swigc__p_mupdf__FzPixmap,
  _swigc__p_mupdf__FzPoint,
  _swigc__p_mupdf__FzRect,
  _swigc__p_mupdf__FzStextChar,
  _swigc__p_mupdf__FzStextLine,
  _swigc__p_mupdf__FzStextPage,
  _swigc__p_mupdf__PdfAnnot,
  _swigc__p_mupdf__PdfDocument,
  _swigc__p_mupdf__PdfGraftMap,
  _swigc__p_mupdf__PdfObj,
  _swigc__p_mupdf__PdfPage,
  _swigc__p_std__vectorT_std__string_t,
};


/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */

static swig_const_info swig_const_table[] = {
{0, 0, 0, 0.0, 0, 0}};

#ifdef __cplusplus
}
#endif
/* -----------------------------------------------------------------------------
 * Type initialization:
 * This problem is made tough by the requirement that no dynamic
 * memory is used. Also, since swig_type_info structures store pointers to
 * swig_cast_info structures and swig_cast_info structures store pointers back
 * to swig_type_info structures, we need some lookup code at initialization.
 * The idea is that swig generates all the structures that are needed.
 * The runtime then collects these partially filled structures.
 * The SWIG_InitializeModule function takes these initial arrays out of
 * swig_module, and does all the lookup, filling in the swig_module.types
 * array with the correct data and linking the correct swig_cast_info
 * structures together.
 *
 * The generated swig_type_info structures are assigned statically to an initial
 * array. We just loop through that array, and handle each type individually.
 * First we lookup if this type has been already loaded, and if so, use the
 * loaded structure instead of the generated one. Then we have to fill in the
 * cast dependencies. The cast data is initially stored in something like a
 * two-dimensional array. Each row corresponds to a type (there are the same
 * number of rows as there are in the swig_type_initial array). Each entry in
 * a column is one of the swig_cast_info structures for that type.
 * The cast_initial array is actually an array of arrays, because each row has
 * a variable number of columns.
 *
 * We loop through the cast[] array associated with the type and mark casts
 * which have not been defined in previously loaded modules by assigning
 * cast pointer value to cast->next. We also hash cast->type->name string
 * and store the value in the cast->value field. If we encounter swig_cast_info
 * structure that represents a cast to self we move it to the beginning
 * of the cast array. One trick we need to do is making sure the type pointer
 * in the swig_cast_info struct is correct.
 *
 * First off, we lookup the cast->type name to see if it is already loaded.
 * There are three cases to handle:
 *  1) If the cast->type has already been loaded AND the type we are adding
 *     casting info to has not been loaded (it is in this module), THEN we
 *     replace the cast->type pointer with the type pointer that has already
 *     been loaded.
 *  2) If BOTH types (the one we are adding casting info to, and the
 *     cast->type) are loaded, THEN the cast info has already been loaded by
 *     the previous module so we just ignore it.
 *  3) Finally, if cast->type has not already been loaded, then we add that
 *     swig_cast_info to the list (because the cast->type) pointer will
 *     be correct.
 *
 * Once the cast array has been set up AND it does have new casts that need
 * to be added we sort non-self cast entries to move filtered out entries
 * to the end of the array and to arrange the rest in the increasing order
 * of their type pointer values. We store the index of the last added entry
 * in the cast->value field of the entry[0] (overwriting the name hash). Then
 * we sort <next|value> fields of the remaining entries to arrange hash values
 * in the increasing order. This way cast->next->type->name field matches
 * the cast->value hash.
 *
 * Example:
 * Array of casts for type stored at 0x5000, cast to type stored at 0x3000
 * has already been loaded
 *
 *      After sweep-and-hash:   After sort-by-type:    After sort-by-hash:
 *        ________________       ________________       ________________
 *       |                |     |                |     |                |
 * Entry |  type = 0x5000 |     |  type = 0x5000 |     |  type = 0x5000 |
 *   0   |                |     |                |     |                |
 *       |  next = Entry0 |     |  next = Entry0 |     |  next = Entry0 |
 *       | value = 1212   |     | value = 3      |     | value = 3      |
 *       |                |     |                |     |                |
 *       |================|     |================|     |================|
 *       |                |     |                |     |                |
 * Entry |  type = 0x2000 |     |  type = 0x1000 |     |  type = 0x1000 |
 *   1   |                |     |                |     |                |
 *       |  next = Entry1 |     |  next = Entry1 |     |  next = Entry3 |
 *       | value = 3434   |     | value = 4545   |     | value = 2323   |
 *       |________________|     |________________|     |________________|
 *       |                |     |                |     |                |
 * Entry |  type = 0x3000 |     |  type = 0x2000 |     |  type = 0x2000 |
 *   2   |                |     |                |     |                |
 *       |  next = 0      |     |  next = Entry2 |     |  next = Entry2 |
 *       | value = 0      |     | value = 3434   |     | value = 3434   |
 *       |________________|     |________________|     |________________|
 *       |                |     |                |     |                |
 * Entry |  type = 0x1000 |     |  type = 0x4000 |     |  type = 0x4000 |
 *   3   |                |     |                |     |                |
 *       |  next = Entry3 |     |  next = Entry3 |     |  next = Entry1 |
 *       | value = 4545   |     | value = 2323   |     | value = 4545   |
 *       |________________|     |________________|     |________________|
 *       |                |     |                |     |                |
 * Entry |  type = 0x4000 |     |  type = 0x3000 |     |  type = 0x3000 |
 *   4   |                |     |                |     |                |
 *       |  next = Entry4 |     |  next = 0      |     |  next = 0      |
 *       | value = 2323   |     | value = 0      |     | value = 0      |
 *       |________________|     |________________|     |________________|
 *
 * Once the cast array has been initialized, we use cast[0]->next field to link
 * it into the list of cast arrays for the type.
 *              ____    ____    ____
 * type->cast->|next|->|next|->|next|->0
 *             |----|  |----|  |----|
 *             |----|  |----|  |----|
 *             |----|  |----|  |----|
 *
 * Subsequent cast resolution works as follows:
 *
 * 1. Check whether the type matches the first entry in the current cast array.
 * 2. If not, then do a binary search over the (0:cast->value] interval using
 *    either type address or the hash value of the type name.
 * 3. If not found, then move over to the next cast array (cast[0]->next).
 *
 * ----------------------------------------------------------------------------- */

#ifdef __cplusplus
extern "C" {
#if 0
} /* c-mode */
#endif
#endif

#if 0
#define SWIGRUNTIME_DEBUG
#endif

#ifndef SWIG_INIT_CLIENT_DATA_TYPE
#define SWIG_INIT_CLIENT_DATA_TYPE void *
#endif

/*
 * Sort function that puts cast entries with nonzero 'next' at the front
 * of the array while ordering them by addresses of their 'type' structs.
 */
SWIGINTERN int SWIG_CastCmpStruct(const void *pa, const void *pb) {
  swig_cast_info *pca = (swig_cast_info *)pa;
  swig_cast_info *pcb = (swig_cast_info *)pb;
  /* Entries with next != 0 (newly mapped) come before entries with next == 0 (already loaded) */
  if (!pca->next && pcb->next) return 1;
  if (pca->next && !pcb->next) return -1;
  /* Within the same group, sort by type pointer for binary search */
  if (pca->type < pcb->type) return -1;
  if (pca->type > pcb->type) return 1;
  return 0;
}

/*
 * Shell-sort 'next' and 'value' field pairs to order them by 'value'.
 */
SWIGINTERN void SWIG_CastHashSort(swig_cast_info *cast, int size) {
  const int hmax = size/9;
  int h, i;
  for(h = 1; h <= hmax; h = 3*h+1);
  for(; h > 0; h /= 3)
  {
    for(i = h; i < size; ++i)
    {
      swig_cast_info *p = cast[i].next;
      unsigned int hash = cast[i].value;
      int j = i;
      while(j >= h && hash < cast[j-h].value)
      {
        cast[j].next = cast[j-h].next;
        cast[j].value = cast[j-h].value;
        j -= h;
      }
      cast[j].next = p;
      cast[j].value = hash;
    }
  }
}

SWIGRUNTIME void
SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) {
  size_t i;
  swig_module_info *module_head, *iter;
  int init;
  
  /* check to see if the circular list has been setup, if not, set it up */
  if (swig_module.next==0) {
    /* Initialize the swig_module */
    swig_module.type_initial = swig_type_initial;
    swig_module.cast_initial = swig_cast_initial;
    swig_module.next = &swig_module;
    init = 1;
  } else {
    init = 0;
  }
  
  /* Try and load any already created modules */
  module_head = SWIG_GetModule(clientdata);
  if (!module_head) {
    /* This is the first module loaded for this interpreter */
    /* so set the swig module into the interpreter */
    SWIG_SetModule(clientdata, &swig_module);
  } else {
    /* the interpreter has loaded a SWIG module, but has it loaded this one? */
    iter=module_head;
    do {
      if (iter==&swig_module) {
        /* Our module is already in the list, so there's nothing more to do. */
        return;
      }
      iter=iter->next;
    } while (iter!= module_head);
    
    /* otherwise we must add our module into the list */
    swig_module.next = module_head->next;
    module_head->next = &swig_module;
  }
  
  /* When multiple interpreters are used, a module could have already been initialized in
       a different interpreter, but not yet have a pointer in this interpreter.
       In this case, we do not want to continue adding types... everything should be
       set up already */
  if (init == 0) return;
  
  /* Now work on filling in swig_module.types */
#ifdef SWIGRUNTIME_DEBUG
  printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size);
#endif
  for (i = 0; i < swig_module.size; ++i) {
    swig_type_info *type = 0;
    swig_type_info *target_type;
    swig_cast_info *cast, *first;
    int num_mapped = 0;
    
#ifdef SWIGRUNTIME_DEBUG
    printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name);
#endif
    
    /* if there is another module already loaded */
    if (swig_module.next != &swig_module) {
      type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
    }
    if (type) {
      /* Overwrite clientdata field */
#ifdef SWIGRUNTIME_DEBUG
      printf("SWIG_InitializeModule: found type %s\n", type->name);
#endif
      if (swig_module.type_initial[i]->clientdata) {
        type->clientdata = swig_module.type_initial[i]->clientdata;
#ifdef SWIGRUNTIME_DEBUG
        printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name);
#endif
      }
    } else {
      type = swig_module.type_initial[i];
    }
    
    /* Insert casting types */
    cast = first = swig_module.cast_initial[i];
    while (cast->type) {
      /* Don't need to add information already in the list */
      target_type = 0;
#ifdef SWIGRUNTIME_DEBUG
      printf("SWIG_InitializeModule: look cast %s\n", cast->type->name);
#endif
      if (swig_module.next != &swig_module) {
        target_type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
        if (target_type) {
          /* Target type already defined in another module */
#ifdef SWIGRUNTIME_DEBUG
          printf("SWIG_InitializeModule: found cast %s\n", target_type->name);
#endif
          if (type == swig_module.type_initial[i]) {
#ifdef SWIGRUNTIME_DEBUG
            printf("SWIG_InitializeModule: skip old type %s\n", target_type->name);
#endif
            cast->type = target_type;
            target_type = 0;
          } else {
            /* Check if this cast is already in the list */
            swig_cast_info *ocast = SWIG_TypeCheck(target_type->name, type);
#ifdef SWIGRUNTIME_DEBUG
            if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", target_type->name);
#endif
            if (!ocast) {
              cast->type = target_type;
              target_type = 0;
            }
          }
        }
      }
      
      if (!target_type) {
#ifdef SWIGRUNTIME_DEBUG
        printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name);
#endif
        /* Set inclusion mark for sorting */
        cast->next = cast;
        num_mapped++;
        
        if (type == cast->type) {
#ifdef SWIGRUNTIME_DEBUG
          printf("%s : self cast at pos [%li]\n", type->name, cast - first);
#endif
          if (cast - first) {
            /* Move cast to itself to the first entry in the array */
            
            swig_cast_info tmp = *cast;
            *cast = *first;
            *first = tmp;
          }
          first++;
          
        } else {
          cast->value = SWIG_Hash(cast->type->name, (unsigned int)strlen(cast->type->name));
        }
      }
      cast++;
    }
    
    if (num_mapped) {
      if (cast - first) {
        swig_cast_info *tmp;
        
        /* Sort casts by type address for binary search in SWIG_TypeCheckStruct */
        qsort(first, (size_t)(cast - first), sizeof(swig_cast_info), SWIG_CastCmpStruct);
        
        /* Remap back links for added entries */
        cast = swig_module.cast_initial[i] + num_mapped;
        for (tmp = first; tmp < cast; tmp++) {
          tmp->next = tmp;
        }
      }
      
      /* Set the value field of the first entry to the index of the last added entry */
      cast = swig_module.cast_initial[i];
      cast->value = (unsigned int)(num_mapped - 1);
      
      num_mapped -= (int)(first - cast);
      if (num_mapped > 1) {
        /* Sort <'next','value'> pairs by 'value' for binary search in SWIG_TypeCheck */
        
        SWIG_CastHashSort(first, num_mapped);
      }
      
      first = type->cast;
      if (first) {
        /* Link the current set into the list of cast arrays */
        cast->next = first->next;
        first->next = cast;
      } else {
        cast->next = 0;
        type->cast = cast;
      }
    }
    
    /* Set entry in modules->types array equal to the type */
    swig_module.types[i] = type;
  }
  swig_module.types[i] = 0;
  
#ifdef SWIGRUNTIME_DEBUG
  printf("**** SWIG_InitializeModule: Cast List ******\n");
  for (i = 0; i < swig_module.size; ++i) {
    int j = 0;
    swig_cast_info *cast = swig_module.cast_initial[i];
    printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name);
    while (cast->type) {
      printf("SWIG_InitializeModule: cast type %s\n", cast->type->name);
      cast++;
      ++j;
    }
    printf("---- Total casts: %d\n",j);
  }
  printf("**** SWIG_InitializeModule: Cast List ******\n");
#endif
}

/* This function will propagate the clientdata field of type to
* any new swig_type_info structures that have been added into the list
* of equivalent types.  It is like calling
* SWIG_TypeClientData(type, clientdata) a second time.
*/
SWIGRUNTIME void
SWIG_PropagateClientData(void) {
  size_t i;
  static int init_run = 0;
  
  if (init_run) return;
  init_run = 1;
  
  for (i = 0; i < swig_module.size; i++) {
    if (swig_module.types[i]->clientdata) {
      swig_cast_info *head, *cast;
      head = swig_module.types[i]->cast;
      while (head) {
        for (cast = head; (cast - head) <= head->value; cast++) {
          if (!cast->converter) {
            if (cast->type && !cast->type->clientdata)
            SWIG_TypeClientData(cast->type, swig_module.types[i]->clientdata);
          }
        }
        head = head->next;
      }
    }
  }
}

#ifdef __cplusplus
#if 0
{
  /* c-mode */
#endif
}
#endif



#ifdef __cplusplus
extern "C" {
#endif
  
  /* -----------------------------------------------------------------------------
   * constants/methods manipulation
   * ----------------------------------------------------------------------------- */
  
  /* Install Constants */
  SWIGINTERN void
  SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {
    PyObject *obj = 0;
    size_t i;
    for (i = 0; constants[i].type; ++i) {
      switch(constants[i].type) {
      case SWIG_PY_POINTER:
        obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
        break;
      case SWIG_PY_BINARY:
        obj = SWIG_NewPackedObj(constants[i].pvalue, (size_t)constants[i].lvalue, *(constants[i].ptype));
        break;
      default:
        obj = 0;
        break;
      }
      if (obj) {
        PyDict_SetItemString(d, constants[i].name, obj);
        SWIG_Py_DECREF(obj);
      }
    }
  }
  
  /* -----------------------------------------------------------------------------
   * Patch %callback methods' docstrings to hold the callback ptrs
   * -----------------------------------------------------------------------------*/
  
  SWIGINTERN void
  SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) {
    size_t i;
    for (i = 0; methods[i].ml_name; ++i) {
      const char *c = methods[i].ml_doc;
      if (!c) continue;
      c = strstr(c, "swig_ptr: ");
      if (c) {
        int j;
        const swig_const_info *ci = 0;
        const char *name = c + 10;
        for (j = 0; const_table[j].type; ++j) {
          if (strncmp(const_table[j].name, name, 
              strlen(const_table[j].name)) == 0) {
            ci = &(const_table[j]);
            break;
          }
        }
        if (ci) {
          void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;
          if (ptr) {
            size_t shift = (size_t)((ci->ptype) - types);
            swig_type_info *ty = types_initial[shift];
            size_t ldoc = (size_t)(c - methods[i].ml_doc);
            size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;
            char *ndoc = (char*)malloc(ldoc + lptr + 10);
            if (ndoc) {
              char *buff = ndoc;
              memcpy(buff, methods[i].ml_doc, ldoc);
              buff += ldoc;
              memcpy(buff, "swig_ptr: ", 10);
              buff += 10;
              SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);
              methods[i].ml_doc = ndoc;
            }
          }
        }
      }
    }
  } 
  
#ifdef __cplusplus
}
#endif




/* -----------------------------------------------------------------------------*
 *  Partial Init method
 * -----------------------------------------------------------------------------*/

SWIGINTERN int SWIG_mod_exec(PyObject *module);

#ifdef __cplusplus
extern "C"
#endif

SWIGEXPORT 
PyObject*
SWIG_init(void) {
  static PyModuleDef_Slot SwigSlots[] = {
    {
      Py_mod_exec, (void *)SWIG_mod_exec 
    },
#ifdef SWIGPYTHON_NOGIL
#ifdef Py_GIL_DISABLED
    {
      Py_mod_gil, Py_MOD_GIL_NOT_USED 
    },
#endif
#endif
    {
      0, NULL 
    }
  };
  
  static struct PyModuleDef SWIG_module = {
    PyModuleDef_HEAD_INIT,
    SWIG_name,
    NULL,
    0,
    SwigMethods,
    SwigSlots,
    NULL,
    NULL,
    NULL
  };
  
  return PyModuleDef_Init(&SWIG_module);
}

SWIGINTERN int SWIG_mod_exec(PyObject *m) {
  PyObject *d, *md, *globals;
  
#if defined(SWIGPYTHON_BUILTIN)
  static SwigPyClientData SwigPyObject_clientdata = {
    0, 0, 0, 0, 0, 0, 0
  };
  static PyGetSetDef this_getset_def = {
    (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL
  };
  static SwigPyGetSet thisown_getset_closure = {
    SwigPyObject_own,
    SwigPyObject_own
  };
  static PyGetSetDef thisown_getset_def = {
    (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure
  };
  PyTypeObject *builtin_pytype;
  int builtin_base_count;
  swig_type_info *builtin_basetype;
  PyObject *tuple;
  PyGetSetDescrObject *static_getset;
  PyTypeObject *metatype;
  PyTypeObject *swigpyobject;
  SwigPyClientData *cd;
  PyObject *public_interface, *public_symbol;
  PyObject *this_descr;
  PyObject *thisown_descr;
  PyObject *self = 0;
  int i;
  
  (void)builtin_pytype;
  (void)builtin_base_count;
  (void)builtin_basetype;
  (void)tuple;
  (void)static_getset;
  (void)self;
  
  /* Metaclass is used to implement static member variables */
  metatype = SwigPyObjectType_Type();
  assert(metatype);
  
  SwigPyStaticVar_Type();
#endif
  
  (void)globals;
  
  /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */
  SWIG_runtime_data_module();
  SWIG_This();
  SWIG_Python_TypeCache();
  SwigPyPacked_Type();
  SwigVarLink_Type();
#ifndef SWIGPYTHON_BUILTIN
  SwigPyObject_Type();
#endif
  
  /* Fix SwigMethods to carry the callback ptrs when needed */
  SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);
  
#ifdef SWIGPYTHON_NOGIL
#ifdef Py_GIL_DISABLED
  PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
#endif
#endif
  
  md = d = PyModule_GetDict(m);
  (void)md;
  
  SWIG_InitializeModule(0);
  
#ifdef SWIGPYTHON_BUILTIN
  swigpyobject = SwigPyObject_TypeOnce();
  
  SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject");
  assert(SwigPyObject_stype);
  cd = (SwigPyClientData*) SwigPyObject_stype->clientdata;
  if (!cd) {
    SwigPyObject_stype->clientdata = &SwigPyObject_clientdata;
    SwigPyObject_clientdata.pytype = swigpyobject;
  } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) {
    PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules.");
    return -1;
  }
  
  /* All objects have a 'this' attribute */
  this_descr = PyDescr_NewGetSet(SwigPyObject_Type(), &this_getset_def);
  (void)this_descr;
  
  /* All objects have a 'thisown' attribute */
  thisown_descr = PyDescr_NewGetSet(SwigPyObject_Type(), &thisown_getset_def);
  (void)thisown_descr;
  
  public_interface = PyList_New(0);
  public_symbol = 0;
  (void)public_symbol;
  
  PyDict_SetItemString(md, "__all__", public_interface);
  SWIG_Py_DECREF(public_interface);
  for (i = 0; SwigMethods[i].ml_name != NULL; ++i)
  SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name);
  for (i = 0; swig_const_table[i].name != 0; ++i)
  SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name);
#endif
  
  SWIG_InstallConstants(d,swig_const_table);
  
  
  /* Initialise some globals that require Python functions.
      
      [Prior to 2023-08-18 we initialised these global variables inline,
      but this causes a SEGV on Windows with Python-3.10 for `dictkey_c`
      (actually any string of length 1 failed).] */
  
  dictkey_align = PyUnicode_InternFromString("align");
  dictkey_ascender = PyUnicode_InternFromString("ascender");
  dictkey_bidi = PyUnicode_InternFromString("bidi");
  dictkey_bbox = PyUnicode_InternFromString("bbox");
  dictkey_blocks = PyUnicode_InternFromString("blocks");
  dictkey_bpc = PyUnicode_InternFromString("bpc");
  dictkey_c = PyUnicode_InternFromString("c");
  dictkey_chars = PyUnicode_InternFromString("chars");
  dictkey_color = PyUnicode_InternFromString("color");
  dictkey_colorspace = PyUnicode_InternFromString("colorspace");
  dictkey_content = PyUnicode_InternFromString("content");
  dictkey_creationDate = PyUnicode_InternFromString("creationDate");
  dictkey_cs_name = PyUnicode_InternFromString("cs-name");
  dictkey_da = PyUnicode_InternFromString("da");
  dictkey_dashes = PyUnicode_InternFromString("dashes");
  dictkey_desc = PyUnicode_InternFromString("descender");
  dictkey_descender = PyUnicode_InternFromString("descender");
  dictkey_dir = PyUnicode_InternFromString("dir");
  dictkey_effect = PyUnicode_InternFromString("effect");
  dictkey_ext = PyUnicode_InternFromString("ext");
  dictkey_filename = PyUnicode_InternFromString("filename");
  dictkey_fill = PyUnicode_InternFromString("fill");
  dictkey_flags = PyUnicode_InternFromString("flags");
  dictkey_char_flags = PyUnicode_InternFromString("char_flags");  /* Only used with mupdf >= 1.25.2. */
  dictkey_font = PyUnicode_InternFromString("font");
  dictkey_glyph = PyUnicode_InternFromString("glyph");
  dictkey_height = PyUnicode_InternFromString("height");
  dictkey_id = PyUnicode_InternFromString("id");
  dictkey_image = PyUnicode_InternFromString("image");
  dictkey_items = PyUnicode_InternFromString("items");
  dictkey_length = PyUnicode_InternFromString("length");
  dictkey_lines = PyUnicode_InternFromString("lines");
  dictkey_matrix = PyUnicode_InternFromString("transform");
  dictkey_modDate = PyUnicode_InternFromString("modDate");
  dictkey_name = PyUnicode_InternFromString("name");
  dictkey_number = PyUnicode_InternFromString("number");
  dictkey_origin = PyUnicode_InternFromString("origin");
  dictkey_rect = PyUnicode_InternFromString("rect");
  dictkey_size = PyUnicode_InternFromString("size");
  dictkey_smask = PyUnicode_InternFromString("smask");
  dictkey_spans = PyUnicode_InternFromString("spans");
  dictkey_stroke = PyUnicode_InternFromString("stroke");
  dictkey_style = PyUnicode_InternFromString("style");
  dictkey_subject = PyUnicode_InternFromString("subject");
  dictkey_text = PyUnicode_InternFromString("text");
  dictkey_title = PyUnicode_InternFromString("title");
  dictkey_type = PyUnicode_InternFromString("type");
  dictkey_ufilename = PyUnicode_InternFromString("ufilename");
  dictkey_width = PyUnicode_InternFromString("width");
  dictkey_wmode = PyUnicode_InternFromString("wmode");
  dictkey_xref = PyUnicode_InternFromString("xref");
  dictkey_xres = PyUnicode_InternFromString("xres");
  dictkey_yres = PyUnicode_InternFromString("yres");
  
  return 0;
}

