pgLatLon

changeset 3:bccc1e155ad8

Simplified approximated distance calculation on WGS-84 ellipsoid
author jbe
date Mon Aug 22 21:35:25 2016 +0200 (2016-08-22)
parents 4f07a22f4d45
children 8f79d4a1cdc1
files latlon-v0002.c
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/latlon-v0002.c	Mon Aug 22 21:35:25 2016 +0200
     1.3 @@ -0,0 +1,2701 @@
     1.4 +
     1.5 +/*-------------*
     1.6 + *  C prelude  *
     1.7 + *-------------*/
     1.8 +
     1.9 +#include "postgres.h"
    1.10 +#include "fmgr.h"
    1.11 +#include "libpq/pqformat.h"
    1.12 +#include "access/gist.h"
    1.13 +#include "access/stratnum.h"
    1.14 +#include "utils/array.h"
    1.15 +#include <math.h>
    1.16 +
    1.17 +#ifdef PG_MODULE_MAGIC
    1.18 +PG_MODULE_MAGIC;
    1.19 +#endif
    1.20 +
    1.21 +#if INT_MAX < 2147483647
    1.22 +#error Expected int type to be at least 32 bit wide
    1.23 +#endif
    1.24 +
    1.25 +
    1.26 +/*---------------------------------*
    1.27 + *  distance calculation on earth  *
    1.28 + *  (using WGS-84 spheroid)        *
    1.29 + *---------------------------------*/
    1.30 +
    1.31 +/*  WGS-84 spheroid with following parameters:
    1.32 +    semi-major axis  a = 6378137
    1.33 +    semi-minor axis  b = a * (1 - 1/298.257223563)
    1.34 +    estimated diameter = 2 * (2*a+b)/3
    1.35 +*/
    1.36 +#define PGL_SPHEROID_A 6378137.0            /* semi major axis */
    1.37 +#define PGL_SPHEROID_F (1.0/298.257223563)  /* flattening */
    1.38 +#define PGL_SPHEROID_B (PGL_SPHEROID_A * (1.0-PGL_SPHEROID_F))
    1.39 +#define PGL_EPS2       ( ( PGL_SPHEROID_A * PGL_SPHEROID_A - \
    1.40 +                           PGL_SPHEROID_B * PGL_SPHEROID_B ) / \
    1.41 +                         ( PGL_SPHEROID_A * PGL_SPHEROID_A ) )
    1.42 +#define PGL_SUBEPS2    (1.0-PGL_EPS2)
    1.43 +#define PGL_DIAMETER   ((4.0*PGL_SPHEROID_A + 2.0*PGL_SPHEROID_B) / 3.0)
    1.44 +#define PGL_SCALE      (PGL_SPHEROID_A / PGL_DIAMETER)  /* semi-major ref. */
    1.45 +#define PGL_FADELIMIT  (PGL_DIAMETER * M_PI / 6.0)      /* 1/6 circumference */
    1.46 +#define PGL_MAXDIST    (PGL_DIAMETER * M_PI / 2.0)      /* maximum distance */
    1.47 +
    1.48 +/* calculate distance between two points on earth (given in degrees) */
    1.49 +static inline double pgl_distance(
    1.50 +  double lat1, double lon1, double lat2, double lon2
    1.51 +) {
    1.52 +  float8 lat1cos, lat1sin, lat2cos, lat2sin, lon2cos, lon2sin;
    1.53 +  float8 nphi1, nphi2, x1, z1, x2, y2, z2, g, s, t;
    1.54 +  /* normalize delta longitude (lon2 > 0 && lon1 = 0) */
    1.55 +  /* lon1 = 0 (not used anymore) */
    1.56 +  lon2 = fabs(lon2-lon1);
    1.57 +  /* convert to radians (first divide, then multiply) */
    1.58 +  lat1 = (lat1 / 180.0) * M_PI;
    1.59 +  lat2 = (lat2 / 180.0) * M_PI;
    1.60 +  lon2 = (lon2 / 180.0) * M_PI;
    1.61 +  /* make lat2 >= lat1 to ensure reversal-symmetry despite floating point
    1.62 +     operations (lon2 >= lon1 is already ensured in a previous step) */
    1.63 +  if (lat2 < lat1) { float8 swap = lat1; lat1 = lat2; lat2 = swap; }
    1.64 +  /* calculate 3d coordinates on scaled ellipsoid which has an average diameter
    1.65 +     of 1.0 */
    1.66 +  lat1cos = cos(lat1); lat1sin = sin(lat1);
    1.67 +  lat2cos = cos(lat2); lat2sin = sin(lat2);
    1.68 +  lon2cos = cos(lon2); lon2sin = sin(lon2);
    1.69 +  nphi1 = PGL_SCALE / sqrt(1 - PGL_EPS2 * lat1sin * lat1sin);
    1.70 +  nphi2 = PGL_SCALE / sqrt(1 - PGL_EPS2 * lat2sin * lat2sin);
    1.71 +  x1 = nphi1 * lat1cos;
    1.72 +  z1 = nphi1 * PGL_SUBEPS2 * lat1sin;
    1.73 +  x2 = nphi2 * lat2cos * lon2cos;
    1.74 +  y2 = nphi2 * lat2cos * lon2sin;
    1.75 +  z2 = nphi2 * PGL_SUBEPS2 * lat2sin;
    1.76 +  /* calculate tunnel distance through scaled (diameter 1.0) ellipsoid */
    1.77 +  g = sqrt((x2-x1)*(x2-x1) + y2*y2 + (z2-z1)*(z2-z1));
    1.78 +  /* convert tunnel distance through scaled ellipsoid to approximated surface
    1.79 +     distance on original ellipsoid */
    1.80 +  if (g > 1.0) g = 1.0;
    1.81 +  s = PGL_DIAMETER * asin(g);
    1.82 +  /* return result only if small enough to be precise (less than 1/3 of
    1.83 +     maximum possible distance) */
    1.84 +  if (s <= PGL_FADELIMIT) return s;
    1.85 +  /* calculate tunnel distance to antipodal point through scaled ellipsoid */
    1.86 +  g = sqrt((x2+x1)*(x2+x1) + y2*y2 + (z2+z1)*(z2+z1));
    1.87 +  /* convert tunnel distance to antipodal point through scaled ellipsoid to
    1.88 +     approximated surface distance to antipodal point on original ellipsoid */
    1.89 +  if (g > 1.0) g = 1.0;
    1.90 +  t = PGL_DIAMETER * asin(g);
    1.91 +  /* surface distance between original points can now be approximated by
    1.92 +     substracting antipodal distance from maximum possible distance;
    1.93 +     return result only if small enough (less than 1/3 of maximum possible
    1.94 +     distance) */
    1.95 +  if (t <= PGL_FADELIMIT) return PGL_MAXDIST-t;
    1.96 +  /* otherwise crossfade direct and antipodal result to ensure monotonicity */
    1.97 +  return (
    1.98 +    (s * (t-PGL_FADELIMIT) + (PGL_MAXDIST-t) * (s-PGL_FADELIMIT)) /
    1.99 +    (s + t - 2*PGL_FADELIMIT)
   1.100 +  );
   1.101 +}
   1.102 +
   1.103 +/* finite distance that can not be reached on earth */
   1.104 +#define PGL_ULTRA_DISTANCE (3 * PGL_MAXDIST)
   1.105 +
   1.106 +
   1.107 +/*--------------------------------*
   1.108 + *  simple geographic data types  *
   1.109 + *--------------------------------*/
   1.110 +
   1.111 +/* point on earth given by latitude and longitude in degrees */
   1.112 +/* (type "epoint" in SQL) */
   1.113 +typedef struct {
   1.114 +  double lat;  /* between  -90 and  90 (both inclusive) */
   1.115 +  double lon;  /* between -180 and 180 (both inclusive) */
   1.116 +} pgl_point;
   1.117 +
   1.118 +/* box delimited by two parallels and two meridians (all in degrees) */
   1.119 +/* (type "ebox" in SQL) */
   1.120 +typedef struct {
   1.121 +  double lat_min;  /* between  -90 and  90 (both inclusive) */
   1.122 +  double lat_max;  /* between  -90 and  90 (both inclusive) */
   1.123 +  double lon_min;  /* between -180 and 180 (both inclusive) */
   1.124 +  double lon_max;  /* between -180 and 180 (both inclusive) */
   1.125 +  /* if lat_min > lat_max, then box is empty */
   1.126 +  /* if lon_min > lon_max, then 180th meridian is crossed */
   1.127 +} pgl_box;
   1.128 +
   1.129 +/* circle on earth surface (for radial searches with fixed radius) */
   1.130 +/* (type "ecircle" in SQL) */
   1.131 +typedef struct {
   1.132 +  pgl_point center;
   1.133 +  double radius; /* positive (including +0 but excluding -0), or -INFINITY */
   1.134 +  /* A negative radius (i.e. -INFINITY) denotes nothing (i.e. no point),
   1.135 +     zero radius (0) denotes a single point,
   1.136 +     a finite radius (0 < radius < INFINITY) denotes a filled circle, and
   1.137 +     a radius of INFINITY is valid and means complete coverage of earth. */
   1.138 +} pgl_circle;
   1.139 +
   1.140 +
   1.141 +/*----------------------------------*
   1.142 + *  geographic "cluster" data type  *
   1.143 + *----------------------------------*/
   1.144 +
   1.145 +/* A cluster is a collection of points, paths, outlines, and polygons. If two
   1.146 +   polygons in a cluster overlap, the area covered by both polygons does not
   1.147 +   belong to the cluster. This way, a cluster can be used to describe complex
   1.148 +   shapes like polygons with holes. Outlines are non-filled polygons. Paths are
   1.149 +   open by default (i.e. the last point in the list is not connected with the
   1.150 +   first point in the list). Note that each outline or polygon in a cluster
   1.151 +   must cover a longitude range of less than 180 degrees to avoid ambiguities.
   1.152 +   Areas which are larger may be split into multiple polygons. */
   1.153 +
   1.154 +/* maximum number of points in a cluster */
   1.155 +/* (limited to avoid integer overflows, e.g. when allocating memory) */
   1.156 +#define PGL_CLUSTER_MAXPOINTS 16777216
   1.157 +
   1.158 +/* types of cluster entries */
   1.159 +#define PGL_ENTRY_POINT   1  /* a point */
   1.160 +#define PGL_ENTRY_PATH    2  /* a path from first point to last point */
   1.161 +#define PGL_ENTRY_OUTLINE 3  /* a non-filled polygon with given vertices */
   1.162 +#define PGL_ENTRY_POLYGON 4  /* a filled polygon with given vertices */
   1.163 +
   1.164 +/* Entries of a cluster are described by two different structs: pgl_newentry
   1.165 +   and pgl_entry. The first is used only during construction of a cluster, the
   1.166 +   second is used in all other cases (e.g. when reading clusters from the
   1.167 +   database, performing operations, etc). */
   1.168 +
   1.169 +/* entry for new geographic cluster during construction of that cluster */
   1.170 +typedef struct {
   1.171 +  int32_t entrytype;
   1.172 +  int32_t npoints;
   1.173 +  pgl_point *points;  /* pointer to an array of points (pgl_point) */
   1.174 +} pgl_newentry;
   1.175 +
   1.176 +/* entry of geographic cluster */
   1.177 +typedef struct {
   1.178 +  int32_t entrytype;  /* type of entry: point, path, outline, polygon */
   1.179 +  int32_t npoints;    /* number of stored points (set to 1 for point entry) */
   1.180 +  int32_t offset;     /* offset of pgl_point array from cluster base address */
   1.181 +  /* use macro PGL_ENTRY_POINTS to obtain a pointer to the array of points */
   1.182 +} pgl_entry;
   1.183 +
   1.184 +/* geographic cluster which is a collection of points, (open) paths, polygons,
   1.185 +   and outlines (non-filled polygons) */
   1.186 +typedef struct {
   1.187 +  char header[VARHDRSZ];  /* PostgreSQL header for variable size data types */
   1.188 +  int32_t nentries;       /* number of stored points */
   1.189 +  pgl_circle bounding;    /* bounding circle */
   1.190 +  /* Note: bounding circle ensures alignment of pgl_cluster for points */
   1.191 +  pgl_entry entries[FLEXIBLE_ARRAY_MEMBER];  /* var-length data */
   1.192 +} pgl_cluster;
   1.193 +
   1.194 +/* macro to determine memory alignment of points */
   1.195 +/* (needed to store pgl_point array after entries in pgl_cluster) */
   1.196 +typedef struct { char dummy; pgl_point aligned; } pgl_point_alignment;
   1.197 +#define PGL_POINT_ALIGNMENT offsetof(pgl_point_alignment, aligned)
   1.198 +
   1.199 +/* macro to extract a pointer to the array of points of a cluster entry */
   1.200 +#define PGL_ENTRY_POINTS(cluster, idx) \
   1.201 +  ((pgl_point *)(((intptr_t)cluster)+(cluster)->entries[idx].offset))
   1.202 +
   1.203 +/* convert pgl_newentry array to pgl_cluster */
   1.204 +static pgl_cluster *pgl_new_cluster(int nentries, pgl_newentry *entries) {
   1.205 +  int i;              /* index of current entry */
   1.206 +  int npoints = 0;    /* number of points in whole cluster */
   1.207 +  int entry_npoints;  /* number of points in current entry */
   1.208 +  int points_offset = PGL_POINT_ALIGNMENT * (
   1.209 +    ( offsetof(pgl_cluster, entries) +
   1.210 +      nentries * sizeof(pgl_entry) +
   1.211 +      PGL_POINT_ALIGNMENT - 1
   1.212 +    ) / PGL_POINT_ALIGNMENT
   1.213 +  );  /* offset of pgl_point array from base address (considering alignment) */
   1.214 +  pgl_cluster *cluster;  /* new cluster to be returned */
   1.215 +  /* determine total number of points */
   1.216 +  for (i=0; i<nentries; i++) npoints += entries[i].npoints;
   1.217 +  /* allocate memory for cluster (including entries and points) */
   1.218 +  cluster = palloc(points_offset + npoints * sizeof(pgl_point));
   1.219 +  /* re-count total number of points to determine offset for each entry */
   1.220 +  npoints = 0;
   1.221 +  /* copy entries and points */
   1.222 +  for (i=0; i<nentries; i++) {
   1.223 +    /* determine number of points in entry */
   1.224 +    entry_npoints = entries[i].npoints;
   1.225 +    /* copy entry */
   1.226 +    cluster->entries[i].entrytype = entries[i].entrytype;
   1.227 +    cluster->entries[i].npoints = entry_npoints;
   1.228 +    /* calculate offset (in bytes) of pgl_point array */
   1.229 +    cluster->entries[i].offset = points_offset + npoints * sizeof(pgl_point);
   1.230 +    /* copy points */
   1.231 +    memcpy(
   1.232 +      PGL_ENTRY_POINTS(cluster, i),
   1.233 +      entries[i].points,
   1.234 +      entry_npoints * sizeof(pgl_point)
   1.235 +    );
   1.236 +    /* update total number of points processed */
   1.237 +    npoints += entry_npoints;
   1.238 +  }
   1.239 +  /* set number of entries in cluster */
   1.240 +  cluster->nentries = nentries;
   1.241 +  /* set PostgreSQL header for variable sized data */
   1.242 +  SET_VARSIZE(cluster, points_offset + npoints * sizeof(pgl_point));
   1.243 +  /* return newly created cluster */
   1.244 +  return cluster;
   1.245 +}
   1.246 +
   1.247 +
   1.248 +/*----------------------------------------*
   1.249 + *  C functions on geographic data types  *
   1.250 + *----------------------------------------*/
   1.251 +
   1.252 +/* round latitude or longitude to 12 digits after decimal point */
   1.253 +static inline double pgl_round(double val) {
   1.254 +  return round(val * 1e12) / 1e12;
   1.255 +}
   1.256 +
   1.257 +/* compare two points */
   1.258 +/* (equality when same point on earth is described, otherwise an arbitrary
   1.259 +   linear order) */
   1.260 +static int pgl_point_cmp(pgl_point *point1, pgl_point *point2) {
   1.261 +  double lon1, lon2;  /* modified longitudes for special cases */
   1.262 +  /* use latitude as first ordering criterion */
   1.263 +  if (point1->lat < point2->lat) return -1;
   1.264 +  if (point1->lat > point2->lat) return 1;
   1.265 +  /* determine modified longitudes (considering special case of poles and
   1.266 +     180th meridian which can be described as W180 or E180) */
   1.267 +  if (point1->lat == -90 || point1->lat == 90) lon1 = 0;
   1.268 +  else if (point1->lon == 180) lon1 = -180;
   1.269 +  else lon1 = point1->lon;
   1.270 +  if (point2->lat == -90 || point2->lat == 90) lon2 = 0;
   1.271 +  else if (point2->lon == 180) lon2 = -180;
   1.272 +  else lon2 = point2->lon;
   1.273 +  /* use (modified) longitude as secondary ordering criterion */
   1.274 +  if (lon1 < lon2) return -1;
   1.275 +  if (lon1 > lon2) return 1;
   1.276 +  /* no difference found, points are equal */
   1.277 +  return 0;
   1.278 +}
   1.279 +
   1.280 +/* compare two boxes */
   1.281 +/* (equality when same box on earth is described, otherwise an arbitrary linear
   1.282 +   order) */
   1.283 +static int pgl_box_cmp(pgl_box *box1, pgl_box *box2) {
   1.284 +  /* two empty boxes are equal, and an empty box is always considered "less
   1.285 +     than" a non-empty box */
   1.286 +  if (box1->lat_min> box1->lat_max && box2->lat_min<=box2->lat_max) return -1;
   1.287 +  if (box1->lat_min> box1->lat_max && box2->lat_min> box2->lat_max) return 0;
   1.288 +  if (box1->lat_min<=box1->lat_max && box2->lat_min> box2->lat_max) return 1;
   1.289 +  /* use southern border as first ordering criterion */
   1.290 +  if (box1->lat_min < box2->lat_min) return -1;
   1.291 +  if (box1->lat_min > box2->lat_min) return 1;
   1.292 +  /* use northern border as second ordering criterion */
   1.293 +  if (box1->lat_max < box2->lat_max) return -1;
   1.294 +  if (box1->lat_max > box2->lat_max) return 1;
   1.295 +  /* use western border as third ordering criterion */
   1.296 +  if (box1->lon_min < box2->lon_min) return -1;
   1.297 +  if (box1->lon_min > box2->lon_min) return 1;
   1.298 +  /* use eastern border as fourth ordering criterion */
   1.299 +  if (box1->lon_max < box2->lon_max) return -1;
   1.300 +  if (box1->lon_max > box2->lon_max) return 1;
   1.301 +  /* no difference found, boxes are equal */
   1.302 +  return 0;
   1.303 +}
   1.304 +
   1.305 +/* compare two circles */
   1.306 +/* (equality when same circle on earth is described, otherwise an arbitrary
   1.307 +   linear order) */
   1.308 +static int pgl_circle_cmp(pgl_circle *circle1, pgl_circle *circle2) {
   1.309 +  /* two circles with same infinite radius (positive or negative infinity) are
   1.310 +     considered equal independently of center point */
   1.311 +  if (
   1.312 +    !isfinite(circle1->radius) && !isfinite(circle2->radius) &&
   1.313 +    circle1->radius == circle2->radius
   1.314 +  ) return 0;
   1.315 +  /* use radius as first ordering criterion */
   1.316 +  if (circle1->radius < circle2->radius) return -1;
   1.317 +  if (circle1->radius > circle2->radius) return 1;
   1.318 +  /* use center point as secondary ordering criterion */
   1.319 +  return pgl_point_cmp(&(circle1->center), &(circle2->center));
   1.320 +}
   1.321 +
   1.322 +/* set box to empty box*/
   1.323 +static void pgl_box_set_empty(pgl_box *box) {
   1.324 +  box->lat_min = INFINITY;
   1.325 +  box->lat_max = -INFINITY;
   1.326 +  box->lon_min = 0;
   1.327 +  box->lon_max = 0;
   1.328 +}
   1.329 +
   1.330 +/* check if point is inside a box */
   1.331 +static bool pgl_point_in_box(pgl_point *point, pgl_box *box) {
   1.332 +  return (
   1.333 +    point->lat >= box->lat_min && point->lat <= box->lat_max && (
   1.334 +      (box->lon_min > box->lon_max) ? (
   1.335 +        /* box crosses 180th meridian */
   1.336 +        point->lon >= box->lon_min || point->lon <= box->lon_max
   1.337 +      ) : (
   1.338 +        /* box does not cross the 180th meridian */
   1.339 +        point->lon >= box->lon_min && point->lon <= box->lon_max
   1.340 +      )
   1.341 +    )
   1.342 +  );
   1.343 +}
   1.344 +
   1.345 +/* check if two boxes overlap */
   1.346 +static bool pgl_boxes_overlap(pgl_box *box1, pgl_box *box2) {
   1.347 +  return (
   1.348 +    box2->lat_max >= box2->lat_min &&  /* ensure box2 is not empty */
   1.349 +    ( box2->lat_min >= box1->lat_min || box2->lat_max >= box1->lat_min ) &&
   1.350 +    ( box2->lat_min <= box1->lat_max || box2->lat_max <= box1->lat_max ) && (
   1.351 +      (
   1.352 +        /* check if one and only one box crosses the 180th meridian */
   1.353 +        ((box1->lon_min > box1->lon_max) ? 1 : 0) ^
   1.354 +        ((box2->lon_min > box2->lon_max) ? 1 : 0)
   1.355 +      ) ? (
   1.356 +        /* exactly one box crosses the 180th meridian */
   1.357 +        box2->lon_min >= box1->lon_min || box2->lon_max >= box1->lon_min ||
   1.358 +        box2->lon_min <= box1->lon_max || box2->lon_max <= box1->lon_max
   1.359 +      ) : (
   1.360 +        /* no box or both boxes cross the 180th meridian */
   1.361 +        (
   1.362 +          (box2->lon_min >= box1->lon_min || box2->lon_max >= box1->lon_min) &&
   1.363 +          (box2->lon_min <= box1->lon_max || box2->lon_max <= box1->lon_max)
   1.364 +        ) ||
   1.365 +        /* handle W180 == E180 */
   1.366 +        ( box1->lon_min == -180 && box2->lon_max == 180 ) ||
   1.367 +        ( box2->lon_min == -180 && box1->lon_max == 180 )
   1.368 +      )
   1.369 +    )
   1.370 +  );
   1.371 +}
   1.372 +
   1.373 +/* check unambiguousness of east/west orientation of cluster entries and set
   1.374 +   bounding circle of cluster */
   1.375 +static bool pgl_finalize_cluster(pgl_cluster *cluster) {
   1.376 +  int i, j;                 /* i: index of entry, j: index of point in entry */
   1.377 +  int npoints;              /* number of points in entry */
   1.378 +  int total_npoints = 0;    /* total number of points in cluster */
   1.379 +  pgl_point *points;        /* points in entry */
   1.380 +  int lon_dir;              /* first point of entry west (-1) or east (+1) */
   1.381 +  double lon_break = 0;     /* antipodal longitude of first point in entry */
   1.382 +  double lon_min, lon_max;  /* covered longitude range of entry */
   1.383 +  double value;             /* temporary variable */
   1.384 +  /* reset bounding circle center to empty circle at 0/0 coordinates */
   1.385 +  cluster->bounding.center.lat = 0;
   1.386 +  cluster->bounding.center.lon = 0;
   1.387 +  cluster->bounding.radius = -INFINITY;
   1.388 +  /* if cluster is not empty */
   1.389 +  if (cluster->nentries != 0) {
   1.390 +    /* iterate over all cluster entries and ensure they each cover a longitude
   1.391 +       range less than 180 degrees */
   1.392 +    for (i=0; i<cluster->nentries; i++) {
   1.393 +      /* get properties of entry */
   1.394 +      npoints = cluster->entries[i].npoints;
   1.395 +      points = PGL_ENTRY_POINTS(cluster, i);
   1.396 +      /* get longitude of first point of entry */
   1.397 +      value = points[0].lon;
   1.398 +      /* initialize lon_min and lon_max with longitude of first point */
   1.399 +      lon_min = value;
   1.400 +      lon_max = value;
   1.401 +      /* determine east/west orientation of first point and calculate antipodal
   1.402 +         longitude (Note: rounding required here) */
   1.403 +      if      (value < 0) { lon_dir = -1; lon_break = pgl_round(value + 180); }
   1.404 +      else if (value > 0) { lon_dir =  1; lon_break = pgl_round(value - 180); }
   1.405 +      else lon_dir = 0;
   1.406 +      /* iterate over all other points in entry */
   1.407 +      for (j=1; j<npoints; j++) {
   1.408 +        /* consider longitude wrap-around */
   1.409 +        value = points[j].lon;
   1.410 +        if      (lon_dir<0 && value>lon_break) value = pgl_round(value - 360);
   1.411 +        else if (lon_dir>0 && value<lon_break) value = pgl_round(value + 360);
   1.412 +        /* update lon_min and lon_max */
   1.413 +        if      (value < lon_min) lon_min = value;
   1.414 +        else if (value > lon_max) lon_max = value;
   1.415 +        /* return false if 180 degrees or more are covered */
   1.416 +        if (lon_max - lon_min >= 180) return false;
   1.417 +      }
   1.418 +    }
   1.419 +    /* iterate over all points of all entries and calculate arbitrary center
   1.420 +       point for bounding circle (best if center point minimizes the radius,
   1.421 +       but some error is allowed here) */
   1.422 +    for (i=0; i<cluster->nentries; i++) {
   1.423 +      /* get properties of entry */
   1.424 +      npoints = cluster->entries[i].npoints;
   1.425 +      points = PGL_ENTRY_POINTS(cluster, i);
   1.426 +      /* check if first entry */
   1.427 +      if (i==0) {
   1.428 +        /* get longitude of first point of first entry in whole cluster */
   1.429 +        value = points[0].lon;
   1.430 +        /* initialize lon_min and lon_max with longitude of first point of
   1.431 +           first entry in whole cluster (used to determine if whole cluster
   1.432 +           covers a longitude range of 180 degrees or more) */
   1.433 +        lon_min = value;
   1.434 +        lon_max = value;
   1.435 +        /* determine east/west orientation of first point and calculate
   1.436 +           antipodal longitude (Note: rounding not necessary here) */
   1.437 +        if      (value < 0) { lon_dir = -1; lon_break = value + 180; }
   1.438 +        else if (value > 0) { lon_dir =  1; lon_break = value - 180; }
   1.439 +        else lon_dir = 0;
   1.440 +      }
   1.441 +      /* iterate over all points in entry */
   1.442 +      for (j=0; j<npoints; j++) {
   1.443 +        /* longitude wrap-around (Note: rounding not necessary here) */
   1.444 +        value = points[j].lon;
   1.445 +        if      (lon_dir < 0 && value > lon_break) value -= 360;
   1.446 +        else if (lon_dir > 0 && value < lon_break) value += 360;
   1.447 +        if      (value < lon_min) lon_min = value;
   1.448 +        else if (value > lon_max) lon_max = value;
   1.449 +        /* set bounding circle to cover whole earth if more than 180 degrees
   1.450 +           are covered */
   1.451 +        if (lon_max - lon_min >= 180) {
   1.452 +          cluster->bounding.center.lat = 0;
   1.453 +          cluster->bounding.center.lon = 0;
   1.454 +          cluster->bounding.radius = INFINITY;
   1.455 +          return true;
   1.456 +        }
   1.457 +        /* add point to bounding circle center (for average calculation) */
   1.458 +        cluster->bounding.center.lat += points[j].lat;
   1.459 +        cluster->bounding.center.lon += value;
   1.460 +      }
   1.461 +      /* count total number of points */
   1.462 +      total_npoints += npoints;
   1.463 +    }
   1.464 +    /* determine average latitude and longitude of cluster */
   1.465 +    cluster->bounding.center.lat /= total_npoints;
   1.466 +    cluster->bounding.center.lon /= total_npoints;
   1.467 +    /* normalize longitude of center of cluster bounding circle */
   1.468 +    if (cluster->bounding.center.lon < -180) {
   1.469 +      cluster->bounding.center.lon += 360;
   1.470 +    }
   1.471 +    else if (cluster->bounding.center.lon > 180) {
   1.472 +      cluster->bounding.center.lon -= 360;
   1.473 +    }
   1.474 +    /* round bounding circle center (useful if it is used by other functions) */
   1.475 +    cluster->bounding.center.lat = pgl_round(cluster->bounding.center.lat);
   1.476 +    cluster->bounding.center.lon = pgl_round(cluster->bounding.center.lon);
   1.477 +    /* calculate radius of bounding circle */
   1.478 +    for (i=0; i<cluster->nentries; i++) {
   1.479 +      npoints = cluster->entries[i].npoints;
   1.480 +      points = PGL_ENTRY_POINTS(cluster, i);
   1.481 +      for (j=0; j<npoints; j++) {
   1.482 +        value = pgl_distance(
   1.483 +          cluster->bounding.center.lat, cluster->bounding.center.lon,
   1.484 +          points[j].lat, points[j].lon
   1.485 +        );
   1.486 +        if (value > cluster->bounding.radius) cluster->bounding.radius = value;
   1.487 +      }
   1.488 +    }
   1.489 +  }
   1.490 +  /* return true (east/west orientation is unambiguous) */
   1.491 +  return true;
   1.492 +}
   1.493 +
   1.494 +/* check if point is inside cluster */
   1.495 +static bool pgl_point_in_cluster(pgl_point *point, pgl_cluster *cluster) {
   1.496 +  int i, j, k;  /* i: entry, j: point in entry, k: next point in entry */
   1.497 +  int entrytype;         /* type of entry */
   1.498 +  int npoints;           /* number of points in entry */
   1.499 +  pgl_point *points;     /* array of points in entry */
   1.500 +  int lon_dir = 0;       /* first vertex west (-1) or east (+1) */
   1.501 +  double lon_break = 0;  /* antipodal longitude of first vertex */
   1.502 +  double lat0 = point->lat;  /* latitude of point */
   1.503 +  double lon0;           /* (adjusted) longitude of point */
   1.504 +  double lat1, lon1;     /* latitude and (adjusted) longitude of vertex */
   1.505 +  double lat2, lon2;     /* latitude and (adjusted) longitude of next vertex */
   1.506 +  double lon;            /* longitude of intersection */
   1.507 +  int counter = 0;       /* counter for intersections east of point */
   1.508 +  /* points outside bounding circle are always assumed to be non-overlapping */
   1.509 +  /* (necessary for consistent table and index scans) */
   1.510 +  if (
   1.511 +    pgl_distance(
   1.512 +      point->lat, point->lon,
   1.513 +      cluster->bounding.center.lat, cluster->bounding.center.lon
   1.514 +    ) > cluster->bounding.radius
   1.515 +  ) return false;
   1.516 +  /* iterate over all entries */
   1.517 +  for (i=0; i<cluster->nentries; i++) {
   1.518 +    /* get properties of entry */
   1.519 +    entrytype = cluster->entries[i].entrytype;
   1.520 +    npoints = cluster->entries[i].npoints;
   1.521 +    points = PGL_ENTRY_POINTS(cluster, i);
   1.522 +    /* determine east/west orientation of first point of entry and calculate
   1.523 +       antipodal longitude */
   1.524 +    lon_break = points[0].lon;
   1.525 +    if      (lon_break < 0) { lon_dir = -1; lon_break += 180; }
   1.526 +    else if (lon_break > 0) { lon_dir =  1; lon_break -= 180; }
   1.527 +    else lon_dir = 0;
   1.528 +    /* get longitude of point */
   1.529 +    lon0 = point->lon;
   1.530 +    /* consider longitude wrap-around for point */
   1.531 +    if      (lon_dir < 0 && lon0 > lon_break) lon0 = pgl_round(lon0 - 360);
   1.532 +    else if (lon_dir > 0 && lon0 < lon_break) lon0 = pgl_round(lon0 + 360);
   1.533 +    /* iterate over all edges and vertices */
   1.534 +    for (j=0; j<npoints; j++) {
   1.535 +      /* return true if point is on vertex of polygon */
   1.536 +      if (pgl_point_cmp(point, &(points[j])) == 0) return true;
   1.537 +      /* calculate index of next vertex */
   1.538 +      k = (j+1) % npoints;
   1.539 +      /* skip last edge unless entry is (closed) outline or polygon */
   1.540 +      if (
   1.541 +        k == 0 &&
   1.542 +        entrytype != PGL_ENTRY_OUTLINE &&
   1.543 +        entrytype != PGL_ENTRY_POLYGON
   1.544 +      ) continue;
   1.545 +      /* get latitude and longitude values of edge */
   1.546 +      lat1 = points[j].lat;
   1.547 +      lat2 = points[k].lat;
   1.548 +      lon1 = points[j].lon;
   1.549 +      lon2 = points[k].lon;
   1.550 +      /* consider longitude wrap-around for edge */
   1.551 +      if      (lon_dir < 0 && lon1 > lon_break) lon1 = pgl_round(lon1 - 360);
   1.552 +      else if (lon_dir > 0 && lon1 < lon_break) lon1 = pgl_round(lon1 + 360);
   1.553 +      if      (lon_dir < 0 && lon2 > lon_break) lon2 = pgl_round(lon2 - 360);
   1.554 +      else if (lon_dir > 0 && lon2 < lon_break) lon2 = pgl_round(lon2 + 360);
   1.555 +      /* return true if point is on horizontal (west to east) edge of polygon */
   1.556 +      if (
   1.557 +        lat0 == lat1 && lat0 == lat2 &&
   1.558 +        ( (lon0 >= lon1 && lon0 <= lon2) || (lon0 >= lon2 && lon0 <= lon1) )
   1.559 +      ) return true;
   1.560 +      /* check if edge crosses east/west line of point */
   1.561 +      if ((lat1 < lat0 && lat2 >= lat0) || (lat2 < lat0 && lat1 >= lat0)) {
   1.562 +        /* calculate longitude of intersection */
   1.563 +        lon = (lon1 * (lat2-lat0) + lon2 * (lat0-lat1)) / (lat2-lat1);
   1.564 +        /* return true if intersection goes (approximately) through point */
   1.565 +        if (pgl_round(lon) == lon0) return true;
   1.566 +        /* count intersection if east of point and entry is polygon*/
   1.567 +        if (entrytype == PGL_ENTRY_POLYGON && lon > lon0) counter++;
   1.568 +      }
   1.569 +    }
   1.570 +  }
   1.571 +  /* return true if number of intersections is odd */
   1.572 +  return counter & 1;
   1.573 +}
   1.574 +
   1.575 +/* calculate (approximate) distance between point and cluster */
   1.576 +static double pgl_point_cluster_distance(pgl_point *point, pgl_cluster *cluster) {
   1.577 +  int i, j, k;  /* i: entry, j: point in entry, k: next point in entry */
   1.578 +  int entrytype;         /* type of entry */
   1.579 +  int npoints;           /* number of points in entry */
   1.580 +  pgl_point *points;     /* array of points in entry */
   1.581 +  int lon_dir = 0;       /* first vertex west (-1) or east (+1) */
   1.582 +  double lon_break = 0;  /* antipodal longitude of first vertex */
   1.583 +  double lon_min = 0;    /* minimum (adjusted) longitude of entry vertices */
   1.584 +  double lon_max = 0;    /* maximum (adjusted) longitude of entry vertices */
   1.585 +  double lat0 = point->lat;  /* latitude of point */
   1.586 +  double lon0;           /* (adjusted) longitude of point */
   1.587 +  double lat1, lon1;     /* latitude and (adjusted) longitude of vertex */
   1.588 +  double lat2, lon2;     /* latitude and (adjusted) longitude of next vertex */
   1.589 +  double s;              /* scalar for vector calculations */
   1.590 +  double dist;           /* distance calculated in one step */
   1.591 +  double min_dist = INFINITY;   /* minimum distance */
   1.592 +  /* distance is zero if point is contained in cluster */
   1.593 +  if (pgl_point_in_cluster(point, cluster)) return 0;
   1.594 +  /* iterate over all entries */
   1.595 +  for (i=0; i<cluster->nentries; i++) {
   1.596 +    /* get properties of entry */
   1.597 +    entrytype = cluster->entries[i].entrytype;
   1.598 +    npoints = cluster->entries[i].npoints;
   1.599 +    points = PGL_ENTRY_POINTS(cluster, i);
   1.600 +    /* determine east/west orientation of first point of entry and calculate
   1.601 +       antipodal longitude */
   1.602 +    lon_break = points[0].lon;
   1.603 +    if      (lon_break < 0) { lon_dir = -1; lon_break += 180; }
   1.604 +    else if (lon_break > 0) { lon_dir =  1; lon_break -= 180; }
   1.605 +    else lon_dir = 0;
   1.606 +    /* determine covered longitude range */
   1.607 +    for (j=0; j<npoints; j++) {
   1.608 +      /* get longitude of vertex */
   1.609 +      lon1 = points[j].lon;
   1.610 +      /* adjust longitude to fix potential wrap-around */
   1.611 +      if      (lon_dir < 0 && lon1 > lon_break) lon1 -= 360;
   1.612 +      else if (lon_dir > 0 && lon1 < lon_break) lon1 += 360;
   1.613 +      /* update minimum and maximum longitude of polygon */
   1.614 +      if (j == 0 || lon1 < lon_min) lon_min = lon1;
   1.615 +      if (j == 0 || lon1 > lon_max) lon_max = lon1;
   1.616 +    }
   1.617 +    /* adjust longitude wrap-around according to full longitude range */
   1.618 +    lon_break = (lon_max + lon_min) / 2;
   1.619 +    if      (lon_break < 0) { lon_dir = -1; lon_break += 180; }
   1.620 +    else if (lon_break > 0) { lon_dir =  1; lon_break -= 180; }
   1.621 +    /* get longitude of point */
   1.622 +    lon0 = point->lon;
   1.623 +    /* consider longitude wrap-around for point */
   1.624 +    if      (lon_dir < 0 && lon0 > lon_break) lon0 -= 360;
   1.625 +    else if (lon_dir > 0 && lon0 < lon_break) lon0 += 360;
   1.626 +    /* iterate over all edges and vertices */
   1.627 +    for (j=0; j<npoints; j++) {
   1.628 +      /* get latitude and longitude values of current point */
   1.629 +      lat1 = points[j].lat;
   1.630 +      lon1 = points[j].lon;
   1.631 +      /* consider longitude wrap-around for current point */
   1.632 +      if      (lon_dir < 0 && lon1 > lon_break) lon1 -= 360;
   1.633 +      else if (lon_dir > 0 && lon1 < lon_break) lon1 += 360;
   1.634 +      /* calculate distance to vertex */
   1.635 +      dist = pgl_distance(lat0, lon0, lat1, lon1);
   1.636 +      /* store calculated distance if smallest */
   1.637 +      if (dist < min_dist) min_dist = dist;
   1.638 +      /* calculate index of next vertex */
   1.639 +      k = (j+1) % npoints;
   1.640 +      /* skip last edge unless entry is (closed) outline or polygon */
   1.641 +      if (
   1.642 +        k == 0 &&
   1.643 +        entrytype != PGL_ENTRY_OUTLINE &&
   1.644 +        entrytype != PGL_ENTRY_POLYGON
   1.645 +      ) continue;
   1.646 +      /* get latitude and longitude values of next point */
   1.647 +      lat2 = points[k].lat;
   1.648 +      lon2 = points[k].lon;
   1.649 +      /* consider longitude wrap-around for next point */
   1.650 +      if      (lon_dir < 0 && lon2 > lon_break) lon2 -= 360;
   1.651 +      else if (lon_dir > 0 && lon2 < lon_break) lon2 += 360;
   1.652 +      /* go to next vertex and edge if edge is degenerated */
   1.653 +      if (lat1 == lat2 && lon1 == lon2) continue;
   1.654 +      /* otherwise test if point can be projected onto edge of polygon */
   1.655 +      s = (
   1.656 +        ((lat0-lat1) * (lat2-lat1) + (lon0-lon1) * (lon2-lon1)) /
   1.657 +        ((lat2-lat1) * (lat2-lat1) + (lon2-lon1) * (lon2-lon1))
   1.658 +      );
   1.659 +      /* go to next vertex and edge if point cannot be projected */
   1.660 +      if (!(s > 0 && s < 1)) continue;
   1.661 +      /* calculate distance from original point to projected point */
   1.662 +      dist = pgl_distance(
   1.663 +        lat0, lon0,
   1.664 +        lat1 + s * (lat2-lat1),
   1.665 +        lon1 + s * (lon2-lon1)
   1.666 +      );
   1.667 +      /* store calculated distance if smallest */
   1.668 +      if (dist < min_dist) min_dist = dist;
   1.669 +    }
   1.670 +  }
   1.671 +  /* return minimum distance */
   1.672 +  return min_dist;
   1.673 +}
   1.674 +
   1.675 +/* estimator function for distance between box and point */
   1.676 +/* allowed to return smaller values than actually correct */
   1.677 +static double pgl_estimate_point_box_distance(pgl_point *point, pgl_box *box) {
   1.678 +  double dlon;  /* longitude range of box (delta longitude) */
   1.679 +  double h;     /* half of distance along meridian */
   1.680 +  double d;     /* distance between both southern or both northern points */
   1.681 +  double cur_dist;  /* calculated distance */
   1.682 +  double min_dist;  /* minimum distance calculated */
   1.683 +  /* return infinity if bounding box is empty */
   1.684 +  if (box->lat_min > box->lat_max) return INFINITY;
   1.685 +  /* return zero if point is inside bounding box */
   1.686 +  if (pgl_point_in_box(point, box)) return 0;
   1.687 +  /* calculate delta longitude */
   1.688 +  dlon = box->lon_max - box->lon_min;
   1.689 +  if (dlon < 0) dlon += 360;  /* 180th meridian crossed */
   1.690 +  /* if delta longitude is greater than 180 degrees, perform safe fall-back */
   1.691 +  if (dlon > 180) return 0;
   1.692 +  /* calculate half of distance along meridian */
   1.693 +  h = pgl_distance(box->lat_min, 0, box->lat_max, 0) / 2;
   1.694 +  /* calculate full distance between southern points */
   1.695 +  d = pgl_distance(box->lat_min, 0, box->lat_min, dlon);
   1.696 +  /* calculate maximum of full distance and half distance */
   1.697 +  if (h > d) d = h;
   1.698 +  /* calculate distance from point to first southern vertex and substract
   1.699 +     maximum error */
   1.700 +  min_dist = pgl_distance(
   1.701 +    point->lat, point->lon, box->lat_min, box->lon_min
   1.702 +  ) - d;
   1.703 +  /* return zero if estimated distance is smaller than zero */
   1.704 +  if (min_dist <= 0) return 0;
   1.705 +  /* repeat procedure with second southern vertex */
   1.706 +  cur_dist = pgl_distance(
   1.707 +    point->lat, point->lon, box->lat_min, box->lon_max
   1.708 +  ) - d;
   1.709 +  if (cur_dist <= 0) return 0;
   1.710 +  if (cur_dist < min_dist) min_dist = cur_dist;
   1.711 +  /* calculate full distance between northern points */
   1.712 +  d = pgl_distance(box->lat_max, 0, box->lat_max, dlon);
   1.713 +  /* calculate maximum of full distance and half distance */
   1.714 +  if (h > d) d = h;
   1.715 +  /* repeat procedure with northern vertices */
   1.716 +  cur_dist = pgl_distance(
   1.717 +    point->lat, point->lon, box->lat_max, box->lon_max
   1.718 +  ) - d;
   1.719 +  if (cur_dist <= 0) return 0;
   1.720 +  if (cur_dist < min_dist) min_dist = cur_dist;
   1.721 +  cur_dist = pgl_distance(
   1.722 +    point->lat, point->lon, box->lat_max, box->lon_min
   1.723 +  ) - d;
   1.724 +  if (cur_dist <= 0) return 0;
   1.725 +  if (cur_dist < min_dist) min_dist = cur_dist;
   1.726 +  /* return smallest value (unless already returned zero) */
   1.727 +  return min_dist;
   1.728 +}
   1.729 +
   1.730 +
   1.731 +/*----------------------------*
   1.732 + *  fractal geographic index  *
   1.733 + *----------------------------*/
   1.734 +
   1.735 +/* number of bytes used for geographic (center) position in keys */
   1.736 +#define PGL_KEY_LATLON_BYTELEN 7
   1.737 +
   1.738 +/* maximum reference value for logarithmic size of geographic objects */
   1.739 +#define PGL_AREAKEY_REFOBJSIZE (PGL_DIAMETER/3.0)  /* can be tweaked */
   1.740 +
   1.741 +/* safety margin to avoid floating point errors in distance estimation */
   1.742 +#define PGL_FPE_SAFETY (1.0+1e-14)  /* slightly greater than 1.0 */
   1.743 +
   1.744 +/* pointer to index key (either pgl_pointkey or pgl_areakey) */
   1.745 +typedef unsigned char *pgl_keyptr;
   1.746 +
   1.747 +/* index key for points (objects with zero area) on the spheroid */
   1.748 +/* bit  0..55: interspersed bits of latitude and longitude,
   1.749 +   bit 56..57: always zero,
   1.750 +   bit 58..63: node depth in hypothetic (full) tree from 0 to 56 (incl.) */
   1.751 +typedef unsigned char pgl_pointkey[PGL_KEY_LATLON_BYTELEN+1];
   1.752 +
   1.753 +/* index key for geographic objects on spheroid with area greater than zero */
   1.754 +/* bit  0..55: interspersed bits of latitude and longitude of center point,
   1.755 +   bit     56: always set to 1,
   1.756 +   bit 57..63: node depth in hypothetic (full) tree from 0 to (2*56)+1 (incl.),
   1.757 +   bit 64..71: logarithmic object size from 0 to 56+1 = 57 (incl.), but set to
   1.758 +               PGL_KEY_OBJSIZE_EMPTY (with interspersed bits = 0 and node depth
   1.759 +               = 113) for empty objects, and set to PGL_KEY_OBJSIZE_UNIVERSAL
   1.760 +               (with interspersed bits = 0 and node depth = 0) for keys which
   1.761 +               cover both empty and non-empty objects */
   1.762 +
   1.763 +typedef unsigned char pgl_areakey[PGL_KEY_LATLON_BYTELEN+2];
   1.764 +
   1.765 +/* helper macros for reading/writing index keys */
   1.766 +#define PGL_KEY_NODEDEPTH_OFFSET  PGL_KEY_LATLON_BYTELEN
   1.767 +#define PGL_KEY_OBJSIZE_OFFSET    (PGL_KEY_NODEDEPTH_OFFSET+1)
   1.768 +#define PGL_POINTKEY_MAXDEPTH     (PGL_KEY_LATLON_BYTELEN*8)
   1.769 +#define PGL_AREAKEY_MAXDEPTH      (2*PGL_POINTKEY_MAXDEPTH+1)
   1.770 +#define PGL_AREAKEY_MAXOBJSIZE    (PGL_POINTKEY_MAXDEPTH+1)
   1.771 +#define PGL_AREAKEY_TYPEMASK      0x80
   1.772 +#define PGL_KEY_LATLONBIT(key, n) ((key)[(n)/8] & (0x80 >> ((n)%8)))
   1.773 +#define PGL_KEY_LATLONBIT_DIFF(key1, key2, n) \
   1.774 +                                  ( PGL_KEY_LATLONBIT(key1, n) ^ \
   1.775 +                                    PGL_KEY_LATLONBIT(key2, n) )
   1.776 +#define PGL_KEY_IS_AREAKEY(key)   ((key)[PGL_KEY_NODEDEPTH_OFFSET] & \
   1.777 +                                    PGL_AREAKEY_TYPEMASK)
   1.778 +#define PGL_KEY_NODEDEPTH(key)    ((key)[PGL_KEY_NODEDEPTH_OFFSET] & \
   1.779 +                                    (PGL_AREAKEY_TYPEMASK-1))
   1.780 +#define PGL_KEY_OBJSIZE(key)      ((key)[PGL_KEY_OBJSIZE_OFFSET])
   1.781 +#define PGL_KEY_OBJSIZE_EMPTY     126
   1.782 +#define PGL_KEY_OBJSIZE_UNIVERSAL 127
   1.783 +#define PGL_KEY_IS_EMPTY(key)     ( PGL_KEY_IS_AREAKEY(key) && \
   1.784 +                                    (key)[PGL_KEY_OBJSIZE_OFFSET] == \
   1.785 +                                    PGL_KEY_OBJSIZE_EMPTY )
   1.786 +#define PGL_KEY_IS_UNIVERSAL(key) ( PGL_KEY_IS_AREAKEY(key) && \
   1.787 +                                    (key)[PGL_KEY_OBJSIZE_OFFSET] == \
   1.788 +                                    PGL_KEY_OBJSIZE_UNIVERSAL )
   1.789 +
   1.790 +/* set area key to match empty objects only */
   1.791 +static void pgl_key_set_empty(pgl_keyptr key) {
   1.792 +  memset(key, 0, sizeof(pgl_areakey));
   1.793 +  /* Note: setting node depth to maximum is required for picksplit function */
   1.794 +  key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK | PGL_AREAKEY_MAXDEPTH;
   1.795 +  key[PGL_KEY_OBJSIZE_OFFSET] = PGL_KEY_OBJSIZE_EMPTY;
   1.796 +}
   1.797 +
   1.798 +/* set area key to match any object (including empty objects) */
   1.799 +static void pgl_key_set_universal(pgl_keyptr key) {
   1.800 +  memset(key, 0, sizeof(pgl_areakey));
   1.801 +  key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK;
   1.802 +  key[PGL_KEY_OBJSIZE_OFFSET] = PGL_KEY_OBJSIZE_UNIVERSAL;
   1.803 +}
   1.804 +
   1.805 +/* convert a point on earth into a max-depth key to be used in index */
   1.806 +static void pgl_point_to_key(pgl_point *point, pgl_keyptr key) {
   1.807 +  double lat = point->lat;
   1.808 +  double lon = point->lon;
   1.809 +  int i;
   1.810 +  /* clear latitude and longitude bits */
   1.811 +  memset(key, 0, PGL_KEY_LATLON_BYTELEN);
   1.812 +  /* set node depth to maximum and type bit to zero */
   1.813 +  key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_POINTKEY_MAXDEPTH;
   1.814 +  /* iterate over all latitude/longitude bit pairs */
   1.815 +  for (i=0; i<PGL_POINTKEY_MAXDEPTH/2; i++) {
   1.816 +    /* determine latitude bit */
   1.817 +    if (lat >= 0) {
   1.818 +      key[i/4] |= 0x80 >> (2*(i%4));
   1.819 +      lat *= 2; lat -= 90;
   1.820 +    } else {
   1.821 +      lat *= 2; lat += 90;
   1.822 +    }
   1.823 +    /* determine longitude bit */
   1.824 +    if (lon >= 0) {
   1.825 +      key[i/4] |= 0x80 >> (2*(i%4)+1);
   1.826 +      lon *= 2; lon -= 180;
   1.827 +    } else {
   1.828 +      lon *= 2; lon += 180;
   1.829 +    }
   1.830 +  }
   1.831 +}
   1.832 +
   1.833 +/* convert a circle on earth into a max-depth key to be used in an index */
   1.834 +static void pgl_circle_to_key(pgl_circle *circle, pgl_keyptr key) {
   1.835 +  /* handle special case of empty circle */
   1.836 +  if (circle->radius < 0) {
   1.837 +    pgl_key_set_empty(key);
   1.838 +    return;
   1.839 +  }
   1.840 +  /* perform same action as for point keys */
   1.841 +  pgl_point_to_key(&(circle->center), key);
   1.842 +  /* but overwrite type and node depth to fit area index key */
   1.843 +  key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK | PGL_AREAKEY_MAXDEPTH;
   1.844 +  /* check if radius is greater than (or equal to) reference size */
   1.845 +  /* (treat equal values as greater values for numerical safety) */
   1.846 +  if (circle->radius >= PGL_AREAKEY_REFOBJSIZE) {
   1.847 +    /* if yes, set logarithmic size to zero */
   1.848 +    key[PGL_KEY_OBJSIZE_OFFSET] = 0;
   1.849 +  } else {
   1.850 +    /* otherwise, determine logarithmic size iteratively */
   1.851 +    /* (one step is equivalent to a factor of sqrt(2)) */
   1.852 +    double reference = PGL_AREAKEY_REFOBJSIZE / M_SQRT2;
   1.853 +    int objsize = 1;
   1.854 +    while (objsize < PGL_AREAKEY_MAXOBJSIZE) {
   1.855 +      /* stop when radius is greater than (or equal to) adjusted reference */
   1.856 +      /* (treat equal values as greater values for numerical safety) */
   1.857 +      if (circle->radius >= reference) break;
   1.858 +      reference /= M_SQRT2;
   1.859 +      objsize++;
   1.860 +    }
   1.861 +    /* set logarithmic size to determined value */
   1.862 +    key[PGL_KEY_OBJSIZE_OFFSET] = objsize;
   1.863 +  }
   1.864 +}
   1.865 +
   1.866 +/* check if one key is subkey of another key or vice versa */
   1.867 +static bool pgl_keys_overlap(pgl_keyptr key1, pgl_keyptr key2) {
   1.868 +  int i;  /* key bit offset (includes both lat/lon and log. obj. size bits) */
   1.869 +  /* determine smallest depth */
   1.870 +  int depth1 = PGL_KEY_NODEDEPTH(key1);
   1.871 +  int depth2 = PGL_KEY_NODEDEPTH(key2);
   1.872 +  int depth = (depth1 < depth2) ? depth1 : depth2;
   1.873 +  /* check if keys are area keys (assuming that both keys have same type) */
   1.874 +  if (PGL_KEY_IS_AREAKEY(key1)) {
   1.875 +    int j = 0;  /* bit offset for logarithmic object size bits */
   1.876 +    int k = 0;  /* bit offset for latitude and longitude */
   1.877 +    /* fetch logarithmic object size information */
   1.878 +    int objsize1 = PGL_KEY_OBJSIZE(key1);
   1.879 +    int objsize2 = PGL_KEY_OBJSIZE(key2);
   1.880 +    /* handle special cases for empty objects (universal and empty keys) */
   1.881 +    if (
   1.882 +      objsize1 == PGL_KEY_OBJSIZE_UNIVERSAL ||
   1.883 +      objsize2 == PGL_KEY_OBJSIZE_UNIVERSAL
   1.884 +    ) return true;
   1.885 +    if (
   1.886 +      objsize1 == PGL_KEY_OBJSIZE_EMPTY ||
   1.887 +      objsize2 == PGL_KEY_OBJSIZE_EMPTY
   1.888 +    ) return objsize1 == objsize2;
   1.889 +    /* iterate through key bits */
   1.890 +    for (i=0; i<depth; i++) {
   1.891 +      /* every second bit is a bit describing the object size */
   1.892 +      if (i%2 == 0) {
   1.893 +        /* check if object size bit is different in both keys (objsize1 and
   1.894 +           objsize2 describe the minimum index when object size bit is set) */
   1.895 +        if (
   1.896 +          (objsize1 <= j && objsize2 > j) ||
   1.897 +          (objsize2 <= j && objsize1 > j)
   1.898 +        ) {
   1.899 +          /* bit differs, therefore keys are in separate branches */
   1.900 +          return false;
   1.901 +        }
   1.902 +        /* increase bit counter for object size bits */
   1.903 +        j++;
   1.904 +      }
   1.905 +      /* all other bits describe latitude and longitude */
   1.906 +      else {
   1.907 +        /* check if bit differs in both keys */
   1.908 +        if (PGL_KEY_LATLONBIT_DIFF(key1, key2, k)) {
   1.909 +          /* bit differs, therefore keys are in separate branches */
   1.910 +          return false;
   1.911 +        }
   1.912 +        /* increase bit counter for latitude/longitude bits */
   1.913 +        k++;
   1.914 +      }
   1.915 +    }
   1.916 +  }
   1.917 +  /* if not, keys are point keys */
   1.918 +  else {
   1.919 +    /* iterate through key bits */
   1.920 +    for (i=0; i<depth; i++) {
   1.921 +      /* check if bit differs in both keys */
   1.922 +      if (PGL_KEY_LATLONBIT_DIFF(key1, key2, i)) {
   1.923 +        /* bit differs, therefore keys are in separate branches */
   1.924 +        return false;
   1.925 +      }
   1.926 +    }
   1.927 +  }
   1.928 +  /* return true because keys are in the same branch */
   1.929 +  return true;
   1.930 +}
   1.931 +
   1.932 +/* combine two keys into new key which covers both original keys */
   1.933 +/* (result stored in first argument) */
   1.934 +static void pgl_unite_keys(pgl_keyptr dst, pgl_keyptr src) {
   1.935 +  int i;  /* key bit offset (includes both lat/lon and log. obj. size bits) */
   1.936 +  /* determine smallest depth */
   1.937 +  int depth1 = PGL_KEY_NODEDEPTH(dst);
   1.938 +  int depth2 = PGL_KEY_NODEDEPTH(src);
   1.939 +  int depth = (depth1 < depth2) ? depth1 : depth2;
   1.940 +  /* check if keys are area keys (assuming that both keys have same type) */
   1.941 +  if (PGL_KEY_IS_AREAKEY(dst)) {
   1.942 +    pgl_areakey dstbuf = { 0, };  /* destination buffer (cleared) */
   1.943 +    int j = 0;  /* bit offset for logarithmic object size bits */
   1.944 +    int k = 0;  /* bit offset for latitude and longitude */
   1.945 +    /* fetch logarithmic object size information */
   1.946 +    int objsize1 = PGL_KEY_OBJSIZE(dst);
   1.947 +    int objsize2 = PGL_KEY_OBJSIZE(src);
   1.948 +    /* handle special cases for empty objects (universal and empty keys) */
   1.949 +    if (
   1.950 +      objsize1 > PGL_AREAKEY_MAXOBJSIZE ||
   1.951 +      objsize2 > PGL_AREAKEY_MAXOBJSIZE
   1.952 +    ) {
   1.953 +      if (
   1.954 +        objsize1 == PGL_KEY_OBJSIZE_EMPTY &&
   1.955 +        objsize2 == PGL_KEY_OBJSIZE_EMPTY
   1.956 +      ) pgl_key_set_empty(dst);
   1.957 +      else pgl_key_set_universal(dst);
   1.958 +      return;
   1.959 +    }
   1.960 +    /* iterate through key bits */
   1.961 +    for (i=0; i<depth; i++) {
   1.962 +      /* every second bit is a bit describing the object size */
   1.963 +      if (i%2 == 0) {
   1.964 +        /* increase bit counter for object size bits first */
   1.965 +        /* (handy when setting objsize variable) */
   1.966 +        j++;
   1.967 +        /* check if object size bit is set in neither key */
   1.968 +        if (objsize1 >= j && objsize2 >= j) {
   1.969 +          /* set objsize in destination buffer to indicate that size bit is
   1.970 +             unset in destination buffer at the current bit position */
   1.971 +          dstbuf[PGL_KEY_OBJSIZE_OFFSET] = j;
   1.972 +        }
   1.973 +        /* break if object size bit is set in one key only */
   1.974 +        else if (objsize1 >= j || objsize2 >= j) break;
   1.975 +      }
   1.976 +      /* all other bits describe latitude and longitude */
   1.977 +      else {
   1.978 +        /* break if bit differs in both keys */
   1.979 +        if (PGL_KEY_LATLONBIT(dst, k)) {
   1.980 +          if (!PGL_KEY_LATLONBIT(src, k)) break;
   1.981 +          /* but set bit in destination buffer if bit is set in both keys */
   1.982 +          dstbuf[k/8] |= 0x80 >> (k%8);
   1.983 +        } else if (PGL_KEY_LATLONBIT(src, k)) break;
   1.984 +        /* increase bit counter for latitude/longitude bits */
   1.985 +        k++;
   1.986 +      }
   1.987 +    }
   1.988 +    /* set common node depth and type bit (type bit = 1) */
   1.989 +    dstbuf[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK | i;
   1.990 +    /* copy contents of destination buffer to first key */
   1.991 +    memcpy(dst, dstbuf, sizeof(pgl_areakey));
   1.992 +  }
   1.993 +  /* if not, keys are point keys */
   1.994 +  else {
   1.995 +    pgl_pointkey dstbuf = { 0, };  /* destination buffer (cleared) */
   1.996 +    /* iterate through key bits */
   1.997 +    for (i=0; i<depth; i++) {
   1.998 +      /* break if bit differs in both keys */
   1.999 +      if (PGL_KEY_LATLONBIT(dst, i)) {
  1.1000 +        if (!PGL_KEY_LATLONBIT(src, i)) break;
  1.1001 +        /* but set bit in destination buffer if bit is set in both keys */
  1.1002 +        dstbuf[i/8] |= 0x80 >> (i%8);
  1.1003 +      } else if (PGL_KEY_LATLONBIT(src, i)) break;
  1.1004 +    }
  1.1005 +    /* set common node depth (type bit = 0) */
  1.1006 +    dstbuf[PGL_KEY_NODEDEPTH_OFFSET] = i;
  1.1007 +    /* copy contents of destination buffer to first key */
  1.1008 +    memcpy(dst, dstbuf, sizeof(pgl_pointkey));
  1.1009 +  }
  1.1010 +}
  1.1011 +
  1.1012 +/* determine center(!) boundaries and radius estimation of index key */
  1.1013 +static double pgl_key_to_box(pgl_keyptr key, pgl_box *box) {
  1.1014 +  int i;
  1.1015 +  /* determine node depth */
  1.1016 +  int depth = PGL_KEY_NODEDEPTH(key);
  1.1017 +  /* center point of possible result */
  1.1018 +  double lat = 0;
  1.1019 +  double lon = 0;
  1.1020 +  /* maximum distance of real center point from key center */
  1.1021 +  double dlat = 90;
  1.1022 +  double dlon = 180;
  1.1023 +  /* maximum radius of contained objects */
  1.1024 +  double radius = 0;  /* always return zero for point index keys */
  1.1025 +  /* check if key is area key */
  1.1026 +  if (PGL_KEY_IS_AREAKEY(key)) {
  1.1027 +    /* get logarithmic object size */
  1.1028 +    int objsize = PGL_KEY_OBJSIZE(key);
  1.1029 +    /* handle special cases for empty objects (universal and empty keys) */
  1.1030 +    if (objsize == PGL_KEY_OBJSIZE_EMPTY) {
  1.1031 +      pgl_box_set_empty(box);
  1.1032 +      return 0;
  1.1033 +    } else if (objsize == PGL_KEY_OBJSIZE_UNIVERSAL) {
  1.1034 +      box->lat_min = -90;
  1.1035 +      box->lat_max =  90;
  1.1036 +      box->lon_min = -180;
  1.1037 +      box->lon_max =  180;
  1.1038 +      return 0;  /* any value >= 0 would do */
  1.1039 +    }
  1.1040 +    /* calculate maximum possible radius of objects covered by the given key */
  1.1041 +    if (objsize == 0) radius = INFINITY;
  1.1042 +    else {
  1.1043 +      radius = PGL_AREAKEY_REFOBJSIZE;
  1.1044 +      while (--objsize) radius /= M_SQRT2;
  1.1045 +    }
  1.1046 +    /* iterate over latitude and longitude bits in key */
  1.1047 +    /* (every second bit is a latitude or longitude bit) */
  1.1048 +    for (i=0; i<depth/2; i++) {
  1.1049 +      /* check if latitude bit */
  1.1050 +      if (i%2 == 0) {
  1.1051 +        /* cut latitude dimension in half */
  1.1052 +        dlat /= 2;
  1.1053 +        /* increase center latitude if bit is 1, otherwise decrease */
  1.1054 +        if (PGL_KEY_LATLONBIT(key, i)) lat += dlat;
  1.1055 +        else lat -= dlat;
  1.1056 +      }
  1.1057 +      /* otherwise longitude bit */
  1.1058 +      else {
  1.1059 +        /* cut longitude dimension in half */
  1.1060 +        dlon /= 2;
  1.1061 +        /* increase center longitude if bit is 1, otherwise decrease */
  1.1062 +        if (PGL_KEY_LATLONBIT(key, i)) lon += dlon;
  1.1063 +        else lon -= dlon;
  1.1064 +      }
  1.1065 +    }
  1.1066 +  }
  1.1067 +  /* if not, keys are point keys */
  1.1068 +  else {
  1.1069 +    /* iterate over all bits in key */
  1.1070 +    for (i=0; i<depth; i++) {
  1.1071 +      /* check if latitude bit */
  1.1072 +      if (i%2 == 0) {
  1.1073 +        /* cut latitude dimension in half */
  1.1074 +        dlat /= 2;
  1.1075 +        /* increase center latitude if bit is 1, otherwise decrease */
  1.1076 +        if (PGL_KEY_LATLONBIT(key, i)) lat += dlat;
  1.1077 +        else lat -= dlat;
  1.1078 +      }
  1.1079 +      /* otherwise longitude bit */
  1.1080 +      else {
  1.1081 +        /* cut longitude dimension in half */
  1.1082 +        dlon /= 2;
  1.1083 +        /* increase center longitude if bit is 1, otherwise decrease */
  1.1084 +        if (PGL_KEY_LATLONBIT(key, i)) lon += dlon;
  1.1085 +        else lon -= dlon;
  1.1086 +      }
  1.1087 +    }
  1.1088 +  }
  1.1089 +  /* calculate boundaries from center point and remaining dlat and dlon */
  1.1090 +  /* (return values through pointer to box) */
  1.1091 +  box->lat_min = lat - dlat;
  1.1092 +  box->lat_max = lat + dlat;
  1.1093 +  box->lon_min = lon - dlon;
  1.1094 +  box->lon_max = lon + dlon;
  1.1095 +  /* return radius (as a function return value) */
  1.1096 +  return radius;
  1.1097 +}
  1.1098 +
  1.1099 +/* estimator function for distance between point and index key */
  1.1100 +/* allowed to return smaller values than actually correct */
  1.1101 +static double pgl_estimate_key_distance(pgl_keyptr key, pgl_point *point) {
  1.1102 +  pgl_box box;  /* center(!) bounding box of area index key */
  1.1103 +  /* calculate center(!) bounding box and maximum radius of objects covered
  1.1104 +     by area index key (radius is zero for point index keys) */
  1.1105 +  double distance = pgl_key_to_box(key, &box);
  1.1106 +  /* calculate estimated distance between bounding box of center point of
  1.1107 +     indexed object and point passed as second argument, then substract maximum
  1.1108 +     radius of objects covered by index key */
  1.1109 +  /* (use PGL_FPE_SAFETY factor to cope with minor floating point errors) */
  1.1110 +  distance = (
  1.1111 +    pgl_estimate_point_box_distance(point, &box) / PGL_FPE_SAFETY -
  1.1112 +    distance * PGL_FPE_SAFETY
  1.1113 +  );
  1.1114 +  /* truncate negative results to zero */
  1.1115 +  if (distance <= 0) distance = 0;
  1.1116 +  /* return result */
  1.1117 +  return distance;
  1.1118 +}
  1.1119 +
  1.1120 +
  1.1121 +/*---------------------------------*
  1.1122 + *  helper functions for text I/O  *
  1.1123 + *---------------------------------*/
  1.1124 +
  1.1125 +#define PGL_NUMBUFLEN 64  /* buffer size for number to string conversion */
  1.1126 +
  1.1127 +/* convert floating point number to string (round-trip safe) */
  1.1128 +static void pgl_print_float(char *buf, double flt) {
  1.1129 +  /* check if number is integral */
  1.1130 +  if (trunc(flt) == flt) {
  1.1131 +    /* for integral floats use maximum precision */
  1.1132 +    snprintf(buf, PGL_NUMBUFLEN, "%.17g", flt);
  1.1133 +  } else {
  1.1134 +    /* otherwise check if 15, 16, or 17 digits needed (round-trip safety) */
  1.1135 +    snprintf(buf, PGL_NUMBUFLEN, "%.15g", flt);
  1.1136 +    if (strtod(buf, NULL) != flt) snprintf(buf, PGL_NUMBUFLEN, "%.16g", flt);
  1.1137 +    if (strtod(buf, NULL) != flt) snprintf(buf, PGL_NUMBUFLEN, "%.17g", flt);
  1.1138 +  }
  1.1139 +}
  1.1140 +
  1.1141 +/* convert latitude floating point number (in degrees) to string */
  1.1142 +static void pgl_print_lat(char *buf, double lat) {
  1.1143 +  if (signbit(lat)) {
  1.1144 +    /* treat negative latitudes (including -0) as south */
  1.1145 +    snprintf(buf, PGL_NUMBUFLEN, "S%015.12f", -lat);
  1.1146 +  } else {
  1.1147 +    /* treat positive latitudes (including +0) as north */
  1.1148 +    snprintf(buf, PGL_NUMBUFLEN, "N%015.12f", lat);
  1.1149 +  }
  1.1150 +}
  1.1151 +
  1.1152 +/* convert longitude floating point number (in degrees) to string */
  1.1153 +static void pgl_print_lon(char *buf, double lon) {
  1.1154 +  if (signbit(lon)) {
  1.1155 +    /* treat negative longitudes (including -0) as west */
  1.1156 +    snprintf(buf, PGL_NUMBUFLEN, "W%016.12f", -lon);
  1.1157 +  } else {
  1.1158 +    /* treat positive longitudes (including +0) as east */
  1.1159 +    snprintf(buf, PGL_NUMBUFLEN, "E%016.12f", lon);
  1.1160 +  }
  1.1161 +}
  1.1162 +
  1.1163 +/* bit masks used as return value of pgl_scan() function */
  1.1164 +#define PGL_SCAN_NONE 0      /* no value has been parsed */
  1.1165 +#define PGL_SCAN_LAT (1<<0)  /* latitude has been parsed */
  1.1166 +#define PGL_SCAN_LON (1<<1)  /* longitude has been parsed */
  1.1167 +#define PGL_SCAN_LATLON (PGL_SCAN_LAT | PGL_SCAN_LON)  /* bitwise OR of both */
  1.1168 +
  1.1169 +/* parse a coordinate (can be latitude or longitude) */
  1.1170 +static int pgl_scan(char **str, double *lat, double *lon) {
  1.1171 +  double val;
  1.1172 +  int len;
  1.1173 +  if (
  1.1174 +    sscanf(*str, " N %lf %n", &val, &len) ||
  1.1175 +    sscanf(*str, " n %lf %n", &val, &len)
  1.1176 +  ) {
  1.1177 +    *str += len; *lat = val; return PGL_SCAN_LAT;
  1.1178 +  }
  1.1179 +  if (
  1.1180 +    sscanf(*str, " S %lf %n", &val, &len) ||
  1.1181 +    sscanf(*str, " s %lf %n", &val, &len)
  1.1182 +  ) {
  1.1183 +    *str += len; *lat = -val; return PGL_SCAN_LAT;
  1.1184 +  }
  1.1185 +  if (
  1.1186 +    sscanf(*str, " E %lf %n", &val, &len) ||
  1.1187 +    sscanf(*str, " e %lf %n", &val, &len)
  1.1188 +  ) {
  1.1189 +    *str += len; *lon = val; return PGL_SCAN_LON;
  1.1190 +  }
  1.1191 +  if (
  1.1192 +    sscanf(*str, " W %lf %n", &val, &len) ||
  1.1193 +    sscanf(*str, " w %lf %n", &val, &len)
  1.1194 +  ) {
  1.1195 +    *str += len; *lon = -val; return PGL_SCAN_LON;
  1.1196 +  }
  1.1197 +  return PGL_SCAN_NONE;
  1.1198 +}
  1.1199 +
  1.1200 +
  1.1201 +/*-----------------*
  1.1202 + *  SQL functions  *
  1.1203 + *-----------------*/
  1.1204 +
  1.1205 +/* Note: These function names use "epoint", "ebox", etc. notation here instead
  1.1206 +   of "point", "box", etc. in order to distinguish them from any previously
  1.1207 +   defined functions. */
  1.1208 +
  1.1209 +/* function needed for dummy types and/or not implemented features */
  1.1210 +PG_FUNCTION_INFO_V1(pgl_notimpl);
  1.1211 +Datum pgl_notimpl(PG_FUNCTION_ARGS) {
  1.1212 +  ereport(ERROR, (errmsg("not implemented by pgLatLon")));
  1.1213 +}
  1.1214 +
  1.1215 +/* set point to latitude and longitude (including checks) */
  1.1216 +static void pgl_epoint_set_latlon(pgl_point *point, double lat, double lon) {
  1.1217 +  /* reject infinite or NaN values */
  1.1218 +  if (!isfinite(lat) || !isfinite(lon)) {
  1.1219 +    ereport(ERROR, (
  1.1220 +      errcode(ERRCODE_DATA_EXCEPTION),
  1.1221 +      errmsg("epoint requires finite coordinates")
  1.1222 +    ));
  1.1223 +  }
  1.1224 +  /* check latitude bounds */
  1.1225 +  if (lat < -90) {
  1.1226 +    ereport(WARNING, (errmsg("latitude exceeds south pole")));
  1.1227 +    lat = -90;
  1.1228 +  } else if (lat > 90) {
  1.1229 +    ereport(WARNING, (errmsg("latitude exceeds north pole")));
  1.1230 +    lat = 90;
  1.1231 +  }
  1.1232 +  /* check longitude bounds */
  1.1233 +  if (lon < -180) {
  1.1234 +    ereport(NOTICE, (errmsg("longitude west of 180th meridian normalized")));
  1.1235 +    lon += 360 - trunc(lon / 360) * 360;
  1.1236 +  } else if (lon > 180) {
  1.1237 +    ereport(NOTICE, (errmsg("longitude east of 180th meridian normalized")));
  1.1238 +    lon -= 360 + trunc(lon / 360) * 360;
  1.1239 +  }
  1.1240 +  /* store rounded latitude/longitude values for round-trip safety */
  1.1241 +  point->lat = pgl_round(lat);
  1.1242 +  point->lon = pgl_round(lon);
  1.1243 +}
  1.1244 +
  1.1245 +/* create point ("epoint" in SQL) from latitude and longitude */
  1.1246 +PG_FUNCTION_INFO_V1(pgl_create_epoint);
  1.1247 +Datum pgl_create_epoint(PG_FUNCTION_ARGS) {
  1.1248 +  pgl_point *point = (pgl_point *)palloc(sizeof(pgl_point));
  1.1249 +  pgl_epoint_set_latlon(point, PG_GETARG_FLOAT8(0), PG_GETARG_FLOAT8(1));
  1.1250 +  PG_RETURN_POINTER(point);
  1.1251 +}
  1.1252 +
  1.1253 +/* parse point ("epoint" in SQL) */
  1.1254 +/* format: '[NS]<float> [EW]<float>' */
  1.1255 +PG_FUNCTION_INFO_V1(pgl_epoint_in);
  1.1256 +Datum pgl_epoint_in(PG_FUNCTION_ARGS) {
  1.1257 +  char *str = PG_GETARG_CSTRING(0);  /* input string */
  1.1258 +  char *strptr = str;  /* current position within string */
  1.1259 +  int done = 0;        /* bit mask storing if latitude or longitude was read */
  1.1260 +  double lat, lon;     /* parsed values as double precision floats */
  1.1261 +  pgl_point *point;    /* return value (to be palloc'ed) */
  1.1262 +  /* parse two floats (each latitude or longitude) separated by white-space */
  1.1263 +  done |= pgl_scan(&strptr, &lat, &lon);
  1.1264 +  if (strptr != str && isspace(strptr[-1])) {
  1.1265 +    done |= pgl_scan(&strptr, &lat, &lon);
  1.1266 +  }
  1.1267 +  /* require end of string, and latitude and longitude parsed successfully */
  1.1268 +  if (strptr[0] || done != PGL_SCAN_LATLON) {
  1.1269 +    ereport(ERROR, (
  1.1270 +      errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
  1.1271 +      errmsg("invalid input syntax for type epoint: \"%s\"", str)
  1.1272 +    ));
  1.1273 +  }
  1.1274 +  /* allocate memory for result */
  1.1275 +  point = (pgl_point *)palloc(sizeof(pgl_point));
  1.1276 +  /* set latitude and longitude (and perform checks) */
  1.1277 +  pgl_epoint_set_latlon(point, lat, lon);
  1.1278 +  /* return result */
  1.1279 +  PG_RETURN_POINTER(point);
  1.1280 +}
  1.1281 +
  1.1282 +/* create box ("ebox" in SQL) that is empty */
  1.1283 +PG_FUNCTION_INFO_V1(pgl_create_empty_ebox);
  1.1284 +Datum pgl_create_empty_ebox(PG_FUNCTION_ARGS) {
  1.1285 +  pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
  1.1286 +  pgl_box_set_empty(box);
  1.1287 +  PG_RETURN_POINTER(box);
  1.1288 +}
  1.1289 +
  1.1290 +/* set box to given boundaries (including checks) */
  1.1291 +static void pgl_ebox_set_boundaries(
  1.1292 +  pgl_box *box,
  1.1293 +  double lat_min, double lat_max, double lon_min, double lon_max
  1.1294 +) {
  1.1295 +  /* if minimum latitude is greater than maximum latitude, return empty box */
  1.1296 +  if (lat_min > lat_max) {
  1.1297 +    pgl_box_set_empty(box);
  1.1298 +    return;
  1.1299 +  }
  1.1300 +  /* otherwise reject infinite or NaN values */
  1.1301 +  if (
  1.1302 +    !isfinite(lat_min) || !isfinite(lat_max) ||
  1.1303 +    !isfinite(lon_min) || !isfinite(lon_max)
  1.1304 +  ) {
  1.1305 +    ereport(ERROR, (
  1.1306 +      errcode(ERRCODE_DATA_EXCEPTION),
  1.1307 +      errmsg("ebox requires finite coordinates")
  1.1308 +    ));
  1.1309 +  }
  1.1310 +  /* check latitude bounds */
  1.1311 +  if (lat_max < -90) {
  1.1312 +    ereport(WARNING, (errmsg("northern latitude exceeds south pole")));
  1.1313 +    lat_max = -90;
  1.1314 +  } else if (lat_max > 90) {
  1.1315 +    ereport(WARNING, (errmsg("northern latitude exceeds north pole")));
  1.1316 +    lat_max = 90;
  1.1317 +  }
  1.1318 +  if (lat_min < -90) {
  1.1319 +    ereport(WARNING, (errmsg("southern latitude exceeds south pole")));
  1.1320 +    lat_min = -90;
  1.1321 +  } else if (lat_min > 90) {
  1.1322 +    ereport(WARNING, (errmsg("southern latitude exceeds north pole")));
  1.1323 +    lat_min = 90;
  1.1324 +  }
  1.1325 +  /* check if all longitudes are included */
  1.1326 +  if (lon_max - lon_min >= 360) {
  1.1327 +    if (lon_max - lon_min > 360) ereport(WARNING, (
  1.1328 +      errmsg("longitude coverage greater than 360 degrees")
  1.1329 +    ));
  1.1330 +    lon_min = -180;
  1.1331 +    lon_max = 180;
  1.1332 +  } else {
  1.1333 +    /* normalize longitude bounds */
  1.1334 +    if      (lon_min < -180) lon_min += 360 - trunc(lon_min / 360) * 360;
  1.1335 +    else if (lon_min >  180) lon_min -= 360 + trunc(lon_min / 360) * 360;
  1.1336 +    if      (lon_max < -180) lon_max += 360 - trunc(lon_max / 360) * 360;
  1.1337 +    else if (lon_max >  180) lon_max -= 360 + trunc(lon_max / 360) * 360;
  1.1338 +  }
  1.1339 +  /* store rounded latitude/longitude values for round-trip safety */
  1.1340 +  box->lat_min = pgl_round(lat_min);
  1.1341 +  box->lat_max = pgl_round(lat_max);
  1.1342 +  box->lon_min = pgl_round(lon_min);
  1.1343 +  box->lon_max = pgl_round(lon_max);
  1.1344 +  /* ensure that rounding does not change orientation */
  1.1345 +  if (lon_min > lon_max && box->lon_min == box->lon_max) {
  1.1346 +    box->lon_min = -180;
  1.1347 +    box->lon_max = 180;
  1.1348 +  }
  1.1349 +}
  1.1350 +
  1.1351 +/* create box ("ebox" in SQL) from min/max latitude and min/max longitude */
  1.1352 +PG_FUNCTION_INFO_V1(pgl_create_ebox);
  1.1353 +Datum pgl_create_ebox(PG_FUNCTION_ARGS) {
  1.1354 +  pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
  1.1355 +  pgl_ebox_set_boundaries(
  1.1356 +    box,
  1.1357 +    PG_GETARG_FLOAT8(0), PG_GETARG_FLOAT8(1),
  1.1358 +    PG_GETARG_FLOAT8(2), PG_GETARG_FLOAT8(3)
  1.1359 +  );
  1.1360 +  PG_RETURN_POINTER(box);
  1.1361 +}
  1.1362 +
  1.1363 +/* create box ("ebox" in SQL) from two points ("epoint"s) */
  1.1364 +/* (can not be used to cover a longitude range of more than 120 degrees) */
  1.1365 +PG_FUNCTION_INFO_V1(pgl_create_ebox_from_epoints);
  1.1366 +Datum pgl_create_ebox_from_epoints(PG_FUNCTION_ARGS) {
  1.1367 +  pgl_point *point1 = (pgl_point *)PG_GETARG_POINTER(0);
  1.1368 +  pgl_point *point2 = (pgl_point *)PG_GETARG_POINTER(1);
  1.1369 +  pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
  1.1370 +  double lat_min, lat_max, lon_min, lon_max;
  1.1371 +  double dlon;  /* longitude range (delta longitude) */
  1.1372 +  /* order latitude and longitude boundaries */
  1.1373 +  if (point2->lat < point1->lat) {
  1.1374 +    lat_min = point2->lat;
  1.1375 +    lat_max = point1->lat;
  1.1376 +  } else {
  1.1377 +    lat_min = point1->lat;
  1.1378 +    lat_max = point2->lat;
  1.1379 +  }
  1.1380 +  if (point2->lon < point1->lon) {
  1.1381 +    lon_min = point2->lon;
  1.1382 +    lon_max = point1->lon;
  1.1383 +  } else {
  1.1384 +    lon_min = point1->lon;
  1.1385 +    lon_max = point2->lon;
  1.1386 +  }
  1.1387 +  /* calculate longitude range (round to avoid floating point errors) */
  1.1388 +  dlon = pgl_round(lon_max - lon_min);
  1.1389 +  /* determine east-west direction */
  1.1390 +  if (dlon >= 240) {
  1.1391 +    /* assume that 180th meridian is crossed and swap min/max longitude */
  1.1392 +    double swap = lon_min; lon_min = lon_max; lon_max = swap;
  1.1393 +  } else if (dlon > 120) {
  1.1394 +    /* unclear orientation since delta longitude > 120 */
  1.1395 +    ereport(ERROR, (
  1.1396 +      errcode(ERRCODE_DATA_EXCEPTION),
  1.1397 +      errmsg("can not determine east/west orientation for ebox")
  1.1398 +    ));
  1.1399 +  }
  1.1400 +  /* use boundaries to setup box (and perform checks) */
  1.1401 +  pgl_ebox_set_boundaries(box, lat_min, lat_max, lon_min, lon_max);
  1.1402 +  /* return result */
  1.1403 +  PG_RETURN_POINTER(box);
  1.1404 +}
  1.1405 +
  1.1406 +/* parse box ("ebox" in SQL) */
  1.1407 +/* format: '[NS]<float> [EW]<float> [NS]<float> [EW]<float>'
  1.1408 +       or: '[NS]<float> [NS]<float> [EW]<float> [EW]<float>' */
  1.1409 +PG_FUNCTION_INFO_V1(pgl_ebox_in);
  1.1410 +Datum pgl_ebox_in(PG_FUNCTION_ARGS) {
  1.1411 +  char *str = PG_GETARG_CSTRING(0);  /* input string */
  1.1412 +  char *str_lower;     /* lower case version of input string */
  1.1413 +  char *strptr;        /* current position within string */
  1.1414 +  int valid;           /* number of valid chars */
  1.1415 +  int done;            /* specifies if latitude or longitude was read */
  1.1416 +  double val;          /* temporary variable */
  1.1417 +  int lat_count = 0;   /* count of latitude values parsed */
  1.1418 +  int lon_count = 0;   /* count of longitufde values parsed */
  1.1419 +  double lat_min, lat_max, lon_min, lon_max;  /* see pgl_box struct */
  1.1420 +  pgl_box *box;        /* return value (to be palloc'ed) */
  1.1421 +  /* lowercase input */
  1.1422 +  str_lower = psprintf("%s", str);
  1.1423 +  for (strptr=str_lower; *strptr; strptr++) {
  1.1424 +    if (*strptr >= 'A' && *strptr <= 'Z') *strptr += 'a' - 'A';
  1.1425 +  }
  1.1426 +  /* reset reading position to start of (lowercase) string */
  1.1427 +  strptr = str_lower;
  1.1428 +  /* check if empty box */
  1.1429 +  valid = 0;
  1.1430 +  sscanf(strptr, " empty %n", &valid);
  1.1431 +  if (valid && strptr[valid] == 0) {
  1.1432 +    /* allocate and return empty box */
  1.1433 +    box = (pgl_box *)palloc(sizeof(pgl_box));
  1.1434 +    pgl_box_set_empty(box);
  1.1435 +    PG_RETURN_POINTER(box);
  1.1436 +  }
  1.1437 +  /* demand four blocks separated by whitespace */
  1.1438 +  valid = 0;
  1.1439 +  sscanf(strptr, " %*s %*s %*s %*s %n", &valid);
  1.1440 +  /* if four blocks separated by whitespace exist, parse those blocks */
  1.1441 +  if (strptr[valid] == 0) while (strptr[0]) {
  1.1442 +    /* parse either latitude or longitude (whichever found in input string) */
  1.1443 +    done = pgl_scan(&strptr, &val, &val);
  1.1444 +    /* store latitude or longitude in lat_min, lat_max, lon_min, or lon_max */
  1.1445 +    if (done == PGL_SCAN_LAT) {
  1.1446 +      if (!lat_count) lat_min = val; else lat_max = val;
  1.1447 +      lat_count++;
  1.1448 +    } else if (done == PGL_SCAN_LON) {
  1.1449 +      if (!lon_count) lon_min = val; else lon_max = val;
  1.1450 +      lon_count++;
  1.1451 +    } else {
  1.1452 +      break;
  1.1453 +    }
  1.1454 +  }
  1.1455 +  /* require end of string, and two latitude and two longitude values */
  1.1456 +  if (strptr[0] || lat_count != 2 || lon_count != 2) {
  1.1457 +    ereport(ERROR, (
  1.1458 +      errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
  1.1459 +      errmsg("invalid input syntax for type ebox: \"%s\"", str)
  1.1460 +    ));
  1.1461 +  }
  1.1462 +  /* free lower case string */
  1.1463 +  pfree(str_lower);
  1.1464 +  /* order boundaries (maximum greater than minimum) */
  1.1465 +  if (lat_min > lat_max) { val = lat_min; lat_min = lat_max; lat_max = val; }
  1.1466 +  if (lon_min > lon_max) { val = lon_min; lon_min = lon_max; lon_max = val; }
  1.1467 +  /* allocate memory for result */
  1.1468 +  box = (pgl_box *)palloc(sizeof(pgl_box));
  1.1469 +  /* set boundaries (and perform checks) */
  1.1470 +  pgl_ebox_set_boundaries(box, lat_min, lat_max, lon_min, lon_max);
  1.1471 +  /* return result */
  1.1472 +  PG_RETURN_POINTER(box);
  1.1473 +}
  1.1474 +
  1.1475 +/* set circle to given latitude, longitude, and radius (including checks) */
  1.1476 +static void pgl_ecircle_set_latlon_radius(
  1.1477 +  pgl_circle *circle, double lat, double lon, double radius
  1.1478 +) {
  1.1479 +  /* set center point (including checks) */
  1.1480 +  pgl_epoint_set_latlon(&(circle->center), lat, lon);
  1.1481 +  /* handle non-positive radius */
  1.1482 +  if (isnan(radius)) {
  1.1483 +    ereport(ERROR, (
  1.1484 +      errcode(ERRCODE_DATA_EXCEPTION),
  1.1485 +      errmsg("invalid radius for ecircle")
  1.1486 +    ));
  1.1487 +  }
  1.1488 +  if (radius == 0) radius = 0;  /* avoids -0 */
  1.1489 +  else if (radius < 0) {
  1.1490 +    if (isfinite(radius)) {
  1.1491 +      ereport(NOTICE, (errmsg("negative radius converted to minus infinity")));
  1.1492 +    }
  1.1493 +    radius = -INFINITY;
  1.1494 +  }
  1.1495 +  /* store radius (round-trip safety is ensured by pgl_print_float) */
  1.1496 +  circle->radius = radius;
  1.1497 +}
  1.1498 +
  1.1499 +/* create circle ("ecircle" in SQL) from latitude, longitude, and radius */
  1.1500 +PG_FUNCTION_INFO_V1(pgl_create_ecircle);
  1.1501 +Datum pgl_create_ecircle(PG_FUNCTION_ARGS) {
  1.1502 +  pgl_circle *circle = (pgl_circle *)palloc(sizeof(pgl_circle));
  1.1503 +  pgl_ecircle_set_latlon_radius(
  1.1504 +    circle, PG_GETARG_FLOAT8(0), PG_GETARG_FLOAT8(1), PG_GETARG_FLOAT8(2)
  1.1505 +  );
  1.1506 +  PG_RETURN_POINTER(circle);
  1.1507 +}
  1.1508 +
  1.1509 +/* create circle ("ecircle" in SQL) from point ("epoint"), and radius */
  1.1510 +PG_FUNCTION_INFO_V1(pgl_create_ecircle_from_epoint);
  1.1511 +Datum pgl_create_ecircle_from_epoint(PG_FUNCTION_ARGS) {
  1.1512 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.1513 +  double radius = PG_GETARG_FLOAT8(1);
  1.1514 +  pgl_circle *circle = (pgl_circle *)palloc(sizeof(pgl_circle));
  1.1515 +  /* set latitude, longitude, radius (and perform checks) */
  1.1516 +  pgl_ecircle_set_latlon_radius(circle, point->lat, point->lon, radius);
  1.1517 +  /* return result */
  1.1518 +  PG_RETURN_POINTER(circle);
  1.1519 +}
  1.1520 +
  1.1521 +/* parse circle ("ecircle" in SQL) */
  1.1522 +/* format: '[NS]<float> [EW]<float> <float>' */
  1.1523 +PG_FUNCTION_INFO_V1(pgl_ecircle_in);
  1.1524 +Datum pgl_ecircle_in(PG_FUNCTION_ARGS) {
  1.1525 +  char *str = PG_GETARG_CSTRING(0);  /* input string */
  1.1526 +  char *strptr = str;       /* current position within string */
  1.1527 +  double lat, lon, radius;  /* parsed values as double precision flaots */
  1.1528 +  int valid = 0;            /* number of valid chars */
  1.1529 +  int done = 0;             /* stores if latitude and/or longitude was read */
  1.1530 +  pgl_circle *circle;       /* return value (to be palloc'ed) */
  1.1531 +  /* demand three blocks separated by whitespace */
  1.1532 +  sscanf(strptr, " %*s %*s %*s %n", &valid);
  1.1533 +  /* if three blocks separated by whitespace exist, parse those blocks */
  1.1534 +  if (strptr[valid] == 0) {
  1.1535 +    /* parse latitude and longitude */
  1.1536 +    done |= pgl_scan(&strptr, &lat, &lon);
  1.1537 +    done |= pgl_scan(&strptr, &lat, &lon);
  1.1538 +    /* parse radius (while incrementing strptr by number of bytes parsed) */
  1.1539 +    valid = 0;
  1.1540 +    if (sscanf(strptr, " %lf %n", &radius, &valid) == 1) strptr += valid;
  1.1541 +  }
  1.1542 +  /* require end of string and both latitude and longitude being parsed */
  1.1543 +  if (strptr[0] || done != PGL_SCAN_LATLON) {
  1.1544 +    ereport(ERROR, (
  1.1545 +      errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
  1.1546 +      errmsg("invalid input syntax for type ecircle: \"%s\"", str)
  1.1547 +    ));
  1.1548 +  }
  1.1549 +  /* allocate memory for result */
  1.1550 +  circle = (pgl_circle *)palloc(sizeof(pgl_circle));
  1.1551 +  /* set latitude, longitude, radius (and perform checks) */
  1.1552 +  pgl_ecircle_set_latlon_radius(circle, lat, lon, radius);
  1.1553 +  /* return result */
  1.1554 +  PG_RETURN_POINTER(circle);
  1.1555 +}
  1.1556 +
  1.1557 +/* parse cluster ("ecluster" in SQL) */
  1.1558 +PG_FUNCTION_INFO_V1(pgl_ecluster_in);
  1.1559 +Datum pgl_ecluster_in(PG_FUNCTION_ARGS) {
  1.1560 +  int i;
  1.1561 +  char *str = PG_GETARG_CSTRING(0);  /* input string */
  1.1562 +  char *str_lower;         /* lower case version of input string */
  1.1563 +  char *strptr;            /* pointer to current reading position of input */
  1.1564 +  int npoints_total = 0;   /* total number of points in cluster */
  1.1565 +  int nentries = 0;        /* total number of entries */
  1.1566 +  pgl_newentry *entries;   /* array of pgl_newentry to create pgl_cluster */
  1.1567 +  int entries_buflen = 4;  /* maximum number of elements in entries array */
  1.1568 +  int valid;               /* number of valid chars processed */
  1.1569 +  double lat, lon;         /* latitude and longitude of parsed point */
  1.1570 +  int entrytype;           /* current entry type */
  1.1571 +  int npoints;             /* number of points in current entry */
  1.1572 +  pgl_point *points;       /* array of pgl_point for pgl_newentry */
  1.1573 +  int points_buflen;       /* maximum number of elements in points array */
  1.1574 +  int done;                /* return value of pgl_scan function */
  1.1575 +  pgl_cluster *cluster;    /* created cluster */
  1.1576 +  /* lowercase input */
  1.1577 +  str_lower = psprintf("%s", str);
  1.1578 +  for (strptr=str_lower; *strptr; strptr++) {
  1.1579 +    if (*strptr >= 'A' && *strptr <= 'Z') *strptr += 'a' - 'A';
  1.1580 +  }
  1.1581 +  /* reset reading position to start of (lowercase) string */
  1.1582 +  strptr = str_lower;
  1.1583 +  /* allocate initial buffer for entries */
  1.1584 +  entries = palloc(entries_buflen * sizeof(pgl_newentry));
  1.1585 +  /* parse until end of string */
  1.1586 +  while (strptr[0]) {
  1.1587 +    /* require previous white-space or closing parenthesis before next token */
  1.1588 +    if (strptr != str_lower && !isspace(strptr[-1]) && strptr[-1] != ')') {
  1.1589 +      goto pgl_ecluster_in_error;
  1.1590 +    }
  1.1591 +    /* ignore token "empty" */
  1.1592 +    valid = 0; sscanf(strptr, " empty %n", &valid);
  1.1593 +    if (valid) { strptr += valid; continue; }
  1.1594 +    /* test for "point" token */
  1.1595 +    valid = 0; sscanf(strptr, " point ( %n", &valid);
  1.1596 +    if (valid) {
  1.1597 +      strptr += valid;
  1.1598 +      entrytype = PGL_ENTRY_POINT;
  1.1599 +      goto pgl_ecluster_in_type_ok;
  1.1600 +    }
  1.1601 +    /* test for "path" token */
  1.1602 +    valid = 0; sscanf(strptr, " path ( %n", &valid);
  1.1603 +    if (valid) {
  1.1604 +      strptr += valid;
  1.1605 +      entrytype = PGL_ENTRY_PATH;
  1.1606 +      goto pgl_ecluster_in_type_ok;
  1.1607 +    }
  1.1608 +    /* test for "outline" token */
  1.1609 +    valid = 0; sscanf(strptr, " outline ( %n", &valid);
  1.1610 +    if (valid) {
  1.1611 +      strptr += valid;
  1.1612 +      entrytype = PGL_ENTRY_OUTLINE;
  1.1613 +      goto pgl_ecluster_in_type_ok;
  1.1614 +    }
  1.1615 +    /* test for "polygon" token */
  1.1616 +    valid = 0; sscanf(strptr, " polygon ( %n", &valid);
  1.1617 +    if (valid) {
  1.1618 +      strptr += valid;
  1.1619 +      entrytype = PGL_ENTRY_POLYGON;
  1.1620 +      goto pgl_ecluster_in_type_ok;
  1.1621 +    }
  1.1622 +    /* error if no valid token found */
  1.1623 +    goto pgl_ecluster_in_error;
  1.1624 +    pgl_ecluster_in_type_ok:
  1.1625 +    /* check if pgl_newentry array needs to grow */
  1.1626 +    if (nentries == entries_buflen) {
  1.1627 +      pgl_newentry *newbuf;
  1.1628 +      entries_buflen *= 2;
  1.1629 +      newbuf = palloc(entries_buflen * sizeof(pgl_newentry));
  1.1630 +      memcpy(newbuf, entries, nentries * sizeof(pgl_newentry));
  1.1631 +      pfree(entries);
  1.1632 +      entries = newbuf;
  1.1633 +    }
  1.1634 +    /* reset number of points for current entry */
  1.1635 +    npoints = 0;
  1.1636 +    /* allocate array for points */
  1.1637 +    points_buflen = 4;
  1.1638 +    points = palloc(points_buflen * sizeof(pgl_point));
  1.1639 +    /* parse until closing parenthesis */
  1.1640 +    while (strptr[0] != ')') {
  1.1641 +      /* error on unexpected end of string */
  1.1642 +      if (strptr[0] == 0) goto pgl_ecluster_in_error;
  1.1643 +      /* mark neither latitude nor longitude as read */
  1.1644 +      done = PGL_SCAN_NONE;
  1.1645 +      /* require white-space before second, third, etc. point */
  1.1646 +      if (npoints != 0 && !isspace(strptr[-1])) goto pgl_ecluster_in_error;
  1.1647 +      /* scan latitude (or longitude) */
  1.1648 +      done |= pgl_scan(&strptr, &lat, &lon);
  1.1649 +      /* require white-space before second coordinate */
  1.1650 +      if (strptr != str && !isspace(strptr[-1])) goto pgl_ecluster_in_error;
  1.1651 +      /* scan longitude (or latitude) */
  1.1652 +      done |= pgl_scan(&strptr, &lat, &lon);
  1.1653 +      /* error unless both latitude and longitude were parsed */
  1.1654 +      if (done != PGL_SCAN_LATLON) goto pgl_ecluster_in_error;
  1.1655 +      /* throw error if number of points is too high */
  1.1656 +      if (npoints_total == PGL_CLUSTER_MAXPOINTS) {
  1.1657 +        ereport(ERROR, (
  1.1658 +          errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
  1.1659 +          errmsg(
  1.1660 +            "too many points for ecluster entry (maximum %i)",
  1.1661 +            PGL_CLUSTER_MAXPOINTS
  1.1662 +          )
  1.1663 +        ));
  1.1664 +      }
  1.1665 +      /* check if pgl_point array needs to grow */
  1.1666 +      if (npoints == points_buflen) {
  1.1667 +        pgl_point *newbuf;
  1.1668 +        points_buflen *= 2;
  1.1669 +        newbuf = palloc(points_buflen * sizeof(pgl_point));
  1.1670 +        memcpy(newbuf, points, npoints * sizeof(pgl_point));
  1.1671 +        pfree(points);
  1.1672 +        points = newbuf;
  1.1673 +      }
  1.1674 +      /* append point to pgl_point array (includes checks) */
  1.1675 +      pgl_epoint_set_latlon(&(points[npoints++]), lat, lon);
  1.1676 +      /* increase total number of points */
  1.1677 +      npoints_total++;
  1.1678 +    }
  1.1679 +    /* error if entry has no points */
  1.1680 +    if (!npoints) goto pgl_ecluster_in_error;
  1.1681 +    /* entries with one point are automatically of type "point" */
  1.1682 +    if (npoints == 1) entrytype = PGL_ENTRY_POINT;
  1.1683 +    /* if entries have more than one point */
  1.1684 +    else {
  1.1685 +      /* throw error if entry type is "point" */
  1.1686 +      if (entrytype == PGL_ENTRY_POINT) {
  1.1687 +        ereport(ERROR, (
  1.1688 +          errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
  1.1689 +          errmsg("invalid input syntax for type ecluster (point entry with more than one point)")
  1.1690 +        ));
  1.1691 +      }
  1.1692 +      /* coerce outlines and polygons with more than 2 points to be a path */
  1.1693 +      if (npoints == 2) entrytype = PGL_ENTRY_PATH;
  1.1694 +    }
  1.1695 +    /* append entry to pgl_newentry array */
  1.1696 +    entries[nentries].entrytype = entrytype;
  1.1697 +    entries[nentries].npoints = npoints;
  1.1698 +    entries[nentries].points = points;
  1.1699 +    nentries++;
  1.1700 +    /* consume closing parenthesis */
  1.1701 +    strptr++;
  1.1702 +    /* consume white-space */
  1.1703 +    while (isspace(strptr[0])) strptr++;
  1.1704 +  }
  1.1705 +  /* free lower case string */
  1.1706 +  pfree(str_lower);
  1.1707 +  /* create cluster from pgl_newentry array */
  1.1708 +  cluster = pgl_new_cluster(nentries, entries);
  1.1709 +  /* free pgl_newentry array */
  1.1710 +  for (i=0; i<nentries; i++) pfree(entries[i].points);
  1.1711 +  pfree(entries);
  1.1712 +  /* set bounding circle of cluster and check east/west orientation */
  1.1713 +  if (!pgl_finalize_cluster(cluster)) {
  1.1714 +    ereport(ERROR, (
  1.1715 +      errcode(ERRCODE_DATA_EXCEPTION),
  1.1716 +      errmsg("can not determine east/west orientation for ecluster"),
  1.1717 +      errhint("Ensure that each entry has a longitude span of less than 180 degrees.")
  1.1718 +    ));
  1.1719 +  }
  1.1720 +  /* return cluster */
  1.1721 +  PG_RETURN_POINTER(cluster);
  1.1722 +  /* code to throw error */
  1.1723 +  pgl_ecluster_in_error:
  1.1724 +  ereport(ERROR, (
  1.1725 +    errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
  1.1726 +    errmsg("invalid input syntax for type ecluster: \"%s\"", str)
  1.1727 +  ));
  1.1728 +}
  1.1729 +
  1.1730 +/* convert point ("epoint") to string representation */
  1.1731 +PG_FUNCTION_INFO_V1(pgl_epoint_out);
  1.1732 +Datum pgl_epoint_out(PG_FUNCTION_ARGS) {
  1.1733 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.1734 +  char latstr[PGL_NUMBUFLEN];
  1.1735 +  char lonstr[PGL_NUMBUFLEN];
  1.1736 +  pgl_print_lat(latstr, point->lat);
  1.1737 +  pgl_print_lon(lonstr, point->lon);
  1.1738 +  PG_RETURN_CSTRING(psprintf("%s %s", latstr, lonstr));
  1.1739 +}
  1.1740 +
  1.1741 +/* convert box ("ebox") to string representation */
  1.1742 +PG_FUNCTION_INFO_V1(pgl_ebox_out);
  1.1743 +Datum pgl_ebox_out(PG_FUNCTION_ARGS) {
  1.1744 +  pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
  1.1745 +  double lon_min = box->lon_min;
  1.1746 +  double lon_max = box->lon_max;
  1.1747 +  char lat_min_str[PGL_NUMBUFLEN];
  1.1748 +  char lat_max_str[PGL_NUMBUFLEN];
  1.1749 +  char lon_min_str[PGL_NUMBUFLEN];
  1.1750 +  char lon_max_str[PGL_NUMBUFLEN];
  1.1751 +  /* return string "empty" if box is set to be empty */
  1.1752 +  if (box->lat_min > box->lat_max) PG_RETURN_CSTRING("empty");
  1.1753 +  /* use boundaries exceeding W180 or E180 if 180th meridian is enclosed */
  1.1754 +  /* (required since pgl_box_in orders the longitude boundaries) */
  1.1755 +  if (lon_min > lon_max) {
  1.1756 +    if (lon_min + lon_max >= 0) lon_min -= 360;
  1.1757 +    else lon_max += 360;
  1.1758 +  }
  1.1759 +  /* format and return result */
  1.1760 +  pgl_print_lat(lat_min_str, box->lat_min);
  1.1761 +  pgl_print_lat(lat_max_str, box->lat_max);
  1.1762 +  pgl_print_lon(lon_min_str, lon_min);
  1.1763 +  pgl_print_lon(lon_max_str, lon_max);
  1.1764 +  PG_RETURN_CSTRING(psprintf(
  1.1765 +    "%s %s %s %s",
  1.1766 +    lat_min_str, lon_min_str, lat_max_str, lon_max_str
  1.1767 +  ));
  1.1768 +}
  1.1769 +
  1.1770 +/* convert circle ("ecircle") to string representation */
  1.1771 +PG_FUNCTION_INFO_V1(pgl_ecircle_out);
  1.1772 +Datum pgl_ecircle_out(PG_FUNCTION_ARGS) {
  1.1773 +  pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
  1.1774 +  char latstr[PGL_NUMBUFLEN];
  1.1775 +  char lonstr[PGL_NUMBUFLEN];
  1.1776 +  char radstr[PGL_NUMBUFLEN];
  1.1777 +  pgl_print_lat(latstr, circle->center.lat);
  1.1778 +  pgl_print_lon(lonstr, circle->center.lon);
  1.1779 +  pgl_print_float(radstr, circle->radius);
  1.1780 +  PG_RETURN_CSTRING(psprintf("%s %s %s", latstr, lonstr, radstr));
  1.1781 +}
  1.1782 +
  1.1783 +/* convert cluster ("ecluster") to string representation */
  1.1784 +PG_FUNCTION_INFO_V1(pgl_ecluster_out);
  1.1785 +Datum pgl_ecluster_out(PG_FUNCTION_ARGS) {
  1.1786 +  pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
  1.1787 +  char latstr[PGL_NUMBUFLEN];  /* string buffer for latitude */
  1.1788 +  char lonstr[PGL_NUMBUFLEN];  /* string buffer for longitude */
  1.1789 +  char ***strings;     /* array of array of strings */
  1.1790 +  char *string;        /* string of current token */
  1.1791 +  char *res, *resptr;  /* result and pointer to current write position */
  1.1792 +  size_t reslen = 1;   /* length of result (init with 1 for terminator) */
  1.1793 +  int npoints;         /* number of points of current entry */
  1.1794 +  int i, j;            /* i: entry, j: point in entry */
  1.1795 +  /* handle empty clusters */
  1.1796 +  if (cluster->nentries == 0) {
  1.1797 +    /* free detoasted cluster (if copy) */
  1.1798 +    PG_FREE_IF_COPY(cluster, 0);
  1.1799 +    /* return static result */
  1.1800 +    PG_RETURN_CSTRING("empty");
  1.1801 +  }
  1.1802 +  /* allocate array of array of strings */
  1.1803 +  strings = palloc(cluster->nentries * sizeof(char **));
  1.1804 +  /* iterate over all entries in cluster */
  1.1805 +  for (i=0; i<cluster->nentries; i++) {
  1.1806 +    /* get number of points in entry */
  1.1807 +    npoints = cluster->entries[i].npoints;
  1.1808 +    /* allocate array of strings (one string for each point plus two extra) */
  1.1809 +    strings[i] = palloc((2 + npoints) * sizeof(char *));
  1.1810 +    /* determine opening string */
  1.1811 +    switch (cluster->entries[i].entrytype) {
  1.1812 +      case PGL_ENTRY_POINT:   string = (i==0)?"point ("  :" point (";   break;
  1.1813 +      case PGL_ENTRY_PATH:    string = (i==0)?"path ("   :" path (";    break;
  1.1814 +      case PGL_ENTRY_OUTLINE: string = (i==0)?"outline (":" outline ("; break;
  1.1815 +      case PGL_ENTRY_POLYGON: string = (i==0)?"polygon (":" polygon ("; break;
  1.1816 +      default:                string = (i==0)?"unknown"  :" unknown";
  1.1817 +    }
  1.1818 +    /* use opening string as first string in array */
  1.1819 +    strings[i][0] = string;
  1.1820 +    /* update result length (for allocating result string later) */
  1.1821 +    reslen += strlen(string);
  1.1822 +    /* iterate over all points */
  1.1823 +    for (j=0; j<npoints; j++) {
  1.1824 +      /* create string representation of point */
  1.1825 +      pgl_print_lat(latstr, PGL_ENTRY_POINTS(cluster, i)[j].lat);
  1.1826 +      pgl_print_lon(lonstr, PGL_ENTRY_POINTS(cluster, i)[j].lon);
  1.1827 +      string = psprintf((j == 0) ? "%s %s" : " %s %s", latstr, lonstr);
  1.1828 +      /* copy string pointer to string array */
  1.1829 +      strings[i][j+1] = string;
  1.1830 +      /* update result length (for allocating result string later) */
  1.1831 +      reslen += strlen(string);
  1.1832 +    }
  1.1833 +    /* use closing parenthesis as last string in array */
  1.1834 +    strings[i][npoints+1] = ")";
  1.1835 +    /* update result length (for allocating result string later) */
  1.1836 +    reslen++;
  1.1837 +  }
  1.1838 +  /* allocate result string */
  1.1839 +  res = palloc(reslen);
  1.1840 +  /* set write pointer to begin of result string */
  1.1841 +  resptr = res;
  1.1842 +  /* copy strings into result string */
  1.1843 +  for (i=0; i<cluster->nentries; i++) {
  1.1844 +    npoints = cluster->entries[i].npoints;
  1.1845 +    for (j=0; j<npoints+2; j++) {
  1.1846 +      string = strings[i][j];
  1.1847 +      strcpy(resptr, string);
  1.1848 +      resptr += strlen(string);
  1.1849 +      /* free strings allocated by psprintf */
  1.1850 +      if (j != 0 && j != npoints+1) pfree(string);
  1.1851 +    }
  1.1852 +    /* free array of strings */
  1.1853 +    pfree(strings[i]);
  1.1854 +  }
  1.1855 +  /* free array of array of strings */
  1.1856 +  pfree(strings);
  1.1857 +  /* free detoasted cluster (if copy) */
  1.1858 +  PG_FREE_IF_COPY(cluster, 0);
  1.1859 +  /* return result */
  1.1860 +  PG_RETURN_CSTRING(res);
  1.1861 +}
  1.1862 +
  1.1863 +/* binary input function for point ("epoint") */
  1.1864 +PG_FUNCTION_INFO_V1(pgl_epoint_recv);
  1.1865 +Datum pgl_epoint_recv(PG_FUNCTION_ARGS) {
  1.1866 +  StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
  1.1867 +  pgl_point *point = (pgl_point *)palloc(sizeof(pgl_point));
  1.1868 +  point->lat = pq_getmsgfloat8(buf);
  1.1869 +  point->lon = pq_getmsgfloat8(buf);
  1.1870 +  PG_RETURN_POINTER(point);
  1.1871 +}
  1.1872 +
  1.1873 +/* binary input function for box ("ebox") */
  1.1874 +PG_FUNCTION_INFO_V1(pgl_ebox_recv);
  1.1875 +Datum pgl_ebox_recv(PG_FUNCTION_ARGS) {
  1.1876 +  StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
  1.1877 +  pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
  1.1878 +  box->lat_min = pq_getmsgfloat8(buf);
  1.1879 +  box->lat_max = pq_getmsgfloat8(buf);
  1.1880 +  box->lon_min = pq_getmsgfloat8(buf);
  1.1881 +  box->lon_max = pq_getmsgfloat8(buf);
  1.1882 +  PG_RETURN_POINTER(box);
  1.1883 +}
  1.1884 +
  1.1885 +/* binary input function for circle ("ecircle") */
  1.1886 +PG_FUNCTION_INFO_V1(pgl_ecircle_recv);
  1.1887 +Datum pgl_ecircle_recv(PG_FUNCTION_ARGS) {
  1.1888 +  StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
  1.1889 +  pgl_circle *circle = (pgl_circle *)palloc(sizeof(pgl_circle));
  1.1890 +  circle->center.lat = pq_getmsgfloat8(buf);
  1.1891 +  circle->center.lon = pq_getmsgfloat8(buf);
  1.1892 +  circle->radius = pq_getmsgfloat8(buf);
  1.1893 +  PG_RETURN_POINTER(circle);
  1.1894 +}
  1.1895 +
  1.1896 +/* TODO: binary receive function for cluster */
  1.1897 +
  1.1898 +/* binary output function for point ("epoint") */
  1.1899 +PG_FUNCTION_INFO_V1(pgl_epoint_send);
  1.1900 +Datum pgl_epoint_send(PG_FUNCTION_ARGS) {
  1.1901 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.1902 +  StringInfoData buf;
  1.1903 +  pq_begintypsend(&buf);
  1.1904 +  pq_sendfloat8(&buf, point->lat);
  1.1905 +  pq_sendfloat8(&buf, point->lon);
  1.1906 +  PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
  1.1907 +}
  1.1908 +
  1.1909 +/* binary output function for box ("ebox") */
  1.1910 +PG_FUNCTION_INFO_V1(pgl_ebox_send);
  1.1911 +Datum pgl_ebox_send(PG_FUNCTION_ARGS) {
  1.1912 +  pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
  1.1913 +  StringInfoData buf;
  1.1914 +  pq_begintypsend(&buf);
  1.1915 +  pq_sendfloat8(&buf, box->lat_min);
  1.1916 +  pq_sendfloat8(&buf, box->lat_max);
  1.1917 +  pq_sendfloat8(&buf, box->lon_min);
  1.1918 +  pq_sendfloat8(&buf, box->lon_max);
  1.1919 +  PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
  1.1920 +}
  1.1921 +
  1.1922 +/* binary output function for circle ("ecircle") */
  1.1923 +PG_FUNCTION_INFO_V1(pgl_ecircle_send);
  1.1924 +Datum pgl_ecircle_send(PG_FUNCTION_ARGS) {
  1.1925 +  pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
  1.1926 +  StringInfoData buf;
  1.1927 +  pq_begintypsend(&buf);
  1.1928 +  pq_sendfloat8(&buf, circle->center.lat);
  1.1929 +  pq_sendfloat8(&buf, circle->center.lon);
  1.1930 +  pq_sendfloat8(&buf, circle->radius);
  1.1931 +  PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
  1.1932 +}
  1.1933 +
  1.1934 +/* TODO: binary send functions for cluster */
  1.1935 +
  1.1936 +/* cast point ("epoint") to box ("ebox") */
  1.1937 +PG_FUNCTION_INFO_V1(pgl_epoint_to_ebox);
  1.1938 +Datum pgl_epoint_to_ebox(PG_FUNCTION_ARGS) {
  1.1939 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.1940 +  pgl_box *box = palloc(sizeof(pgl_box));
  1.1941 +  box->lat_min = point->lat;
  1.1942 +  box->lat_max = point->lat;
  1.1943 +  box->lon_min = point->lon;
  1.1944 +  box->lon_max = point->lon;
  1.1945 +  PG_RETURN_POINTER(box);
  1.1946 +}
  1.1947 +
  1.1948 +/* cast point ("epoint") to circle ("ecircle") */
  1.1949 +PG_FUNCTION_INFO_V1(pgl_epoint_to_ecircle);
  1.1950 +Datum pgl_epoint_to_ecircle(PG_FUNCTION_ARGS) {
  1.1951 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.1952 +  pgl_circle *circle = palloc(sizeof(pgl_box));
  1.1953 +  circle->center = *point;
  1.1954 +  circle->radius = 0;
  1.1955 +  PG_RETURN_POINTER(circle);
  1.1956 +}
  1.1957 +
  1.1958 +/* cast point ("epoint") to cluster ("ecluster") */
  1.1959 +PG_FUNCTION_INFO_V1(pgl_epoint_to_ecluster);
  1.1960 +Datum pgl_epoint_to_ecluster(PG_FUNCTION_ARGS) {
  1.1961 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.1962 +  pgl_newentry entry;
  1.1963 +  entry.entrytype = PGL_ENTRY_POINT;
  1.1964 +  entry.npoints = 1;
  1.1965 +  entry.points = point;
  1.1966 +  PG_RETURN_POINTER(pgl_new_cluster(1, &entry));
  1.1967 +}
  1.1968 +
  1.1969 +/* cast box ("ebox") to cluster ("ecluster") */
  1.1970 +#define pgl_ebox_to_ecluster_macro(i, a, b) \
  1.1971 +  entries[i].entrytype = PGL_ENTRY_POLYGON; \
  1.1972 +  entries[i].npoints = 4; \
  1.1973 +  entries[i].points = points[i]; \
  1.1974 +  points[i][0].lat = box->lat_min; \
  1.1975 +  points[i][0].lon = (a); \
  1.1976 +  points[i][1].lat = box->lat_min; \
  1.1977 +  points[i][1].lon = (b); \
  1.1978 +  points[i][2].lat = box->lat_max; \
  1.1979 +  points[i][2].lon = (b); \
  1.1980 +  points[i][3].lat = box->lat_max; \
  1.1981 +  points[i][3].lon = (a);
  1.1982 +PG_FUNCTION_INFO_V1(pgl_ebox_to_ecluster);
  1.1983 +Datum pgl_ebox_to_ecluster(PG_FUNCTION_ARGS) {
  1.1984 +  pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
  1.1985 +  double lon, dlon;
  1.1986 +  int nentries;
  1.1987 +  pgl_newentry entries[3];
  1.1988 +  pgl_point points[3][4];
  1.1989 +  if (box->lat_min > box->lat_max) {
  1.1990 +    nentries = 0;
  1.1991 +  } else if (box->lon_min > box->lon_max) {
  1.1992 +    if (box->lon_min < 0) {
  1.1993 +      lon = pgl_round((box->lon_min + 180) / 2.0);
  1.1994 +      nentries = 3;
  1.1995 +      pgl_ebox_to_ecluster_macro(0, box->lon_min, lon);
  1.1996 +      pgl_ebox_to_ecluster_macro(1, lon, 180);
  1.1997 +      pgl_ebox_to_ecluster_macro(2, -180, box->lon_max);
  1.1998 +    } else if (box->lon_max > 0) {
  1.1999 +      lon = pgl_round((box->lon_max - 180) / 2.0);
  1.2000 +      nentries = 3;
  1.2001 +      pgl_ebox_to_ecluster_macro(0, box->lon_min, 180);
  1.2002 +      pgl_ebox_to_ecluster_macro(1, -180, lon);
  1.2003 +      pgl_ebox_to_ecluster_macro(2, lon, box->lon_max);
  1.2004 +    } else {
  1.2005 +      nentries = 2;
  1.2006 +      pgl_ebox_to_ecluster_macro(0, box->lon_min, 180);
  1.2007 +      pgl_ebox_to_ecluster_macro(1, -180, box->lon_max);
  1.2008 +    }
  1.2009 +  } else {
  1.2010 +    dlon = pgl_round(box->lon_max - box->lon_min);
  1.2011 +    if (dlon < 180) {
  1.2012 +      nentries = 1;
  1.2013 +      pgl_ebox_to_ecluster_macro(0, box->lon_min, box->lon_max);
  1.2014 +    } else {
  1.2015 +      lon = pgl_round((box->lon_min + box->lon_max) / 2.0);
  1.2016 +      if (
  1.2017 +        pgl_round(lon - box->lon_min) < 180 &&
  1.2018 +        pgl_round(box->lon_max - lon) < 180
  1.2019 +      ) {
  1.2020 +        nentries = 2;
  1.2021 +        pgl_ebox_to_ecluster_macro(0, box->lon_min, lon);
  1.2022 +        pgl_ebox_to_ecluster_macro(1, lon, box->lon_max);
  1.2023 +      } else {
  1.2024 +        nentries = 3;
  1.2025 +        pgl_ebox_to_ecluster_macro(0, box->lon_min, -60);
  1.2026 +        pgl_ebox_to_ecluster_macro(1, -60, 60);
  1.2027 +        pgl_ebox_to_ecluster_macro(2, 60, box->lon_max);
  1.2028 +      }
  1.2029 +    }
  1.2030 +  }
  1.2031 +  PG_RETURN_POINTER(pgl_new_cluster(nentries, entries));
  1.2032 +}
  1.2033 +
  1.2034 +/* extract latitude from point ("epoint") */
  1.2035 +PG_FUNCTION_INFO_V1(pgl_epoint_lat);
  1.2036 +Datum pgl_epoint_lat(PG_FUNCTION_ARGS) {
  1.2037 +  PG_RETURN_FLOAT8(((pgl_point *)PG_GETARG_POINTER(0))->lat);
  1.2038 +}
  1.2039 +
  1.2040 +/* extract longitude from point ("epoint") */
  1.2041 +PG_FUNCTION_INFO_V1(pgl_epoint_lon);
  1.2042 +Datum pgl_epoint_lon(PG_FUNCTION_ARGS) {
  1.2043 +  PG_RETURN_FLOAT8(((pgl_point *)PG_GETARG_POINTER(0))->lon);
  1.2044 +}
  1.2045 +
  1.2046 +/* extract minimum latitude from box ("ebox") */
  1.2047 +PG_FUNCTION_INFO_V1(pgl_ebox_lat_min);
  1.2048 +Datum pgl_ebox_lat_min(PG_FUNCTION_ARGS) {
  1.2049 +  PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lat_min);
  1.2050 +}
  1.2051 +
  1.2052 +/* extract maximum latitude from box ("ebox") */
  1.2053 +PG_FUNCTION_INFO_V1(pgl_ebox_lat_max);
  1.2054 +Datum pgl_ebox_lat_max(PG_FUNCTION_ARGS) {
  1.2055 +  PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lat_max);
  1.2056 +}
  1.2057 +
  1.2058 +/* extract minimum longitude from box ("ebox") */
  1.2059 +PG_FUNCTION_INFO_V1(pgl_ebox_lon_min);
  1.2060 +Datum pgl_ebox_lon_min(PG_FUNCTION_ARGS) {
  1.2061 +  PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lon_min);
  1.2062 +}
  1.2063 +
  1.2064 +/* extract maximum longitude from box ("ebox") */
  1.2065 +PG_FUNCTION_INFO_V1(pgl_ebox_lon_max);
  1.2066 +Datum pgl_ebox_lon_max(PG_FUNCTION_ARGS) {
  1.2067 +  PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lon_max);
  1.2068 +}
  1.2069 +
  1.2070 +/* extract center point from circle ("ecircle") */
  1.2071 +PG_FUNCTION_INFO_V1(pgl_ecircle_center);
  1.2072 +Datum pgl_ecircle_center(PG_FUNCTION_ARGS) {
  1.2073 +  PG_RETURN_POINTER(&(((pgl_circle *)PG_GETARG_POINTER(0))->center));
  1.2074 +}
  1.2075 +
  1.2076 +/* extract radius from circle ("ecircle") */
  1.2077 +PG_FUNCTION_INFO_V1(pgl_ecircle_radius);
  1.2078 +Datum pgl_ecircle_radius(PG_FUNCTION_ARGS) {
  1.2079 +  PG_RETURN_FLOAT8(((pgl_circle *)PG_GETARG_POINTER(0))->radius);
  1.2080 +}
  1.2081 +
  1.2082 +/* check if point is inside box (overlap operator "&&") in SQL */
  1.2083 +PG_FUNCTION_INFO_V1(pgl_epoint_ebox_overlap);
  1.2084 +Datum pgl_epoint_ebox_overlap(PG_FUNCTION_ARGS) {
  1.2085 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.2086 +  pgl_box *box = (pgl_box *)PG_GETARG_POINTER(1);
  1.2087 +  PG_RETURN_BOOL(pgl_point_in_box(point, box));
  1.2088 +}
  1.2089 +
  1.2090 +/* check if point is inside circle (overlap operator "&&") in SQL */
  1.2091 +PG_FUNCTION_INFO_V1(pgl_epoint_ecircle_overlap);
  1.2092 +Datum pgl_epoint_ecircle_overlap(PG_FUNCTION_ARGS) {
  1.2093 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.2094 +  pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(1);
  1.2095 +  PG_RETURN_BOOL(
  1.2096 +    pgl_distance(
  1.2097 +      point->lat, point->lon,
  1.2098 +      circle->center.lat, circle->center.lon
  1.2099 +    ) <= circle->radius
  1.2100 +  );
  1.2101 +}
  1.2102 +
  1.2103 +/* check if point is inside cluster (overlap operator "&&") in SQL */
  1.2104 +PG_FUNCTION_INFO_V1(pgl_epoint_ecluster_overlap);
  1.2105 +Datum pgl_epoint_ecluster_overlap(PG_FUNCTION_ARGS) {
  1.2106 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.2107 +  pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
  1.2108 +  bool retval = pgl_point_in_cluster(point, cluster);
  1.2109 +  PG_FREE_IF_COPY(cluster, 1);
  1.2110 +  PG_RETURN_BOOL(retval);
  1.2111 +}
  1.2112 +
  1.2113 +/* check if two boxes overlap (overlap operator "&&") in SQL */
  1.2114 +PG_FUNCTION_INFO_V1(pgl_ebox_overlap);
  1.2115 +Datum pgl_ebox_overlap(PG_FUNCTION_ARGS) {
  1.2116 +  pgl_box *box1 = (pgl_box *)PG_GETARG_POINTER(0);
  1.2117 +  pgl_box *box2 = (pgl_box *)PG_GETARG_POINTER(1);
  1.2118 +  PG_RETURN_BOOL(pgl_boxes_overlap(box1, box2));
  1.2119 +}
  1.2120 +
  1.2121 +/* check if two circles overlap (overlap operator "&&") in SQL */
  1.2122 +PG_FUNCTION_INFO_V1(pgl_ecircle_overlap);
  1.2123 +Datum pgl_ecircle_overlap(PG_FUNCTION_ARGS) {
  1.2124 +  pgl_circle *circle1 = (pgl_circle *)PG_GETARG_POINTER(0);
  1.2125 +  pgl_circle *circle2 = (pgl_circle *)PG_GETARG_POINTER(1);
  1.2126 +  PG_RETURN_BOOL(
  1.2127 +    pgl_distance(
  1.2128 +      circle1->center.lat, circle1->center.lon,
  1.2129 +      circle2->center.lat, circle2->center.lon
  1.2130 +    ) <= circle1->radius + circle2->radius
  1.2131 +  );
  1.2132 +}
  1.2133 +
  1.2134 +/* check if circle and cluster overlap (overlap operator "&&") in SQL */
  1.2135 +PG_FUNCTION_INFO_V1(pgl_ecircle_ecluster_overlap);
  1.2136 +Datum pgl_ecircle_ecluster_overlap(PG_FUNCTION_ARGS) {
  1.2137 +  pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
  1.2138 +  pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
  1.2139 +  bool retval = (
  1.2140 +    pgl_point_cluster_distance(&(circle->center), cluster) <= circle->radius
  1.2141 +  );
  1.2142 +  PG_FREE_IF_COPY(cluster, 1);
  1.2143 +  PG_RETURN_BOOL(retval);
  1.2144 +}
  1.2145 +
  1.2146 +/* calculate distance between two points ("<->" operator) in SQL */
  1.2147 +PG_FUNCTION_INFO_V1(pgl_epoint_distance);
  1.2148 +Datum pgl_epoint_distance(PG_FUNCTION_ARGS) {
  1.2149 +  pgl_point *point1 = (pgl_point *)PG_GETARG_POINTER(0);
  1.2150 +  pgl_point *point2 = (pgl_point *)PG_GETARG_POINTER(1);
  1.2151 +  PG_RETURN_FLOAT8(pgl_distance(
  1.2152 +    point1->lat, point1->lon, point2->lat, point2->lon
  1.2153 +  ));
  1.2154 +}
  1.2155 +
  1.2156 +/* calculate point to circle distance ("<->" operator) in SQL */
  1.2157 +PG_FUNCTION_INFO_V1(pgl_epoint_ecircle_distance);
  1.2158 +Datum pgl_epoint_ecircle_distance(PG_FUNCTION_ARGS) {
  1.2159 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.2160 +  pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(1);
  1.2161 +  double distance = pgl_distance(
  1.2162 +    point->lat, point->lon, circle->center.lat, circle->center.lon
  1.2163 +  ) - circle->radius;
  1.2164 +  PG_RETURN_FLOAT8((distance <= 0) ? 0 : distance);
  1.2165 +}
  1.2166 +
  1.2167 +/* calculate point to cluster distance ("<->" operator) in SQL */
  1.2168 +PG_FUNCTION_INFO_V1(pgl_epoint_ecluster_distance);
  1.2169 +Datum pgl_epoint_ecluster_distance(PG_FUNCTION_ARGS) {
  1.2170 +  pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
  1.2171 +  pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
  1.2172 +  double distance = pgl_point_cluster_distance(point, cluster);
  1.2173 +  PG_FREE_IF_COPY(cluster, 1);
  1.2174 +  PG_RETURN_FLOAT8(distance);
  1.2175 +}
  1.2176 +
  1.2177 +/* calculate distance between two circles ("<->" operator) in SQL */
  1.2178 +PG_FUNCTION_INFO_V1(pgl_ecircle_distance);
  1.2179 +Datum pgl_ecircle_distance(PG_FUNCTION_ARGS) {
  1.2180 +  pgl_circle *circle1 = (pgl_circle *)PG_GETARG_POINTER(0);
  1.2181 +  pgl_circle *circle2 = (pgl_circle *)PG_GETARG_POINTER(1);
  1.2182 +  double distance = pgl_distance(
  1.2183 +    circle1->center.lat, circle1->center.lon,
  1.2184 +    circle2->center.lat, circle2->center.lon
  1.2185 +  ) - (circle1->radius + circle2->radius);
  1.2186 +  PG_RETURN_FLOAT8((distance <= 0) ? 0 : distance);
  1.2187 +}
  1.2188 +
  1.2189 +/* calculate circle to cluster distance ("<->" operator) in SQL */
  1.2190 +PG_FUNCTION_INFO_V1(pgl_ecircle_ecluster_distance);
  1.2191 +Datum pgl_ecircle_ecluster_distance(PG_FUNCTION_ARGS) {
  1.2192 +  pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
  1.2193 +  pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
  1.2194 +  double distance = (
  1.2195 +    pgl_point_cluster_distance(&(circle->center), cluster) - circle->radius
  1.2196 +  );
  1.2197 +  PG_FREE_IF_COPY(cluster, 1);
  1.2198 +  PG_RETURN_FLOAT8((distance <= 0) ? 0 : distance);
  1.2199 +}
  1.2200 +
  1.2201 +
  1.2202 +/*-----------------------------------------------------------*
  1.2203 + *  B-tree comparison operators and index support functions  *
  1.2204 + *-----------------------------------------------------------*/
  1.2205 +
  1.2206 +/* macro for a B-tree operator (without detoasting) */
  1.2207 +#define PGL_BTREE_OPER(func, type, cmpfunc, oper) \
  1.2208 +  PG_FUNCTION_INFO_V1(func); \
  1.2209 +  Datum func(PG_FUNCTION_ARGS) { \
  1.2210 +    type *a = (type *)PG_GETARG_POINTER(0); \
  1.2211 +    type *b = (type *)PG_GETARG_POINTER(1); \
  1.2212 +    PG_RETURN_BOOL(cmpfunc(a, b) oper 0); \
  1.2213 +  }
  1.2214 +
  1.2215 +/* macro for a B-tree comparison function (without detoasting) */
  1.2216 +#define PGL_BTREE_CMP(func, type, cmpfunc) \
  1.2217 +  PG_FUNCTION_INFO_V1(func); \
  1.2218 +  Datum func(PG_FUNCTION_ARGS) { \
  1.2219 +    type *a = (type *)PG_GETARG_POINTER(0); \
  1.2220 +    type *b = (type *)PG_GETARG_POINTER(1); \
  1.2221 +    PG_RETURN_INT32(cmpfunc(a, b)); \
  1.2222 +  }
  1.2223 +
  1.2224 +/* macro for a B-tree operator (with detoasting) */
  1.2225 +#define PGL_BTREE_OPER_DETOAST(func, type, cmpfunc, oper) \
  1.2226 +  PG_FUNCTION_INFO_V1(func); \
  1.2227 +  Datum func(PG_FUNCTION_ARGS) { \
  1.2228 +    bool res; \
  1.2229 +    type *a = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); \
  1.2230 +    type *b = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); \
  1.2231 +    res = cmpfunc(a, b) oper 0; \
  1.2232 +    PG_FREE_IF_COPY(a, 0); \
  1.2233 +    PG_FREE_IF_COPY(b, 1); \
  1.2234 +    PG_RETURN_BOOL(res); \
  1.2235 +  }
  1.2236 +
  1.2237 +/* macro for a B-tree comparison function (with detoasting) */
  1.2238 +#define PGL_BTREE_CMP_DETOAST(func, type, cmpfunc) \
  1.2239 +  PG_FUNCTION_INFO_V1(func); \
  1.2240 +  Datum func(PG_FUNCTION_ARGS) { \
  1.2241 +    int32_t res; \
  1.2242 +    type *a = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); \
  1.2243 +    type *b = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); \
  1.2244 +    res = cmpfunc(a, b); \
  1.2245 +    PG_FREE_IF_COPY(a, 0); \
  1.2246 +    PG_FREE_IF_COPY(b, 1); \
  1.2247 +    PG_RETURN_INT32(res); \
  1.2248 +  }
  1.2249 +
  1.2250 +/* B-tree operators and comparison function for point */
  1.2251 +PGL_BTREE_OPER(pgl_btree_epoint_lt, pgl_point, pgl_point_cmp, <)
  1.2252 +PGL_BTREE_OPER(pgl_btree_epoint_le, pgl_point, pgl_point_cmp, <=)
  1.2253 +PGL_BTREE_OPER(pgl_btree_epoint_eq, pgl_point, pgl_point_cmp, ==)
  1.2254 +PGL_BTREE_OPER(pgl_btree_epoint_ne, pgl_point, pgl_point_cmp, !=)
  1.2255 +PGL_BTREE_OPER(pgl_btree_epoint_ge, pgl_point, pgl_point_cmp, >=)
  1.2256 +PGL_BTREE_OPER(pgl_btree_epoint_gt, pgl_point, pgl_point_cmp, >)
  1.2257 +PGL_BTREE_CMP(pgl_btree_epoint_cmp, pgl_point, pgl_point_cmp)
  1.2258 +
  1.2259 +/* B-tree operators and comparison function for box */
  1.2260 +PGL_BTREE_OPER(pgl_btree_ebox_lt, pgl_box, pgl_box_cmp, <)
  1.2261 +PGL_BTREE_OPER(pgl_btree_ebox_le, pgl_box, pgl_box_cmp, <=)
  1.2262 +PGL_BTREE_OPER(pgl_btree_ebox_eq, pgl_box, pgl_box_cmp, ==)
  1.2263 +PGL_BTREE_OPER(pgl_btree_ebox_ne, pgl_box, pgl_box_cmp, !=)
  1.2264 +PGL_BTREE_OPER(pgl_btree_ebox_ge, pgl_box, pgl_box_cmp, >=)
  1.2265 +PGL_BTREE_OPER(pgl_btree_ebox_gt, pgl_box, pgl_box_cmp, >)
  1.2266 +PGL_BTREE_CMP(pgl_btree_ebox_cmp, pgl_box, pgl_box_cmp)
  1.2267 +
  1.2268 +/* B-tree operators and comparison function for circle */
  1.2269 +PGL_BTREE_OPER(pgl_btree_ecircle_lt, pgl_circle, pgl_circle_cmp, <)
  1.2270 +PGL_BTREE_OPER(pgl_btree_ecircle_le, pgl_circle, pgl_circle_cmp, <=)
  1.2271 +PGL_BTREE_OPER(pgl_btree_ecircle_eq, pgl_circle, pgl_circle_cmp, ==)
  1.2272 +PGL_BTREE_OPER(pgl_btree_ecircle_ne, pgl_circle, pgl_circle_cmp, !=)
  1.2273 +PGL_BTREE_OPER(pgl_btree_ecircle_ge, pgl_circle, pgl_circle_cmp, >=)
  1.2274 +PGL_BTREE_OPER(pgl_btree_ecircle_gt, pgl_circle, pgl_circle_cmp, >)
  1.2275 +PGL_BTREE_CMP(pgl_btree_ecircle_cmp, pgl_circle, pgl_circle_cmp)
  1.2276 +
  1.2277 +
  1.2278 +/*--------------------------------*
  1.2279 + *  GiST index support functions  *
  1.2280 + *--------------------------------*/
  1.2281 +
  1.2282 +/* GiST "consistent" support function */
  1.2283 +PG_FUNCTION_INFO_V1(pgl_gist_consistent);
  1.2284 +Datum pgl_gist_consistent(PG_FUNCTION_ARGS) {
  1.2285 +  GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  1.2286 +  pgl_keyptr key = (pgl_keyptr)DatumGetPointer(entry->key);
  1.2287 +  StrategyNumber strategy = (StrategyNumber)PG_GETARG_UINT16(2);
  1.2288 +  bool *recheck = (bool *)PG_GETARG_POINTER(4);
  1.2289 +  /* demand recheck because index and query methods are lossy */
  1.2290 +  *recheck = true;
  1.2291 +  /* strategy number 11: equality of two points */
  1.2292 +  if (strategy == 11) {
  1.2293 +    /* query datum is another point */
  1.2294 +    pgl_point *query = (pgl_point *)PG_GETARG_POINTER(1);
  1.2295 +    /* convert other point to key */
  1.2296 +    pgl_pointkey querykey;
  1.2297 +    pgl_point_to_key(query, querykey);
  1.2298 +    /* return true if both keys overlap */
  1.2299 +    PG_RETURN_BOOL(pgl_keys_overlap(key, querykey));
  1.2300 +  }
  1.2301 +  /* strategy number 13: equality of two circles */
  1.2302 +  if (strategy == 13) {
  1.2303 +    /* query datum is another circle */
  1.2304 +    pgl_circle *query = (pgl_circle *)PG_GETARG_POINTER(1);
  1.2305 +    /* convert other circle to key */
  1.2306 +    pgl_areakey querykey;
  1.2307 +    pgl_circle_to_key(query, querykey);
  1.2308 +    /* return true if both keys overlap */
  1.2309 +    PG_RETURN_BOOL(pgl_keys_overlap(key, querykey));
  1.2310 +  }
  1.2311 +  /* for all remaining strategies, keys on empty objects produce no match */
  1.2312 +  /* (check necessary because query radius may be infinite) */
  1.2313 +  if (PGL_KEY_IS_EMPTY(key)) PG_RETURN_BOOL(false);
  1.2314 +  /* strategy number 21: overlapping with point */
  1.2315 +  if (strategy == 21) {
  1.2316 +    /* query datum is a point */
  1.2317 +    pgl_point *query = (pgl_point *)PG_GETARG_POINTER(1);
  1.2318 +    /* return true if estimated distance (allowed to be smaller than real
  1.2319 +       distance) between index key and point is zero */
  1.2320 +    PG_RETURN_BOOL(pgl_estimate_key_distance(key, query) == 0);
  1.2321 +  }
  1.2322 +  /* strategy number 22: (point) overlapping with box */
  1.2323 +  if (strategy == 22) {
  1.2324 +    /* query datum is a box */
  1.2325 +    pgl_box *query = (pgl_box *)PG_GETARG_POINTER(1);
  1.2326 +    /* determine bounding box of indexed key */
  1.2327 +    pgl_box keybox;
  1.2328 +    pgl_key_to_box(key, &keybox);
  1.2329 +    /* return true if query box overlaps with bounding box of indexed key */
  1.2330 +    PG_RETURN_BOOL(pgl_boxes_overlap(query, &keybox));
  1.2331 +  }
  1.2332 +  /* strategy number 23: overlapping with circle */
  1.2333 +  if (strategy == 23) {
  1.2334 +    /* query datum is a circle */
  1.2335 +    pgl_circle *query = (pgl_circle *)PG_GETARG_POINTER(1);
  1.2336 +    /* return true if estimated distance (allowed to be smaller than real
  1.2337 +       distance) between index key and circle center is smaller than radius */
  1.2338 +    PG_RETURN_BOOL(
  1.2339 +      pgl_estimate_key_distance(key, &(query->center)) <= query->radius
  1.2340 +    );
  1.2341 +  }
  1.2342 +  /* strategy number 24: overlapping with cluster */
  1.2343 +  if (strategy == 24) {
  1.2344 +    bool retval;  /* return value */
  1.2345 +    /* query datum is a cluster */
  1.2346 +    pgl_cluster *query = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
  1.2347 +    /* return true if estimated distance (allowed to be smaller than real
  1.2348 +       distance) between index key and circle center is smaller than radius */
  1.2349 +    retval = (
  1.2350 +      pgl_estimate_key_distance(key, &(query->bounding.center)) <=
  1.2351 +      query->bounding.radius
  1.2352 +    );
  1.2353 +    PG_FREE_IF_COPY(query, 1);  /* free detoasted cluster (if copy) */
  1.2354 +    PG_RETURN_BOOL(retval);
  1.2355 +  }
  1.2356 +  /* throw error for any unknown strategy number */
  1.2357 +  elog(ERROR, "unrecognized strategy number: %d", strategy);
  1.2358 +}
  1.2359 +
  1.2360 +/* GiST "union" support function */
  1.2361 +PG_FUNCTION_INFO_V1(pgl_gist_union);
  1.2362 +Datum pgl_gist_union(PG_FUNCTION_ARGS) {
  1.2363 +  GistEntryVector *entryvec = (GistEntryVector *)PG_GETARG_POINTER(0);
  1.2364 +  pgl_keyptr out;  /* return value (to be palloc'ed) */
  1.2365 +  int i;
  1.2366 +  /* determine key size */
  1.2367 +  size_t keysize = PGL_KEY_IS_AREAKEY(
  1.2368 +    (pgl_keyptr)DatumGetPointer(entryvec->vector[0].key)
  1.2369 +  ) ? sizeof (pgl_areakey) : sizeof(pgl_pointkey);
  1.2370 +  /* begin with first key as result */
  1.2371 +  out = palloc(keysize);
  1.2372 +  memcpy(out, (pgl_keyptr)DatumGetPointer(entryvec->vector[0].key), keysize);
  1.2373 +  /* unite current result with second, third, etc. key */
  1.2374 +  for (i=1; i<entryvec->n; i++) {
  1.2375 +    pgl_unite_keys(out, (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key));
  1.2376 +  }
  1.2377 +  /* return result */
  1.2378 +  PG_RETURN_POINTER(out);
  1.2379 +}
  1.2380 +
  1.2381 +/* GiST "compress" support function for indicis on points */
  1.2382 +PG_FUNCTION_INFO_V1(pgl_gist_compress_epoint);
  1.2383 +Datum pgl_gist_compress_epoint(PG_FUNCTION_ARGS) {
  1.2384 +  GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  1.2385 +  GISTENTRY *retval;  /* return value (to be palloc'ed unless set to entry) */
  1.2386 +  /* only transform new leaves */
  1.2387 +  if (entry->leafkey) {
  1.2388 +    /* get point to be transformed */
  1.2389 +    pgl_point *point = (pgl_point *)DatumGetPointer(entry->key);
  1.2390 +    /* allocate memory for key */
  1.2391 +    pgl_keyptr key = palloc(sizeof(pgl_pointkey));
  1.2392 +    /* transform point to key */
  1.2393 +    pgl_point_to_key(point, key);
  1.2394 +    /* create new GISTENTRY structure as return value */
  1.2395 +    retval = palloc(sizeof(GISTENTRY));
  1.2396 +    gistentryinit(
  1.2397 +      *retval, PointerGetDatum(key),
  1.2398 +      entry->rel, entry->page, entry->offset, FALSE
  1.2399 +    );
  1.2400 +  } else {
  1.2401 +    /* inner nodes have already been transformed */
  1.2402 +    retval = entry;
  1.2403 +  }
  1.2404 +  /* return pointer to old or new GISTENTRY structure */
  1.2405 +  PG_RETURN_POINTER(retval);
  1.2406 +}
  1.2407 +
  1.2408 +/* GiST "compress" support function for indicis on circles */
  1.2409 +PG_FUNCTION_INFO_V1(pgl_gist_compress_ecircle);
  1.2410 +Datum pgl_gist_compress_ecircle(PG_FUNCTION_ARGS) {
  1.2411 +  GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  1.2412 +  GISTENTRY *retval;  /* return value (to be palloc'ed unless set to entry) */
  1.2413 +  /* only transform new leaves */
  1.2414 +  if (entry->leafkey) {
  1.2415 +    /* get circle to be transformed */
  1.2416 +    pgl_circle *circle = (pgl_circle *)DatumGetPointer(entry->key);
  1.2417 +    /* allocate memory for key */
  1.2418 +    pgl_keyptr key = palloc(sizeof(pgl_areakey));
  1.2419 +    /* transform circle to key */
  1.2420 +    pgl_circle_to_key(circle, key);
  1.2421 +    /* create new GISTENTRY structure as return value */
  1.2422 +    retval = palloc(sizeof(GISTENTRY));
  1.2423 +    gistentryinit(
  1.2424 +      *retval, PointerGetDatum(key),
  1.2425 +      entry->rel, entry->page, entry->offset, FALSE
  1.2426 +    );
  1.2427 +  } else {
  1.2428 +    /* inner nodes have already been transformed */
  1.2429 +    retval = entry;
  1.2430 +  }
  1.2431 +  /* return pointer to old or new GISTENTRY structure */
  1.2432 +  PG_RETURN_POINTER(retval);
  1.2433 +}
  1.2434 +
  1.2435 +/* GiST "compress" support function for indices on clusters */
  1.2436 +PG_FUNCTION_INFO_V1(pgl_gist_compress_ecluster);
  1.2437 +Datum pgl_gist_compress_ecluster(PG_FUNCTION_ARGS) {
  1.2438 +  GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  1.2439 +  GISTENTRY *retval;  /* return value (to be palloc'ed unless set to entry) */
  1.2440 +  /* only transform new leaves */
  1.2441 +  if (entry->leafkey) {
  1.2442 +    /* get cluster to be transformed (detoasting necessary!) */
  1.2443 +    pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(entry->key);
  1.2444 +    /* allocate memory for key */
  1.2445 +    pgl_keyptr key = palloc(sizeof(pgl_areakey));
  1.2446 +    /* transform cluster to key */
  1.2447 +    pgl_circle_to_key(&(cluster->bounding), key);
  1.2448 +    /* create new GISTENTRY structure as return value */
  1.2449 +    retval = palloc(sizeof(GISTENTRY));
  1.2450 +    gistentryinit(
  1.2451 +      *retval, PointerGetDatum(key),
  1.2452 +      entry->rel, entry->page, entry->offset, FALSE
  1.2453 +    );
  1.2454 +    /* free detoasted datum */
  1.2455 +    if ((void *)cluster != (void *)DatumGetPointer(entry->key)) pfree(cluster);
  1.2456 +  } else {
  1.2457 +    /* inner nodes have already been transformed */
  1.2458 +    retval = entry;
  1.2459 +  }
  1.2460 +  /* return pointer to old or new GISTENTRY structure */
  1.2461 +  PG_RETURN_POINTER(retval);
  1.2462 +}
  1.2463 +
  1.2464 +/* GiST "decompress" support function for indices */
  1.2465 +PG_FUNCTION_INFO_V1(pgl_gist_decompress);
  1.2466 +Datum pgl_gist_decompress(PG_FUNCTION_ARGS) {
  1.2467 +  /* return passed pointer without transformation */
  1.2468 +  PG_RETURN_POINTER(PG_GETARG_POINTER(0));
  1.2469 +}
  1.2470 +
  1.2471 +/* GiST "penalty" support function */
  1.2472 +PG_FUNCTION_INFO_V1(pgl_gist_penalty);
  1.2473 +Datum pgl_gist_penalty(PG_FUNCTION_ARGS) {
  1.2474 +  GISTENTRY *origentry = (GISTENTRY *)PG_GETARG_POINTER(0);
  1.2475 +  GISTENTRY *newentry = (GISTENTRY *)PG_GETARG_POINTER(1);
  1.2476 +  float *penalty = (float *)PG_GETARG_POINTER(2);
  1.2477 +  /* get original key and key to insert */
  1.2478 +  pgl_keyptr orig = (pgl_keyptr)DatumGetPointer(origentry->key);
  1.2479 +  pgl_keyptr new = (pgl_keyptr)DatumGetPointer(newentry->key);
  1.2480 +  /* copy original key */
  1.2481 +  union { pgl_pointkey pointkey; pgl_areakey areakey; } union_key;
  1.2482 +  if (PGL_KEY_IS_AREAKEY(orig)) {
  1.2483 +    memcpy(union_key.areakey, orig, sizeof(union_key.areakey));
  1.2484 +  } else {
  1.2485 +    memcpy(union_key.pointkey, orig, sizeof(union_key.pointkey));
  1.2486 +  }
  1.2487 +  /* calculate union of both keys */
  1.2488 +  pgl_unite_keys((pgl_keyptr)&union_key, new);
  1.2489 +  /* penalty equal to reduction of key length (logarithm of added area) */
  1.2490 +  /* (return value by setting referenced value and returning pointer) */
  1.2491 +  *penalty = (
  1.2492 +    PGL_KEY_NODEDEPTH(orig) - PGL_KEY_NODEDEPTH((pgl_keyptr)&union_key)
  1.2493 +  );
  1.2494 +  PG_RETURN_POINTER(penalty);
  1.2495 +}
  1.2496 +
  1.2497 +/* GiST "picksplit" support function */
  1.2498 +PG_FUNCTION_INFO_V1(pgl_gist_picksplit);
  1.2499 +Datum pgl_gist_picksplit(PG_FUNCTION_ARGS) {
  1.2500 +  GistEntryVector *entryvec = (GistEntryVector *)PG_GETARG_POINTER(0);
  1.2501 +  GIST_SPLITVEC *v = (GIST_SPLITVEC *)PG_GETARG_POINTER(1);
  1.2502 +  OffsetNumber i;  /* between FirstOffsetNumber and entryvec->n (inclusive) */
  1.2503 +  union {
  1.2504 +    pgl_pointkey pointkey;
  1.2505 +    pgl_areakey areakey;
  1.2506 +  } union_all;  /* union of all keys (to be calculated from scratch)
  1.2507 +                   (later cut in half) */
  1.2508 +  int is_areakey = PGL_KEY_IS_AREAKEY(
  1.2509 +    (pgl_keyptr)DatumGetPointer(entryvec->vector[FirstOffsetNumber].key)
  1.2510 +  );
  1.2511 +  int keysize = is_areakey ? sizeof(pgl_areakey) : sizeof(pgl_pointkey);
  1.2512 +  pgl_keyptr unionL = palloc(keysize);  /* union of keys that go left */
  1.2513 +  pgl_keyptr unionR = palloc(keysize);  /* union of keys that go right */
  1.2514 +  pgl_keyptr key;  /* current key to be processed */
  1.2515 +  /* allocate memory for array of left and right keys, set counts to zero */
  1.2516 +  v->spl_left = (OffsetNumber *)palloc(entryvec->n * sizeof(OffsetNumber));
  1.2517 +  v->spl_nleft = 0;
  1.2518 +  v->spl_right = (OffsetNumber *)palloc(entryvec->n * sizeof(OffsetNumber));
  1.2519 +  v->spl_nright = 0;
  1.2520 +  /* calculate union of all keys from scratch */
  1.2521 +  memcpy(
  1.2522 +    (pgl_keyptr)&union_all,
  1.2523 +    (pgl_keyptr)DatumGetPointer(entryvec->vector[FirstOffsetNumber].key),
  1.2524 +    keysize
  1.2525 +  );
  1.2526 +  for (i=FirstOffsetNumber+1; i<entryvec->n; i=OffsetNumberNext(i)) {
  1.2527 +    pgl_unite_keys(
  1.2528 +      (pgl_keyptr)&union_all,
  1.2529 +      (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key)
  1.2530 +    );
  1.2531 +  }
  1.2532 +  /* check if trivial split is necessary due to exhausted key length */
  1.2533 +  /* (Note: keys for empty objects must have node depth set to maximum) */
  1.2534 +  if (PGL_KEY_NODEDEPTH((pgl_keyptr)&union_all) == (
  1.2535 +    is_areakey ? PGL_AREAKEY_MAXDEPTH : PGL_POINTKEY_MAXDEPTH
  1.2536 +  )) {
  1.2537 +    /* half of all keys go left */
  1.2538 +    for (
  1.2539 +      i=FirstOffsetNumber;
  1.2540 +      i<FirstOffsetNumber+(entryvec->n - FirstOffsetNumber)/2;
  1.2541 +      i=OffsetNumberNext(i)
  1.2542 +    ) {
  1.2543 +      /* pointer to current key */
  1.2544 +      key = (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key);
  1.2545 +      /* update unionL */
  1.2546 +      /* check if key is first key that goes left */
  1.2547 +      if (!v->spl_nleft) {
  1.2548 +        /* first key that goes left is just copied to unionL */
  1.2549 +        memcpy(unionL, key, keysize);
  1.2550 +      } else {
  1.2551 +        /* unite current value and next key */
  1.2552 +        pgl_unite_keys(unionL, key);
  1.2553 +      }
  1.2554 +      /* append offset number to list of keys that go left */
  1.2555 +      v->spl_left[v->spl_nleft++] = i;
  1.2556 +    }
  1.2557 +    /* other half goes right */
  1.2558 +    for (
  1.2559 +      i=FirstOffsetNumber+(entryvec->n - FirstOffsetNumber)/2;
  1.2560 +      i<entryvec->n;
  1.2561 +      i=OffsetNumberNext(i)
  1.2562 +    ) {
  1.2563 +      /* pointer to current key */
  1.2564 +      key = (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key);
  1.2565 +      /* update unionR */
  1.2566 +      /* check if key is first key that goes right */
  1.2567 +      if (!v->spl_nright) {
  1.2568 +        /* first key that goes right is just copied to unionR */
  1.2569 +        memcpy(unionR, key, keysize);
  1.2570 +      } else {
  1.2571 +        /* unite current value and next key */
  1.2572 +        pgl_unite_keys(unionR, key);
  1.2573 +      }
  1.2574 +      /* append offset number to list of keys that go right */
  1.2575 +      v->spl_right[v->spl_nright++] = i;
  1.2576 +    }
  1.2577 +  }
  1.2578 +  /* otherwise, a non-trivial split is possible */
  1.2579 +  else {
  1.2580 +    /* cut covered area in half */
  1.2581 +    /* (union_all then refers to area of keys that go left) */
  1.2582 +    /* check if union of all keys covers empty and non-empty objects */
  1.2583 +    if (PGL_KEY_IS_UNIVERSAL((pgl_keyptr)&union_all)) {
  1.2584 +      /* if yes, split into empty and non-empty objects */
  1.2585 +      pgl_key_set_empty((pgl_keyptr)&union_all);
  1.2586 +    } else {
  1.2587 +      /* otherwise split by next bit */
  1.2588 +      ((pgl_keyptr)&union_all)[PGL_KEY_NODEDEPTH_OFFSET]++;
  1.2589 +      /* NOTE: type bit conserved */
  1.2590 +    }
  1.2591 +    /* determine for each key if it goes left or right */
  1.2592 +    for (i=FirstOffsetNumber; i<entryvec->n; i=OffsetNumberNext(i)) {
  1.2593 +      /* pointer to current key */
  1.2594 +      key = (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key);
  1.2595 +      /* keys within one half of the area go left */
  1.2596 +      if (pgl_keys_overlap((pgl_keyptr)&union_all, key)) {
  1.2597 +        /* update unionL */
  1.2598 +        /* check if key is first key that goes left */
  1.2599 +        if (!v->spl_nleft) {
  1.2600 +          /* first key that goes left is just copied to unionL */
  1.2601 +          memcpy(unionL, key, keysize);
  1.2602 +        } else {
  1.2603 +          /* unite current value of unionL and processed key */
  1.2604 +          pgl_unite_keys(unionL, key);
  1.2605 +        }
  1.2606 +        /* append offset number to list of keys that go left */
  1.2607 +        v->spl_left[v->spl_nleft++] = i;
  1.2608 +      }
  1.2609 +      /* the other keys go right */
  1.2610 +      else {
  1.2611 +        /* update unionR */
  1.2612 +        /* check if key is first key that goes right */
  1.2613 +        if (!v->spl_nright) {
  1.2614 +          /* first key that goes right is just copied to unionR */
  1.2615 +          memcpy(unionR, key, keysize);
  1.2616 +        } else {
  1.2617 +          /* unite current value of unionR and processed key */
  1.2618 +          pgl_unite_keys(unionR, key);
  1.2619 +        }
  1.2620 +        /* append offset number to list of keys that go right */
  1.2621 +        v->spl_right[v->spl_nright++] = i;
  1.2622 +      }
  1.2623 +    }
  1.2624 +  }
  1.2625 +  /* store unions in return value */
  1.2626 +  v->spl_ldatum = PointerGetDatum(unionL);
  1.2627 +  v->spl_rdatum = PointerGetDatum(unionR);
  1.2628 +  /* return all results */
  1.2629 +  PG_RETURN_POINTER(v);
  1.2630 +}
  1.2631 +
  1.2632 +/* GiST "same"/"equal" support function */
  1.2633 +PG_FUNCTION_INFO_V1(pgl_gist_same);
  1.2634 +Datum pgl_gist_same(PG_FUNCTION_ARGS) {
  1.2635 +  pgl_keyptr key1 = (pgl_keyptr)PG_GETARG_POINTER(0);
  1.2636 +  pgl_keyptr key2 = (pgl_keyptr)PG_GETARG_POINTER(1);
  1.2637 +  bool *boolptr = (bool *)PG_GETARG_POINTER(2);
  1.2638 +  /* two keys are equal if they are binary equal */
  1.2639 +  /* (return result by setting referenced boolean and returning pointer) */
  1.2640 +  *boolptr = !memcmp(
  1.2641 +    key1,
  1.2642 +    key2,
  1.2643 +    PGL_KEY_IS_AREAKEY(key1) ? sizeof(pgl_areakey) : sizeof(pgl_pointkey)
  1.2644 +  );
  1.2645 +  PG_RETURN_POINTER(boolptr);
  1.2646 +}
  1.2647 +
  1.2648 +/* GiST "distance" support function */
  1.2649 +PG_FUNCTION_INFO_V1(pgl_gist_distance);
  1.2650 +Datum pgl_gist_distance(PG_FUNCTION_ARGS) {
  1.2651 +  GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
  1.2652 +  pgl_keyptr key = (pgl_keyptr)DatumGetPointer(entry->key);
  1.2653 +  StrategyNumber strategy = (StrategyNumber)PG_GETARG_UINT16(2);
  1.2654 +  bool *recheck = (bool *)PG_GETARG_POINTER(4);
  1.2655 +  double distance;  /* return value */
  1.2656 +  /* demand recheck because distance is just an estimation */
  1.2657 +  /* (real distance may be bigger) */
  1.2658 +  *recheck = true;
  1.2659 +  /* strategy number 31: distance to point */
  1.2660 +  if (strategy == 31) {
  1.2661 +    /* query datum is a point */
  1.2662 +    pgl_point *query = (pgl_point *)PG_GETARG_POINTER(1);
  1.2663 +    /* use pgl_estimate_pointkey_distance() function to compute result */
  1.2664 +    distance = pgl_estimate_key_distance(key, query);
  1.2665 +    /* avoid infinity (reserved!) */
  1.2666 +    if (!isfinite(distance)) distance = PGL_ULTRA_DISTANCE;
  1.2667 +    /* return result */
  1.2668 +    PG_RETURN_FLOAT8(distance);
  1.2669 +  }
  1.2670 +  /* strategy number 33: distance to circle */
  1.2671 +  if (strategy == 33) {
  1.2672 +    /* query datum is a circle */
  1.2673 +    pgl_circle *query = (pgl_circle *)PG_GETARG_POINTER(1);
  1.2674 +    /* estimate distance to circle center and substract circle radius */
  1.2675 +    distance = (
  1.2676 +      pgl_estimate_key_distance(key, &(query->center)) - query->radius
  1.2677 +    );
  1.2678 +    /* convert non-positive values to zero and avoid infinity (reserved!) */
  1.2679 +    if (distance <= 0) distance = 0;
  1.2680 +    else if (!isfinite(distance)) distance = PGL_ULTRA_DISTANCE;
  1.2681 +    /* return result */
  1.2682 +    PG_RETURN_FLOAT8(distance);
  1.2683 +  }
  1.2684 +  /* strategy number 34: distance to cluster */
  1.2685 +  if (strategy == 34) {
  1.2686 +    /* query datum is a cluster */
  1.2687 +    pgl_cluster *query = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
  1.2688 +    /* estimate distance to bounding center and substract bounding radius */
  1.2689 +    distance = (
  1.2690 +      pgl_estimate_key_distance(key, &(query->bounding.center)) -
  1.2691 +      query->bounding.radius
  1.2692 +    );
  1.2693 +    /* convert non-positive values to zero and avoid infinity (reserved!) */
  1.2694 +    if (distance <= 0) distance = 0;
  1.2695 +    else if (!isfinite(distance)) distance = PGL_ULTRA_DISTANCE;
  1.2696 +    /* free detoasted cluster (if copy) */
  1.2697 +    PG_FREE_IF_COPY(query, 1);
  1.2698 +    /* return result */
  1.2699 +    PG_RETURN_FLOAT8(distance);
  1.2700 +  }
  1.2701 +  /* throw error for any unknown strategy number */
  1.2702 +  elog(ERROR, "unrecognized strategy number: %d", strategy);
  1.2703 +}
  1.2704 +

Impressum / About Us