-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-- 
-- $Id: lwpostgis.sql.in 2406 2006-07-07 13:56:52Z strk $
--
-- PostGIS - Spatial Types for PostgreSQL
-- http://postgis.refractions.net
-- Copyright 2001-2003 Refractions Research Inc.
--
-- This is free software; you can redistribute and/or modify it under
-- the terms of the GNU General Public Licence. See the COPYING file.
--  
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--
-- WARNING: Any change in this file must be evaluated for compatibility.
--          Changes cleanly handled by lwpostgis_uptrade.sql are fine,
--	    other changes will require a bump in Major version.
--	    Currently only function replaceble by CREATE OR REPLACE
--	    are cleanly handled.
--
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


#define CREATEFUNCTION CREATE OR REPLACE FUNCTION

#if USE_VERSION > 72
# define _IMMUTABLE_STRICT IMMUTABLE STRICT
# define _IMMUTABLE IMMUTABLE
# define _STABLE_STRICT STABLE STRICT
# define _STABLE STABLE
# define _VOLATILE_STRICT VOLATILE STRICT
# define _VOLATILE VOLATILE
# define _STRICT STRICT
# define _SECURITY_DEFINER SECURITY DEFINER
#else 
# define _IMMUTABLE_STRICT  with(iscachable,isstrict)
# define _IMMUTABLE with(iscachable)
# define _STABLE_STRICT with(isstrict)
# define _STABLE 
# define _VOLATILE_STRICT with(isstrict)
# define _VOLATILE 
# define _STRICT with(isstrict)
# define _SECURITY_DEFINER 
#endif 

#if USE_VERSION >= 73
# define HAS_SCHEMAS 1
#endif

BEGIN;

-------------------------------------------------------------------
--  HISTOGRAM2D TYPE (lwhistogram2d)
-------------------------------------------------------------------

#if USE_VERSION < 73
# define HISTOGRAM_IN_REP opaque
# define HISTOGRAM_OUT_REP opaque
#else
# define HISTOGRAM_IN_REP histogram2d
# define HISTOGRAM_OUT_REP cstring
#endif

CREATEFUNCTION histogram2d_in(HISTOGRAM_OUT_REP)
	RETURNS HISTOGRAM_IN_REP
	AS '@MODULE_FILENAME@', 'lwhistogram2d_in'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION histogram2d_out(HISTOGRAM_IN_REP)
	RETURNS HISTOGRAM_OUT_REP
	AS '@MODULE_FILENAME@', 'lwhistogram2d_out'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATE TYPE histogram2d (
	alignment = double,
	internallength = variable,
	input = histogram2d_in,
	output = histogram2d_out,
	storage = main
);

-------------------------------------------------------------------
--  SPHEROID TYPE
-------------------------------------------------------------------

#if USE_VERSION < 73
# define SPHEROID_IN_REP opaque
# define SPHEROID_OUT_REP opaque
#else
# define SPHEROID_IN_REP spheroid
# define SPHEROID_OUT_REP cstring
#endif

CREATEFUNCTION spheroid_in(SPHEROID_OUT_REP)
	RETURNS SPHEROID_IN_REP
	AS '@MODULE_FILENAME@','ellipsoid_in'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION spheroid_out(SPHEROID_IN_REP)
	RETURNS SPHEROID_OUT_REP
	AS '@MODULE_FILENAME@','ellipsoid_out'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATE TYPE spheroid (
	alignment = double,
	internallength = 65,
	input = spheroid_in,
	output = spheroid_out
);

-------------------------------------------------------------------
--  GEOMETRY TYPE (lwgeom)
-------------------------------------------------------------------

#if USE_VERSION < 73
# define GEOMETRY_IN_REP opaque
# define GEOMETRY_OUT_REP opaque
#else
# define GEOMETRY_IN_REP geometry
# define GEOMETRY_OUT_REP cstring
#endif

CREATEFUNCTION geometry_in(GEOMETRY_OUT_REP)
        RETURNS geometry
        AS '@MODULE_FILENAME@','LWGEOM_in'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_out(GEOMETRY_IN_REP)
        RETURNS cstring
        AS '@MODULE_FILENAME@','LWGEOM_out'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

#if USE_VERSION >= 80
CREATEFUNCTION geometry_analyze(internal)
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_analyze'
	LANGUAGE 'C' _VOLATILE_STRICT; -- WITH (isstrict);
#endif

#if USE_VERSION > 73
CREATEFUNCTION geometry_recv(internal)
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_recv'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION geometry_send(geometry)
	RETURNS bytea
	AS '@MODULE_FILENAME@','LWGEOM_send'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);
#endif


CREATE TYPE geometry (
        internallength = variable,
        input = geometry_in,
        output = geometry_out,
#if USE_VERSION > 73
	send = geometry_send,
	receive = geometry_recv,
#endif
	delimiter = ':',
#if USE_VERSION >= 80
	analyze = geometry_analyze,
#endif 
        storage = main
);

-------------------------------------------
-- Affine transforms
-------------------------------------------

-- Availability: 1.1.2
CREATE OR REPLACE FUNCTION Affine(geometry,float8,float8,float8,float8,float8,float8,float8,float8,float8,float8,float8,float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_affine'
	LANGUAGE 'C' _IMMUTABLE_STRICT; 

-- Availability: 1.1.2
CREATE OR REPLACE FUNCTION Affine(geometry,float8,float8,float8,float8,float8,float8)
	RETURNS geometry
	AS 'SELECT affine($1,  $2, $3, 0,  $4, $5, 0,  0, 0, 1,  $6, $7, 0)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

-- Availability: 1.1.2
CREATEFUNCTION RotateZ(geometry,float8)
	RETURNS geometry
	AS 'SELECT affine($1,  cos($2), -sin($2), 0,  sin($2), cos($2), 0,  0, 0, 1,  0, 0, 0)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

-- Availability: 1.1.2
CREATEFUNCTION Rotate(geometry,float8)
	RETURNS geometry
	AS 'SELECT rotateZ($1, $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

-- Availability: 1.1.2
CREATEFUNCTION RotateX(geometry,float8)
	RETURNS geometry
 	AS 'SELECT affine($1, 1, 0, 0, 0, cos($2), -sin($2), 0, sin($2), cos($2), 0, 0, 0)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

-- Availability: 1.1.2
CREATEFUNCTION RotateY(geometry,float8)
	RETURNS geometry
 	AS 'SELECT affine($1,  cos($2), 0, sin($2),  0, 1, 0,  -sin($2), 0, cos($2), 0,  0, 0)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

CREATEFUNCTION Translate(geometry,float8,float8,float8)
	RETURNS geometry
 	AS 'SELECT affine($1, 1, 0, 0, 0, 1, 0, 0, 0, 1, $2, $3, $4)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

CREATEFUNCTION Translate(geometry,float8,float8)
	RETURNS geometry
	AS 'SELECT translate($1, $2, $3, 0)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT;

-- Availability: 1.1.0
CREATEFUNCTION Scale(geometry,float8,float8,float8)
	RETURNS geometry
	AS 'SELECT affine($1,  $2, 0, 0,  0, $3, 0,  0, 0, $4,  0, 0, 0)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

-- Availability: 1.1.0
CREATEFUNCTION Scale(geometry,float8,float8)
	RETURNS geometry
	AS 'SELECT scale($1, $2, $3, 1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; 

-- Availability: 1.1.0 
CREATEFUNCTION transscale(geometry,float8,float8,float8,float8)
        RETURNS geometry
        AS 'SELECT affine($1,  $4, 0, 0,  0, $5, 0, 
		0, 0, 1,  $2 * $4, $3 * $5, 0)'
        LANGUAGE 'SQL' _IMMUTABLE_STRICT;

-- Availability: 1.1.0
CREATEFUNCTION shift_longitude(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_longitude_shift'
	LANGUAGE 'C' _IMMUTABLE_STRICT; 


        
-------------------------------------------------------------------
--  BOX3D TYPE
-------------------------------------------------------------------

#if USE_VERSION < 73
# define BOX3D_IN_REP opaque
# define BOX3D_OUT_REP opaque
#else
# define BOX3D_IN_REP box3d
# define BOX3D_OUT_REP cstring
#endif

CREATEFUNCTION box3d_in(BOX3D_OUT_REP)
	RETURNS BOX3D_IN_REP
	AS '@MODULE_FILENAME@', 'BOX3D_in'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION box3d_out(BOX3D_IN_REP)
	RETURNS BOX3D_OUT_REP
	AS '@MODULE_FILENAME@', 'BOX3D_out'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATE TYPE box3d (
	alignment = double,
	internallength = 48,
	input = box3d_in,
	output = box3d_out
);

CREATEFUNCTION xmin(box3d)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','BOX3D_xmin'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION ymin(box3d)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','BOX3D_ymin'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION zmin(box3d)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','BOX3D_zmin'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION xmax(box3d)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','BOX3D_xmax'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION ymax(box3d)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','BOX3D_ymax'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION zmax(box3d)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','BOX3D_zmax'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-------------------------------------------------------------------
--  CHIP TYPE
-------------------------------------------------------------------

#if USE_VERSION < 73
# define CHIP_IN_REP opaque
# define CHIP_OUT_REP opaque
#else
# define CHIP_IN_REP chip
# define CHIP_OUT_REP cstring
#endif

CREATEFUNCTION chip_in(CHIP_OUT_REP)
	RETURNS CHIP_IN_REP
	AS '@MODULE_FILENAME@','CHIP_in'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION chip_out(CHIP_IN_REP)
	RETURNS CHIP_OUT_REP
	AS '@MODULE_FILENAME@','CHIP_out'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATE TYPE chip (
	alignment = double,
	internallength = variable,
	input = chip_in,
	output = chip_out,
	storage = extended
);

-----------------------------------------------------------------------
-- BOX2D
-----------------------------------------------------------------------


#if USE_VERSION < 73
# define BOX2D_IN_REP opaque
# define BOX2D_OUT_REP opaque
#else
# define BOX2D_IN_REP box2d
# define BOX2D_OUT_REP cstring
#endif

CREATEFUNCTION box2d_in(BOX2D_OUT_REP)
        RETURNS box2d
        AS '@MODULE_FILENAME@','BOX2DFLOAT4_in'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_out(BOX2D_IN_REP)
        RETURNS cstring
        AS '@MODULE_FILENAME@','BOX2DFLOAT4_out'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATE TYPE box2d (
        internallength = 16,
        input = box2d_in,
        output = box2d_out,
        storage = plain
);

---- BOX2D  support functions


CREATEFUNCTION box2d_overleft(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_overleft'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_overright(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_overright' 
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_left(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_left' 
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_right(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_right' 
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_contain(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_contain'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_contained(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_contained'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_overlap(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_overlap'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_same(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_same'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d_intersects(box2d, box2d) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'BOX2D_intersects'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- lwgeom  operator support functions

-------------------------------------------------------------------
-- BTREE indexes
-------------------------------------------------------------------

CREATEFUNCTION geometry_lt(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'lwgeom_lt'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION geometry_le(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'lwgeom_le'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION geometry_gt(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'lwgeom_gt'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION geometry_ge(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'lwgeom_ge'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION geometry_eq(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'lwgeom_eq'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION geometry_cmp(geometry, geometry) 
	RETURNS integer
	AS '@MODULE_FILENAME@', 'lwgeom_cmp'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

--
-- Sorting operators for Btree
--

CREATE OPERATOR < (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_lt,
   COMMUTATOR = '>', NEGATOR = '>=',
   RESTRICT = contsel, JOIN = contjoinsel
);

CREATE OPERATOR <= (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_le,
   COMMUTATOR = '>=', NEGATOR = '>',
   RESTRICT = contsel, JOIN = contjoinsel
);

CREATE OPERATOR = (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_eq,
   COMMUTATOR = '=', -- we might implement a faster negator here
   RESTRICT = contsel, JOIN = contjoinsel
);

CREATE OPERATOR >= (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_ge,
   COMMUTATOR = '<=', NEGATOR = '<',
   RESTRICT = contsel, JOIN = contjoinsel
);
CREATE OPERATOR > (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_gt,
   COMMUTATOR = '<', NEGATOR = '<=',
   RESTRICT = contsel, JOIN = contjoinsel
);

#if USE_VERSION >= 74

CREATE OPERATOR CLASS btree_geometry_ops
	DEFAULT FOR TYPE geometry USING btree AS
	OPERATOR	1	< ,
	OPERATOR	2	<= ,
	OPERATOR	3	= ,
	OPERATOR	4	>= ,
	OPERATOR	5	> ,
	FUNCTION	1	geometry_cmp (geometry, geometry);

#endif


-------------------------------------------------------------------
-- GiST indexes
-------------------------------------------------------------------
#if USE_VERSION < 73
CREATEFUNCTION postgis_gist_sel(opaque, oid,  opaque, int4)
#else
CREATEFUNCTION postgis_gist_sel (internal, oid, internal, int4)
#endif
	RETURNS float8
	AS '@MODULE_FILENAME@', 'LWGEOM_gist_sel'
	LANGUAGE 'C';

#if USE_VERSION == 72
CREATEFUNCTION postgis_gist_joinsel(opaque, oid,  opaque)
#elif USE_VERSION == 73
CREATEFUNCTION postgis_gist_joinsel(internal, oid,  internal)
#else
CREATEFUNCTION postgis_gist_joinsel(internal, oid, internal, smallint)
#endif
	RETURNS float8
	AS '@MODULE_FILENAME@', 'LWGEOM_gist_joinsel'
	LANGUAGE 'C';

CREATEFUNCTION geometry_overleft(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_overleft'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_overright(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_overright'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_overabove(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_overabove'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_overbelow(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_overbelow'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_left(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_left'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_right(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_right'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_above(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_above'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_below(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_below'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_contain(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_contain'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_contained(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_contained'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_overlap(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_overlap'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry_same(geometry, geometry) 
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_same'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- GEOMETRY operators

CREATE OPERATOR << (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_left,
   COMMUTATOR = '>>',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR &< (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_overleft,
   COMMUTATOR = '&>',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR <<| (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_below,
   COMMUTATOR = '|>>',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR &<| (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_overbelow,
   COMMUTATOR = '|&>',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR && (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_overlap,
   COMMUTATOR = '&&',
   RESTRICT = postgis_gist_sel, JOIN = postgis_gist_joinsel
);

CREATE OPERATOR &> (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_overright,
   COMMUTATOR = '&<',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR >> (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_right,
   COMMUTATOR = '<<',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR |&> (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_overabove,
   COMMUTATOR = '&<|',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR |>> (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_above,
   COMMUTATOR = '<<|',
   RESTRICT = positionsel, JOIN = positionjoinsel
);

CREATE OPERATOR ~= (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_same,
   COMMUTATOR = '~=', 
   RESTRICT = eqsel, JOIN = eqjoinsel
);

CREATE OPERATOR @ (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_contained,
   COMMUTATOR = '~',
   RESTRICT = contsel, JOIN = contjoinsel
);

CREATE OPERATOR ~ (
   LEFTARG = geometry, RIGHTARG = geometry, PROCEDURE = geometry_contain,
   COMMUTATOR = '@',
   RESTRICT = contsel, JOIN = contjoinsel
);

-- gist support functions

#if USE_VERSION < 73
#define OPAQUE_TYPE opaque
#else
#define OPAQUE_TYPE internal
#endif

CREATEFUNCTION LWGEOM_gist_consistent(OPAQUE_TYPE,geometry,int4) 
	RETURNS bool 
	AS '@MODULE_FILENAME@' ,'LWGEOM_gist_consistent'
	LANGUAGE 'C';

CREATEFUNCTION LWGEOM_gist_compress(OPAQUE_TYPE) 
	RETURNS OPAQUE_TYPE 
	AS '@MODULE_FILENAME@','LWGEOM_gist_compress'
	LANGUAGE 'C';

CREATEFUNCTION LWGEOM_gist_penalty(OPAQUE_TYPE,OPAQUE_TYPE,OPAQUE_TYPE) 
	RETURNS OPAQUE_TYPE 
	AS '@MODULE_FILENAME@' ,'LWGEOM_gist_penalty'
	LANGUAGE 'C';

CREATEFUNCTION LWGEOM_gist_picksplit(OPAQUE_TYPE, OPAQUE_TYPE) 
	RETURNS OPAQUE_TYPE 
	AS '@MODULE_FILENAME@' ,'LWGEOM_gist_picksplit'
	LANGUAGE 'C';

CREATEFUNCTION LWGEOM_gist_union(bytea, OPAQUE_TYPE) 
	RETURNS OPAQUE_TYPE 
	AS '@MODULE_FILENAME@' ,'LWGEOM_gist_union'
	LANGUAGE 'C';

CREATEFUNCTION LWGEOM_gist_same(box2d, box2d, OPAQUE_TYPE) 
	RETURNS OPAQUE_TYPE 
	AS '@MODULE_FILENAME@' ,'LWGEOM_gist_same'
	LANGUAGE 'C';

CREATEFUNCTION LWGEOM_gist_decompress(OPAQUE_TYPE) 
	RETURNS OPAQUE_TYPE
	AS '@MODULE_FILENAME@' ,'LWGEOM_gist_decompress'
	LANGUAGE 'C';

-------------------------------------------
-- GIST opclass index binding entries.
-------------------------------------------

#if USE_VERSION == 72

--
-- Create opclass index binding entries for PG72
--

INSERT INTO pg_opclass (opcamid, opcname, opcintype, opcdefault, opckeytype)
    VALUES (
        (SELECT oid FROM pg_am WHERE amname = 'gist'),
        'gist_geometry_ops',
        (SELECT oid FROM pg_type WHERE typname = 'geometry'),
        true,
        (SELECT oid FROM pg_type WHERE typname = 'box2d'));

-- drop table rt_ops_tmp;

SELECT o.oid AS opoid, o.oprname
	INTO TABLE rt_ops_tmp
	FROM pg_operator o, pg_type t
	WHERE o.oprleft = t.oid 
		AND t.typname = 'geometry';

-- poly_left
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 1, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '<<';

-- poly_overleft
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 2, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '&<';

-- poly_overlap
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 3, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '&&';

-- poly_overright
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 4, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '&>';

-- poly_right
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr)
   SELECT opcl.oid, 5, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '>>';

-- poly_same
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 6, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '~=';

-- poly_contains
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr)
   SELECT opcl.oid, 7, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '~';

-- poly_contained
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr)
   SELECT opcl.oid, 8, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '@';

-- poly_overbelow
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr)
   SELECT opcl.oid, 9, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '&<|';

-- poly_below
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 10, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '<<|';

-- poly_above
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 11, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '|>>';

-- poly_overabove
INSERT INTO pg_amop (amopclaid, amopstrategy, amopreqcheck, amopopr) 
   SELECT opcl.oid, 12, true, c.opoid
   FROM pg_opclass opcl, rt_ops_tmp c
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops' 
      and c.oprname = '|&>';

DROP TABLE rt_ops_tmp;


-- add the entries to amproc for the support methods
-- note the amprocnum numbers associated with each are specific!
INSERT INTO pg_amproc (amopclaid, amprocnum, amproc)
   SELECT opcl.oid, 1, pro.oid
   FROM pg_opclass opcl, pg_proc pro
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops'
      and proname = 'lwgeom_gist_consistent';

INSERT INTO pg_amproc (amopclaid, amprocnum, amproc)
   SELECT opcl.oid, 2, pro.oid
   FROM pg_opclass opcl, pg_proc pro
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops'
      and proname = 'lwgeom_gist_union';

INSERT INTO pg_amproc (amopclaid, amprocnum, amproc)
   SELECT opcl.oid, 3, pro.oid
   FROM pg_opclass opcl, pg_proc pro
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops'
      and proname = 'lwgeom_gist_compress';

INSERT INTO pg_amproc (amopclaid, amprocnum, amproc)
   SELECT opcl.oid, 4, pro.oid
   FROM pg_opclass opcl, pg_proc pro
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops'
      and proname = 'lwgeom_gist_decompress';

INSERT INTO pg_amproc (amopclaid, amprocnum, amproc)
   SELECT opcl.oid, 5, pro.oid
   FROM pg_opclass opcl, pg_proc pro
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops'
      and proname = 'lwgeom_gist_penalty';

INSERT INTO pg_amproc (amopclaid, amprocnum, amproc)
   SELECT opcl.oid, 6, pro.oid
   FROM pg_opclass opcl, pg_proc pro
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops'
      and proname = 'lwgeom_gist_picksplit';

INSERT INTO pg_amproc (amopclaid, amprocnum, amproc)
   SELECT opcl.oid, 7, pro.oid
   FROM pg_opclass opcl, pg_proc pro
   WHERE
      opcamid = (SELECT oid FROM pg_am WHERE amname = 'gist')
      and opcname = 'gist_geometry_ops'
      and proname = 'lwgeom_gist_same';

#else

--
-- Create opclass index bindings for PG>=73
--

CREATE OPERATOR CLASS gist_geometry_ops
        DEFAULT FOR TYPE geometry USING gist AS
        OPERATOR        1        << 	RECHECK,
        OPERATOR        2        &<	RECHECK,
        OPERATOR        3        &&	RECHECK,
        OPERATOR        4        &>	RECHECK,
        OPERATOR        5        >>	RECHECK,
        OPERATOR        6        ~=	RECHECK,
        OPERATOR        7        ~	RECHECK,
        OPERATOR        8        @	RECHECK,
	OPERATOR	9	 &<|	RECHECK,
	OPERATOR	10	 <<|	RECHECK,
	OPERATOR	11	 |>>	RECHECK,
	OPERATOR	12	 |&>	RECHECK,
	FUNCTION        1        LWGEOM_gist_consistent (internal, geometry, int4),
        FUNCTION        2        LWGEOM_gist_union (bytea, internal),
        FUNCTION        3        LWGEOM_gist_compress (internal),
        FUNCTION        4        LWGEOM_gist_decompress (internal),
        FUNCTION        5        LWGEOM_gist_penalty (internal, internal, internal),
        FUNCTION        6        LWGEOM_gist_picksplit (internal, internal),
        FUNCTION        7        LWGEOM_gist_same (box2d, box2d, internal);

UPDATE pg_opclass 
	SET opckeytype = (SELECT oid FROM pg_type 
                          WHERE typname = 'box2d' 
                          AND typnamespace = (SELECT oid FROM pg_namespace 
                                              WHERE nspname=current_schema())) 
	WHERE opcname = 'gist_geometry_ops' 
        AND opcnamespace = (SELECT oid from pg_namespace 
                            WHERE nspname=current_schema());
	
-- TODO: add btree binding...

#endif
	
-------------------------------------------
-- other lwgeom functions
-------------------------------------------

CREATEFUNCTION addBBOX(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_addBBOX'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION dropBBOX(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_dropBBOX'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

	
CREATEFUNCTION getSRID(geometry) 
	RETURNS int4
	AS '@MODULE_FILENAME@','LWGEOM_getSRID'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION getBBOX(geometry)
        RETURNS box2d
        AS '@MODULE_FILENAME@','LWGEOM_to_BOX2DFLOAT4'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-------------------------------------------
--- CHIP functions
-------------------------------------------

CREATEFUNCTION srid(chip)
	RETURNS int4
	AS '@MODULE_FILENAME@','CHIP_getSRID'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION height(chip)
	RETURNS int4
	AS '@MODULE_FILENAME@','CHIP_getHeight'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION factor(chip)
	RETURNS FLOAT4
	AS '@MODULE_FILENAME@','CHIP_getFactor'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION width(chip)
	RETURNS int4
	AS '@MODULE_FILENAME@','CHIP_getWidth'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION datatype(chip)
	RETURNS int4
	AS '@MODULE_FILENAME@','CHIP_getDatatype'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION compression(chip)
	RETURNS int4
	AS '@MODULE_FILENAME@','CHIP_getCompression'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION setSRID(chip,int4)
	RETURNS chip
	AS '@MODULE_FILENAME@','CHIP_setSRID'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION setFactor(chip,float4)
	RETURNS chip
	AS '@MODULE_FILENAME@','CHIP_setFactor'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

------------------------------------------------------------------------
-- DEBUG
------------------------------------------------------------------------

CREATEFUNCTION mem_size(geometry)
	RETURNS int4
	AS '@MODULE_FILENAME@', 'LWGEOM_mem_size'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION summary(geometry)
	RETURNS text
	AS '@MODULE_FILENAME@', 'LWGEOM_summary'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION npoints(geometry)
	RETURNS int4
	AS '@MODULE_FILENAME@', 'LWGEOM_npoints'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION nrings(geometry)
	RETURNS int4
	AS '@MODULE_FILENAME@', 'LWGEOM_nrings'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

------------------------------------------------------------------------
-- Misures
------------------------------------------------------------------------

-- this is a fake (for back-compatibility)
-- uses 3d if 3d is available, 2d otherwise
CREATEFUNCTION length3d(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@', 'LWGEOM_length_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION length2d(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@', 'LWGEOM_length2d_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION length(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@', 'LWGEOM_length_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-- this is a fake (for back-compatibility)
-- uses 3d if 3d is available, 2d otherwise
CREATEFUNCTION length3d_spheroid(geometry, spheroid)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','LWGEOM_length_ellipsoid_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION length_spheroid(geometry, spheroid)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','LWGEOM_length_ellipsoid_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION length2d_spheroid(geometry, spheroid)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','LWGEOM_length2d_ellipsoid_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-- this is a fake (for back-compatibility)
-- uses 3d if 3d is available, 2d otherwise
CREATEFUNCTION perimeter3d(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@', 'LWGEOM_perimeter_poly'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION perimeter2d(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@', 'LWGEOM_perimeter2d_poly'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION perimeter(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@', 'LWGEOM_perimeter_poly'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-- this is an alias for 'area(geometry)'
-- there is nothing such an 'area3d'...
CREATEFUNCTION area2d(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@', 'LWGEOM_area_polygon'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION area(geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','LWGEOM_area_polygon'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION distance_spheroid(geometry,geometry,spheroid)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','LWGEOM_distance_ellipsoid_point'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION distance_sphere(geometry,geometry)
	RETURNS FLOAT8
	AS '@MODULE_FILENAME@','LWGEOM_distance_sphere'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-- Minimum distance. 2d only.
CREATEFUNCTION distance(geometry,geometry)
	RETURNS float8
	AS '@MODULE_FILENAME@', 'LWGEOM_mindistance2d'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- Maximum distance between linestrings. 2d only. Very bogus.
CREATEFUNCTION max_distance(geometry,geometry)
	RETURNS float8
	AS '@MODULE_FILENAME@', 'LWGEOM_maxdistance2d_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION point_inside_circle(geometry,float8,float8,float8)
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_inside_circle_point'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION azimuth(geometry,geometry)
	RETURNS float8
	AS '@MODULE_FILENAME@', 'LWGEOM_azimuth'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);


------------------------------------------------------------------------
-- MISC
------------------------------------------------------------------------

CREATEFUNCTION force_2d(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_force_2d'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION force_3dz(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_force_3dz'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-- an alias for force_3dz
CREATEFUNCTION force_3d(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_force_3dz'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION force_3dm(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_force_3dm'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION force_4d(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_force_4d'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION force_collection(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_force_collection'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION multi(geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_force_multi'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION collector(geometry, geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_collect'
	LANGUAGE 'C' _IMMUTABLE;

CREATEFUNCTION collect(geometry, geometry) 
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_collect'
	LANGUAGE 'C' _IMMUTABLE;

CREATE AGGREGATE memcollect(
	sfunc = collect,
	basetype = geometry,
	stype = geometry
	);

CREATEFUNCTION geom_accum (geometry[],geometry)
	RETURNS geometry[]
	AS '@MODULE_FILENAME@', 'LWGEOM_accum'
	LANGUAGE 'C' _IMMUTABLE;

CREATE AGGREGATE accum (
	sfunc = geom_accum,
	basetype = geometry,
	stype = geometry[]
	);

CREATEFUNCTION collect_garray (geometry[])
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_collect_garray'
	LANGUAGE 'C' _IMMUTABLE_STRICT;

CREATE AGGREGATE collect (
	sfunc = geom_accum,
	basetype = geometry,
	stype = geometry[],
	finalfunc = collect_garray
	);

CREATEFUNCTION expand(box3d,float8)
	RETURNS box3d
	AS '@MODULE_FILENAME@', 'BOX3D_expand'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION expand(box2d,float8)
	RETURNS box2d
	AS '@MODULE_FILENAME@', 'BOX2DFLOAT4_expand'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION expand(geometry,float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_expand'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION envelope(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_envelope'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION reverse(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_reverse'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION ForceRHR(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_forceRHR_poly'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION noop(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_noop'
	LANGUAGE 'C' _VOLATILE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION zmflag(geometry)
	RETURNS smallint
	AS '@MODULE_FILENAME@', 'LWGEOM_zmflag'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION hasBBOX(geometry)
	RETURNS bool
	AS '@MODULE_FILENAME@', 'LWGEOM_hasBBOX'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION ndims(geometry)
	RETURNS smallint
	AS '@MODULE_FILENAME@', 'LWGEOM_ndims'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION AsEWKT(geometry)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','LWGEOM_asEWKT'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsEWKB(geometry)
	RETURNS BYTEA
	AS '@MODULE_FILENAME@','WKBFromLWGEOM'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsHEXEWKB(geometry)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','LWGEOM_asHEXEWKB'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsHEXEWKB(geometry, text)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','LWGEOM_asHEXEWKB'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsEWKB(geometry,text)
	RETURNS bytea
	AS '@MODULE_FILENAME@','WKBFromLWGEOM'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomFromEWKB(bytea)
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOMFromWKB'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomFromEWKT(text)
	RETURNS geometry
	AS '@MODULE_FILENAME@','parse_WKT_lwgeom'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION cache_bbox()
	RETURNS trigger
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C';

------------------------------------------------------------------------
-- CONSTRUCTORS
------------------------------------------------------------------------

CREATEFUNCTION makePoint(float8, float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makepoint'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION makePoint(float8, float8, float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makepoint'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION makePoint(float8, float8, float8, float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makepoint'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION makePointM(float8, float8, float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makepoint3dm'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION makeBox2d(geometry, geometry)
	RETURNS box2d
	AS '@MODULE_FILENAME@', 'BOX2DFLOAT4_construct'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION makeBox3d(geometry, geometry)
	RETURNS box3d
	AS '@MODULE_FILENAME@', 'BOX3D_construct'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION makeline_garray (geometry[])
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makeline_garray'
	LANGUAGE 'C' _IMMUTABLE_STRICT;

CREATEFUNCTION LineFromMultiPoint(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_line_from_mpoint'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION MakeLine(geometry, geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makeline'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION AddPoint(geometry, geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_addpoint'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION AddPoint(geometry, geometry, integer)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_addpoint'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION RemovePoint(geometry, integer)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_removepoint'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION SetPoint(geometry, integer, geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_setpoint_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATE AGGREGATE makeline (
	sfunc = geom_accum,
	basetype = geometry,
	stype = geometry[],
	finalfunc = makeline_garray
	);

CREATEFUNCTION MakePolygon(geometry, geometry[])
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makepoly'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION MakePolygon(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_makepoly'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION BuildArea(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_buildarea'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);

CREATEFUNCTION polygonize_garray (geometry[])
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'polygonize_garray'
	LANGUAGE 'C' _IMMUTABLE_STRICT;

CREATEFUNCTION LineMerge(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'linemerge'
	LANGUAGE 'C' _IMMUTABLE_STRICT;

CREATE AGGREGATE polygonize (
	sfunc = geom_accum,
	basetype = geometry,
	stype = geometry[],
	finalfunc = polygonize_garray
	);


#if USE_VERSION > 72

CREATE TYPE geometry_dump AS (path integer[], geom geometry);

CREATEFUNCTION Dump(geometry)
	RETURNS SETOF geometry_dump
	AS '@MODULE_FILENAME@', 'LWGEOM_dump'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION DumpRings(geometry)
	RETURNS SETOF geometry_dump
	AS '@MODULE_FILENAME@', 'LWGEOM_dump_rings'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

#endif

------------------------------------------------------------------------

--
-- Aggregate functions
--

CREATEFUNCTION combine_bbox(box2d,geometry)
	RETURNS box2d
	AS '@MODULE_FILENAME@', 'BOX2DFLOAT4_combine'
	LANGUAGE 'C' _IMMUTABLE;

CREATE AGGREGATE extent(
	sfunc = combine_bbox,
	basetype = geometry,
	stype = box2d
	);

CREATEFUNCTION combine_bbox(box3d,geometry)
	RETURNS box3d
	AS '@MODULE_FILENAME@', 'BOX3D_combine'
	LANGUAGE 'C' _IMMUTABLE;

CREATE AGGREGATE extent3d(
	sfunc = combine_bbox,
	basetype = geometry,
	stype = box3d
	);

-----------------------------------------------------------------------
-- CREATE_HISTOGRAM2D( <box2d>, <size> )
-----------------------------------------------------------------------
--
-- Returns a histgram with 0s in all the boxes.
--
-----------------------------------------------------------------------
CREATEFUNCTION create_histogram2d(box2d,int)
	RETURNS histogram2d
	AS '@MODULE_FILENAME@','create_lwhistogram2d'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- BUILD_HISTOGRAM2D( <histogram2d>, <tablename>, <columnname> )
-----------------------------------------------------------------------
CREATEFUNCTION build_histogram2d (histogram2d,text,text)
	RETURNS histogram2d
	AS '@MODULE_FILENAME@','build_lwhistogram2d'
	LANGUAGE 'C' _STABLE_STRICT; -- WITH (isstrict);

#if USE_VERSION >= 73
-----------------------------------------------------------------------
-- BUILD_HISTOGRAM2D(<histogram2d>,<schema>,<tablename>,<columnname>)
-----------------------------------------------------------------------
-- This is a wrapper to the omonimous schema unaware function,
-- thanks to Carl Anderson for the idea.
-----------------------------------------------------------------------
CREATEFUNCTION build_histogram2d (histogram2d,text,text,text)
RETURNS histogram2d
AS '
BEGIN
	EXECUTE ''SET local search_path = ''||$2||'',public'';
	RETURN public.build_histogram2d($1,$3,$4);
END
'
LANGUAGE 'plpgsql' _STABLE_STRICT; -- WITH (isstrict);
#endif

-----------------------------------------------------------------------
-- EXPLODE_HISTOGRAM2D( <histogram2d>, <tablename> )
-----------------------------------------------------------------------
CREATEFUNCTION explode_histogram2d (histogram2d,text)
	RETURNS histogram2d
	AS '@MODULE_FILENAME@','explode_lwhistogram2d'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- ESTIMATE_HISTOGRAM2D( <histogram2d>, <box> )
-----------------------------------------------------------------------
CREATEFUNCTION estimate_histogram2d(histogram2d,box2d)
	RETURNS float8
	AS '@MODULE_FILENAME@','estimate_lwhistogram2d'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- ESTIMATED_EXTENT( <schema name>, <table name>, <column name> )
-----------------------------------------------------------------------
CREATEFUNCTION estimated_extent(text,text,text) RETURNS box2d AS
	'@MODULE_FILENAME@', 'LWGEOM_estimated_extent'
	LANGUAGE 'C' _IMMUTABLE_STRICT _SECURITY_DEFINER;

-----------------------------------------------------------------------
-- ESTIMATED_EXTENT( <table name>, <column name> )
-----------------------------------------------------------------------
CREATEFUNCTION estimated_extent(text,text) RETURNS box2d AS
	'@MODULE_FILENAME@', 'LWGEOM_estimated_extent'
	LANGUAGE 'C' _IMMUTABLE_STRICT _SECURITY_DEFINER; 

-----------------------------------------------------------------------
-- FIND_EXTENT( <schema name>, <table name>, <column name> )
-----------------------------------------------------------------------
CREATEFUNCTION find_extent(text,text,text) RETURNS box2d AS
'
DECLARE
	schemaname alias for $1;
	tablename alias for $2;
	columnname alias for $3;
	myrec RECORD;

BEGIN
	FOR myrec IN EXECUTE ''SELECT extent("''||columnname||''") FROM "''||schemaname||''"."''||tablename||''"'' LOOP
		return myrec.extent;
	END LOOP; 
END;
'
LANGUAGE 'plpgsql' _IMMUTABLE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- FIND_EXTENT( <table name>, <column name> )
-----------------------------------------------------------------------
CREATEFUNCTION find_extent(text,text) RETURNS box2d AS
'
DECLARE
	tablename alias for $1;
	columnname alias for $2;
	myrec RECORD;

BEGIN
	FOR myrec IN EXECUTE ''SELECT extent("''||columnname||''") FROM "''||tablename||''"'' LOOP
		return myrec.extent;
	END LOOP; 
END;
'
LANGUAGE 'plpgsql' _IMMUTABLE_STRICT; -- WITH (isstrict);

-------------------------------------------------------------------
-- SPATIAL_REF_SYS
-------------------------------------------------------------------
CREATE TABLE spatial_ref_sys (
	 srid integer not null primary key,
	 auth_name varchar(256), 
	 auth_srid integer, 
	 srtext varchar(2048),
	 proj4text varchar(2048) 
);

-------------------------------------------------------------------
-- GEOMETRY_COLUMNS
-------------------------------------------------------------------
CREATE TABLE geometry_columns (
	f_table_catalog varchar(256) not null,
	f_table_schema varchar(256) not null,
	f_table_name varchar(256) not null,
	f_geometry_column varchar(256) not null,
	coord_dimension integer not null,
	srid integer not null,
	type varchar(30) not null,
#if USE_VERSION < 80
	attrelid oid,
	varattnum int,
	stats histogram2d,
#endif
	CONSTRAINT geometry_columns_pk primary key ( 
		f_table_catalog, 
		f_table_schema, 
		f_table_name, 
		f_geometry_column )
) WITH OIDS;

-----------------------------------------------------------------------
-- RENAME_GEOMETRY_TABLE_CONSTRAINTS()
-----------------------------------------------------------------------
-- This function has been obsoleted for the difficulty in
-- finding attribute on which the constraint is applied.
-- AddGeometryColumn will name the constraints in a meaningful
-- way, but nobody can rely on it since old postgis versions did
-- not do that.
-----------------------------------------------------------------------
CREATEFUNCTION rename_geometry_table_constraints() RETURNS text
AS 
'
SELECT ''rename_geometry_table_constraint() is obsoleted''::text
'
LANGUAGE 'SQL' _IMMUTABLE;

-----------------------------------------------------------------------
-- FIX_GEOMETRY_COLUMNS() 
-----------------------------------------------------------------------
-- This function will:
--
--	o try to fix the schema of records with an invalid one
--		(for PG>=73)
--
--	o link records to system tables through attrelid and varattnum
--		(for PG<75)
--
--	o delete all records for which no linking was possible
--		(for PG<75)
--	
-- 
-----------------------------------------------------------------------
CREATEFUNCTION fix_geometry_columns() RETURNS text
AS 
'
DECLARE
	mislinked record;
	result text;
	linked integer;
	deleted integer;
#if USE_VERSION >= 73
	foundschema integer;
#endif
BEGIN

#if USE_VERSION >= 73
	-- Since 7.3 schema support has been added.
	-- Previous postgis versions used to put the database name in
	-- the schema column. This needs to be fixed, so we try to 
	-- set the correct schema for each geometry_colums record
	-- looking at table, column, type and srid.
	UPDATE geometry_columns SET f_table_schema = n.nspname
		FROM pg_namespace n, pg_class c, pg_attribute a,
			pg_constraint sridcheck, pg_constraint typecheck
                WHERE ( f_table_schema is NULL
		OR f_table_schema = ''''
                OR f_table_schema NOT IN (
                        SELECT nspname::varchar
                        FROM pg_namespace nn, pg_class cc, pg_attribute aa
                        WHERE cc.relnamespace = nn.oid
                        AND cc.relname = f_table_name::name
                        AND aa.attrelid = cc.oid
                        AND aa.attname = f_geometry_column::name))
                AND f_table_name::name = c.relname
                AND c.oid = a.attrelid
                AND c.relnamespace = n.oid
                AND f_geometry_column::name = a.attname

                AND sridcheck.conrelid = c.oid
		AND sridcheck.consrc LIKE ''(srid(% = %)''
                AND sridcheck.consrc ~ textcat('' = '', srid::text)

                AND typecheck.conrelid = c.oid
		AND typecheck.consrc LIKE
	''((geometrytype(%) = ''''%''''::text) OR (% IS NULL))''
                AND typecheck.consrc ~ textcat('' = '''''', type::text)

                AND NOT EXISTS (
                        SELECT oid FROM geometry_columns gc
                        WHERE c.relname::varchar = gc.f_table_name
                        AND n.nspname::varchar = gc.f_table_schema
                        AND a.attname::varchar = gc.f_geometry_column
                );

	GET DIAGNOSTICS foundschema = ROW_COUNT;
#endif

#if USE_VERSION >= 80
	-- no linkage to system table needed
	return ''fixed:''||foundschema::text;
#endif

	-- fix linking to system tables
	SELECT 0 INTO linked;
	FOR mislinked in
		SELECT gc.oid as gcrec,
			a.attrelid as attrelid, a.attnum as attnum
                FROM geometry_columns gc, pg_class c,
#if USE_VERSION >= 73
		pg_namespace n, pg_attribute a
#else
		pg_attribute a
#endif
                WHERE ( gc.attrelid IS NULL OR gc.attrelid != a.attrelid 
			OR gc.varattnum IS NULL OR gc.varattnum != a.attnum)
#if USE_VERSION >= 73
                AND n.nspname = gc.f_table_schema::name
                AND c.relnamespace = n.oid
#endif
                AND c.relname = gc.f_table_name::name
                AND a.attname = f_geometry_column::name
                AND a.attrelid = c.oid
	LOOP
		UPDATE geometry_columns SET
			attrelid = mislinked.attrelid,
			varattnum = mislinked.attnum,
			stats = NULL
			WHERE geometry_columns.oid = mislinked.gcrec;
		SELECT linked+1 INTO linked;
	END LOOP; 

	-- remove stale records
	DELETE FROM geometry_columns WHERE attrelid IS NULL;

	GET DIAGNOSTICS deleted = ROW_COUNT;

	result = 
#if USE_VERSION >= 73
		''fixed:'' || foundschema::text ||
#endif
		'' linked:'' || linked::text || 
		'' deleted:'' || deleted::text;

	return result;

END;
'
LANGUAGE 'plpgsql' _VOLATILE;

-----------------------------------------------------------------------
-- PROBE_GEOMETRY_COLUMNS() 
-----------------------------------------------------------------------
-- Fill the geometry_columns table with values probed from the system
-- catalogues. 3d flag cannot be probed, it defaults to 2
--
-- Note that bogus records already in geometry_columns are not
-- overridden (a check for schema.table.column is performed), so
-- to have a fresh probe backup your geometry_column, delete from
-- it and probe.
-----------------------------------------------------------------------
CREATEFUNCTION probe_geometry_columns() RETURNS text AS
'
DECLARE
	inserted integer;
	oldcount integer;
	probed integer;
	stale integer;
BEGIN

	SELECT count(*) INTO oldcount FROM geometry_columns;

	SELECT count(*) INTO probed
		FROM pg_class c, pg_attribute a, pg_type t, 
#if USE_VERSION >= 73
			pg_namespace n,
			pg_constraint sridcheck, pg_constraint typecheck
#else
			pg_relcheck sridcheck, pg_relcheck typecheck
#endif 

		WHERE t.typname = ''geometry''
		AND a.atttypid = t.oid
		AND a.attrelid = c.oid
#if USE_VERSION >= 73
		AND c.relnamespace = n.oid
		AND sridcheck.connamespace = n.oid
		AND typecheck.connamespace = n.oid
#endif

#if USE_VERSION >= 73
		AND sridcheck.conrelid = c.oid
		AND sridcheck.consrc LIKE ''(srid(''||a.attname||'') = %)''
		AND typecheck.conrelid = c.oid
		AND typecheck.consrc LIKE
	''((geometrytype(''||a.attname||'') = ''''%''''::text) OR (% IS NULL))''
#else
		AND sridcheck.rcrelid = c.oid
		AND sridcheck.rcsrc LIKE ''(srid(''||a.attname||'') = %)''
		AND typecheck.rcrelid = c.oid
		AND typecheck.rcsrc LIKE
	''((geometrytype(''||a.attname||'') = ''''%''''::text) OR (% IS NULL))''
#endif
		;

	INSERT INTO geometry_columns SELECT
		''''::varchar as f_table_catalogue,
#if USE_VERSION >= 73
		n.nspname::varchar as f_table_schema,
#else
		''''::varchar as f_table_schema,
#endif
		c.relname::varchar as f_table_name,
		a.attname::varchar as f_geometry_column,
		2 as coord_dimension,
#if USE_VERSION >= 73
		trim(both  '' =)'' from substr(sridcheck.consrc,
			strpos(sridcheck.consrc, ''='')))::integer as srid,
		trim(both '' =)'''''' from substr(typecheck.consrc, 
			strpos(typecheck.consrc, ''=''),
			strpos(typecheck.consrc, ''::'')-
			strpos(typecheck.consrc, ''='')
			))::varchar as type
#else
		trim(both  '' =)'' from substr(sridcheck.rcsrc,
			strpos(sridcheck.rcsrc, ''='')))::integer as srid,
		trim(both '' =)'''''' from substr(typecheck.rcsrc, 
			strpos(typecheck.rcsrc, ''=''),
			strpos(typecheck.rcsrc, ''::'')-
			strpos(typecheck.rcsrc, ''='')
			))::varchar as type
#endif

#if USE_VERSION < 80
		, a.attrelid,
		a.attnum as varattnum,
		null::histogram2d as stats
#endif
		FROM pg_class c, pg_attribute a, pg_type t, 
#if USE_VERSION >= 73
			pg_namespace n,
			pg_constraint sridcheck, pg_constraint typecheck
#else
			pg_relcheck sridcheck, pg_relcheck typecheck
#endif 
		WHERE t.typname = ''geometry''
		AND a.atttypid = t.oid
		AND a.attrelid = c.oid
#if USE_VERSION >= 73
		AND c.relnamespace = n.oid
		AND sridcheck.connamespace = n.oid
		AND typecheck.connamespace = n.oid
		AND sridcheck.conrelid = c.oid
		AND sridcheck.consrc LIKE ''(srid(''||a.attname||'') = %)''
		AND typecheck.conrelid = c.oid
		AND typecheck.consrc LIKE
	''((geometrytype(''||a.attname||'') = ''''%''''::text) OR (% IS NULL))''
#else
		AND sridcheck.rcrelid = c.oid
		AND sridcheck.rcsrc LIKE ''(srid(''||a.attname||'') = %)''
		AND typecheck.rcrelid = c.oid
		AND typecheck.rcsrc LIKE
	''((geometrytype(''||a.attname||'') = ''''%''''::text) OR (% IS NULL))''
#endif

                AND NOT EXISTS (
                        SELECT oid FROM geometry_columns gc
                        WHERE c.relname::varchar = gc.f_table_name
#if USE_VERSION >= 73
                        AND n.nspname::varchar = gc.f_table_schema
#endif
                        AND a.attname::varchar = gc.f_geometry_column
                );

	GET DIAGNOSTICS inserted = ROW_COUNT;

	IF oldcount > probed THEN
		stale = oldcount-probed;
	ELSE
		stale = 0;
	END IF;

        RETURN ''probed:''||probed||
		'' inserted:''||inserted||
		'' conflicts:''||probed-inserted||
		'' stale:''||stale;
END

'
LANGUAGE 'plpgsql' _VOLATILE;

-----------------------------------------------------------------------
-- ADDGEOMETRYCOLUMN
--   <catalogue>, <schema>, <table>, <column>, <srid>, <type>, <dim>
-----------------------------------------------------------------------
--
-- Type can be one of geometry, GEOMETRYCOLLECTION, POINT, MULTIPOINT, POLYGON,
-- MULTIPOLYGON, LINESTRING, or MULTILINESTRING.
--
-- Types (except geometry) are checked for consistency using a CHECK constraint
-- uses SQL ALTER TABLE command to add the geometry column to the table.
-- Addes a row to geometry_columns.
-- Addes a constraint on the table that all the geometries MUST have the same 
-- SRID. Checks the coord_dimension to make sure its between 0 and 3.
-- Should also check the precision grid (future expansion).
-- Calls fix_geometry_columns() at the end.
--
-----------------------------------------------------------------------
CREATEFUNCTION AddGeometryColumn(varchar,varchar,varchar,varchar,integer,varchar,integer)
	RETURNS text
	AS 
'
DECLARE
	catalog_name alias for $1;
	schema_name alias for $2;
	table_name alias for $3;
	column_name alias for $4;
	new_srid alias for $5;
	new_type alias for $6;
	new_dim alias for $7;
#if USE_VERSION >= 73
	rec RECORD;
	schema_ok bool;
	real_schema name;
#endif

BEGIN

	IF ( not ( (new_type =''GEOMETRY'') or
		   (new_type =''GEOMETRYCOLLECTION'') or
		   (new_type =''POINT'') or 
		   (new_type =''MULTIPOINT'') or
		   (new_type =''POLYGON'') or
		   (new_type =''MULTIPOLYGON'') or
		   (new_type =''LINESTRING'') or
		   (new_type =''MULTILINESTRING'') or
		   (new_type =''GEOMETRYCOLLECTIONM'') or
		   (new_type =''POINTM'') or 
		   (new_type =''MULTIPOINTM'') or
		   (new_type =''POLYGONM'') or
		   (new_type =''MULTIPOLYGONM'') or
		   (new_type =''LINESTRINGM'') or
		   (new_type =''MULTILINESTRINGM'')) )
	THEN
		RAISE EXCEPTION ''Invalid type name - valid ones are: 
			GEOMETRY, GEOMETRYCOLLECTION, POINT, 
			MULTIPOINT, POLYGON, MULTIPOLYGON, 
			LINESTRING, MULTILINESTRING,
			GEOMETRYCOLLECTIONM, POINTM, 
			MULTIPOINTM, POLYGONM, MULTIPOLYGONM, 
			LINESTRINGM, or MULTILINESTRINGM '';
		return ''fail'';
	END IF;

	IF ( (new_dim >4) or (new_dim <0) ) THEN
		RAISE EXCEPTION ''invalid dimension'';
		return ''fail'';
	END IF;

	IF ( (new_type LIKE ''%M'') and (new_dim!=3) ) THEN

		RAISE EXCEPTION ''TypeM needs 3 dimensions'';
		return ''fail'';
	END IF;

#if USE_VERSION >= 73
	IF ( schema_name != '''' ) THEN
		schema_ok = ''f'';
		FOR rec IN SELECT nspname FROM pg_namespace WHERE text(nspname) = schema_name LOOP
			schema_ok := ''t'';
		END LOOP;

		if ( schema_ok <> ''t'' ) THEN
			RAISE NOTICE ''Invalid schema name - using current_schema()'';
			SELECT current_schema() into real_schema;
		ELSE
			real_schema = schema_name;
		END IF;

	ELSE
		SELECT current_schema() into real_schema;
	END IF;
#endif


	-- Add geometry column

	EXECUTE ''ALTER TABLE '' ||
#if USE_VERSION >= 73
		quote_ident(real_schema) || ''.'' || quote_ident(table_name)
#else
		quote_ident(table_name)
#endif
		|| '' ADD COLUMN '' || quote_ident(column_name) || 
		'' geometry '';


	-- Delete stale record in geometry_column (if any)

	EXECUTE ''DELETE FROM geometry_columns WHERE
		f_table_catalog = '' || quote_literal('''') || 
		'' AND f_table_schema = '' ||
#if USE_VERSION >= 73
		quote_literal(real_schema) || 
#else
		quote_literal('''') || 
#endif
		'' AND f_table_name = '' || quote_literal(table_name) ||
		'' AND f_geometry_column = '' || quote_literal(column_name);


	-- Add record in geometry_column 

	EXECUTE ''INSERT INTO geometry_columns VALUES ('' ||
		quote_literal('''') || '','' ||
#if USE_VERSION >= 73
		quote_literal(real_schema) || '','' ||
#else
		quote_literal('''') || '','' ||
#endif
		quote_literal(table_name) || '','' ||
		quote_literal(column_name) || '','' ||
		new_dim || '','' || new_srid || '','' ||
		quote_literal(new_type) || '')'';

	-- Add table checks

	EXECUTE ''ALTER TABLE '' || 
#if USE_VERSION >= 73
		quote_ident(real_schema) || ''.'' || quote_ident(table_name)
#else
		quote_ident(table_name)
#endif
		|| '' ADD CONSTRAINT '' 
		|| quote_ident(''enforce_srid_'' || column_name)
		|| '' CHECK (SRID('' || quote_ident(column_name) ||
		'') = '' || new_srid || '')'' ;

	EXECUTE ''ALTER TABLE '' || 
#if USE_VERSION >= 73
		quote_ident(real_schema) || ''.'' || quote_ident(table_name)
#else
		quote_ident(table_name)
#endif
		|| '' ADD CONSTRAINT ''
		|| quote_ident(''enforce_dims_'' || column_name)
		|| '' CHECK (ndims('' || quote_ident(column_name) ||
		'') = '' || new_dim || '')'' ;

	IF (not(new_type = ''GEOMETRY'')) THEN
		EXECUTE ''ALTER TABLE '' || 
#if USE_VERSION >= 73
		quote_ident(real_schema) || ''.'' || quote_ident(table_name)
#else
		quote_ident(table_name)
#endif
		|| '' ADD CONSTRAINT ''
		|| quote_ident(''enforce_geotype_'' || column_name)
		|| '' CHECK (geometrytype('' ||
		quote_ident(column_name) || '')='' ||
		quote_literal(new_type) || '' OR ('' ||
		quote_ident(column_name) || '') is null)'';
	END IF;

	return 
#if USE_VERSION >= 73
		real_schema || ''.'' || 
#endif
		table_name || ''.'' || column_name ||
		'' SRID:'' || new_srid ||
		'' TYPE:'' || new_type || 
		'' DIMS:'' || new_dim || chr(10) || '' ''; 
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

----------------------------------------------------------------------------
-- ADDGEOMETRYCOLUMN ( <schema>, <table>, <column>, <srid>, <type>, <dim> )
----------------------------------------------------------------------------
--
-- This is a wrapper to the real AddGeometryColumn, for use
-- when catalogue is undefined
--
----------------------------------------------------------------------------
CREATEFUNCTION AddGeometryColumn(varchar,varchar,varchar,integer,varchar,integer) RETURNS text AS '
DECLARE
	ret  text;
BEGIN
	SELECT AddGeometryColumn('''',$1,$2,$3,$4,$5,$6) into ret;
	RETURN ret;
END;
'
LANGUAGE 'plpgsql' _STABLE_STRICT; -- WITH (isstrict);

----------------------------------------------------------------------------
-- ADDGEOMETRYCOLUMN ( <table>, <column>, <srid>, <type>, <dim> )
----------------------------------------------------------------------------
--
-- This is a wrapper to the real AddGeometryColumn, for use
-- when catalogue and schema are undefined
--
----------------------------------------------------------------------------
CREATEFUNCTION AddGeometryColumn(varchar,varchar,integer,varchar,integer) RETURNS text AS '
DECLARE
	ret  text;
BEGIN
	SELECT AddGeometryColumn('''','''',$1,$2,$3,$4,$5) into ret;
	RETURN ret;
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- DROPGEOMETRYCOLUMN
--   <catalogue>, <schema>, <table>, <column>
-----------------------------------------------------------------------
--
-- Removes geometry column reference from geometry_columns table.
-- Drops the column with pgsql >= 73.
-- Make some silly enforcements on it for pgsql < 73
--
-----------------------------------------------------------------------
CREATEFUNCTION DropGeometryColumn(varchar, varchar,varchar,varchar)
	RETURNS text
	AS 
'
DECLARE
	catalog_name alias for $1; 
	schema_name alias for $2;
	table_name alias for $3;
	column_name alias for $4;
	myrec RECORD;
	okay boolean;
	real_schema name;

BEGIN


#if USE_VERSION >= 73
	-- Find, check or fix schema_name
	IF ( schema_name != '''' ) THEN
		okay = ''f'';

		FOR myrec IN SELECT nspname FROM pg_namespace WHERE text(nspname) = schema_name LOOP
			okay := ''t'';
		END LOOP;

		IF ( okay <> ''t'' ) THEN
			RAISE NOTICE ''Invalid schema name - using current_schema()'';
			SELECT current_schema() into real_schema;
		ELSE
			real_schema = schema_name;
		END IF;
	ELSE
		SELECT current_schema() into real_schema;
	END IF;
#else
	real_schema = schema_name;
#endif

 	-- Find out if the column is in the geometry_columns table
	okay = ''f'';
	FOR myrec IN SELECT * from geometry_columns where f_table_schema = text(real_schema) and f_table_name = table_name and f_geometry_column = column_name LOOP
		okay := ''t'';
	END LOOP; 
	IF (okay <> ''t'') THEN 
		RAISE EXCEPTION ''column not found in geometry_columns table'';
		RETURN ''f'';
	END IF;

	-- Remove ref from geometry_columns table
	EXECUTE ''delete from geometry_columns where f_table_schema = '' ||
		quote_literal(real_schema) || '' and f_table_name = '' ||
		quote_literal(table_name)  || '' and f_geometry_column = '' ||
		quote_literal(column_name);
	
#if USE_VERSION < 73
	-- Remove not-null constraint to table column 
	EXECUTE ''update pg_attribute set attnotnull = false from pg_class where pg_attribute.attrelid = pg_class.oid and pg_class.relname = '' || quote_literal(table_name) ||'' and pg_attribute.attname = '' || quote_literal(column_name);
	-- update the given table/column so that it it all NULLS
	EXECUTE ''update "''||table_name||''" set "''||column_name||''"= NULL'';
	-- add = NULL constraint to given table/column
	EXECUTE ''ALTER TABLE "''||table_name||''" ADD CHECK ("''||column_name||''" IS NULL)'';
#else
	-- Remove table column
	EXECUTE ''ALTER TABLE '' || quote_ident(real_schema) || ''.'' ||
		quote_ident(table_name) || '' DROP COLUMN '' ||
		quote_ident(column_name);
#endif 


	RETURN real_schema || ''.'' || table_name || ''.'' || column_name ||'' effectively removed.'';
	
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- DROPGEOMETRYCOLUMN
--   <schema>, <table>, <column>
-----------------------------------------------------------------------
--
-- This is a wrapper to the real DropGeometryColumn, for use
-- when catalogue is undefined
--
-----------------------------------------------------------------------
CREATEFUNCTION DropGeometryColumn(varchar,varchar,varchar)
	RETURNS text
	AS 
'
DECLARE
	ret text;
BEGIN
	SELECT DropGeometryColumn('''',$1,$2,$3) into ret;
	RETURN ret;
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- DROPGEOMETRYCOLUMN
--   <table>, <column>
-----------------------------------------------------------------------
--
-- This is a wrapper to the real DropGeometryColumn, for use
-- when catalogue and schema is undefined. 
--
-----------------------------------------------------------------------
CREATEFUNCTION DropGeometryColumn(varchar,varchar)
	RETURNS text
	AS 
'
DECLARE
	ret text;
BEGIN
	SELECT DropGeometryColumn('''','''',$1,$2) into ret;
	RETURN ret;
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- DROPGEOMETRYTABLE
--   <catalogue>, <schema>, <table>
-----------------------------------------------------------------------
--
-- Drop a table and all its references in geometry_columns
--
-----------------------------------------------------------------------
CREATEFUNCTION DropGeometryTable(varchar, varchar,varchar)
	RETURNS text
	AS 
'
DECLARE
	catalog_name alias for $1; 
	schema_name alias for $2;
	table_name alias for $3;
	real_schema name;

BEGIN

#if USE_VERSION >= 73
	IF ( schema_name = '''' ) THEN
		SELECT current_schema() into real_schema;
	ELSE
		real_schema = schema_name;
	END IF;
#endif

	-- Remove refs from geometry_columns table
	EXECUTE ''DELETE FROM geometry_columns WHERE '' ||
#if USE_VERSION >= 73
		''f_table_schema = '' || quote_literal(real_schema) ||
		'' AND '' ||
#endif
		'' f_table_name = '' || quote_literal(table_name);
	
	-- Remove table 
	EXECUTE ''DROP TABLE ''
#if USE_VERSION >= 73
		|| quote_ident(real_schema) || ''.'' ||
#endif 
		quote_ident(table_name);

	RETURN
#if USE_VERSION >= 73
		real_schema || ''.'' ||
#endif 
		table_name ||'' dropped.'';
	
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- DROPGEOMETRYTABLE
--   <schema>, <table>
-----------------------------------------------------------------------
--
-- Drop a table and all its references in geometry_columns
--
-----------------------------------------------------------------------
CREATEFUNCTION DropGeometryTable(varchar,varchar) RETURNS text AS 
'SELECT DropGeometryTable('''',$1,$2)'
LANGUAGE 'sql' WITH (isstrict);

-----------------------------------------------------------------------
-- DROPGEOMETRYTABLE
--   <table>
-----------------------------------------------------------------------
--
-- Drop a table and all its references in geometry_columns
-- For PG>=73 use current_schema()
--
-----------------------------------------------------------------------
CREATEFUNCTION DropGeometryTable(varchar) RETURNS text AS 
'SELECT DropGeometryTable('''','''',$1)'
LANGUAGE 'sql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- UPDATEGEOMETRYSRID
--   <catalogue>, <schema>, <table>, <column>, <srid>
-----------------------------------------------------------------------
--
-- Change SRID of all features in a spatially-enabled table
--
-----------------------------------------------------------------------
CREATEFUNCTION UpdateGeometrySRID(varchar,varchar,varchar,varchar,integer)
	RETURNS text
	AS 
'
DECLARE
	catalog_name alias for $1; 
	schema_name alias for $2;
	table_name alias for $3;
	column_name alias for $4;
	new_srid alias for $5;
	myrec RECORD;
	okay boolean;
	cname varchar;
	real_schema name;

BEGIN


#if USE_VERSION >= 73
	-- Find, check or fix schema_name
	IF ( schema_name != '''' ) THEN
		okay = ''f'';

		FOR myrec IN SELECT nspname FROM pg_namespace WHERE text(nspname) = schema_name LOOP
			okay := ''t'';
		END LOOP;

		IF ( okay <> ''t'' ) THEN
			RAISE EXCEPTION ''Invalid schema name'';
		ELSE
			real_schema = schema_name;
		END IF;
	ELSE
		SELECT INTO real_schema current_schema()::text;
	END IF;
#endif

 	-- Find out if the column is in the geometry_columns table
	okay = ''f'';
	FOR myrec IN SELECT * from geometry_columns where f_table_schema = text(real_schema) and f_table_name = table_name and f_geometry_column = column_name LOOP
		okay := ''t'';
	END LOOP; 
	IF (okay <> ''t'') THEN 
		RAISE EXCEPTION ''column not found in geometry_columns table'';
		RETURN ''f'';
	END IF;

	-- Update ref from geometry_columns table
	EXECUTE ''UPDATE geometry_columns SET SRID = '' || new_srid || 
		'' where f_table_schema = '' ||
		quote_literal(real_schema) || '' and f_table_name = '' ||
		quote_literal(table_name)  || '' and f_geometry_column = '' ||
		quote_literal(column_name);
	
	-- Make up constraint name
	cname = ''enforce_srid_''  || column_name;

	-- Drop enforce_srid constraint
#if USE_VERSION < 73
	EXECUTE ''ALTER TABLE '' || quote_ident(table_name) ||
#else
	EXECUTE ''ALTER TABLE '' || quote_ident(real_schema) ||
		''.'' || quote_ident(table_name) ||
#endif
		'' DROP constraint '' || quote_ident(cname);

	-- Update geometries SRID
#if USE_VERSION < 73
	EXECUTE ''UPDATE '' || quote_ident(table_name) ||
#else
	EXECUTE ''UPDATE '' || quote_ident(real_schema) ||
		''.'' || quote_ident(table_name) ||
#endif
		'' SET '' || quote_ident(column_name) ||
		'' = setSRID('' || quote_ident(column_name) ||
		'', '' || new_srid || '')'';

	-- Reset enforce_srid constraint
#if USE_VERSION < 73
	EXECUTE ''ALTER TABLE '' || quote_ident(table_name) ||
#else
	EXECUTE ''ALTER TABLE '' || quote_ident(real_schema) ||
		''.'' || quote_ident(table_name) ||
#endif
		'' ADD constraint '' || quote_ident(cname) ||
		'' CHECK (srid('' || quote_ident(column_name) ||
		'') = '' || new_srid || '')'';

	RETURN real_schema || ''.'' || table_name || ''.'' || column_name ||'' SRID changed to '' || new_srid;
	
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- UPDATEGEOMETRYSRID
--   <schema>, <table>, <column>, <srid>
-----------------------------------------------------------------------
CREATEFUNCTION UpdateGeometrySRID(varchar,varchar,varchar,integer)
	RETURNS text
	AS '
DECLARE
	ret  text;
BEGIN
	SELECT UpdateGeometrySRID('''',$1,$2,$3,$4) into ret;
	RETURN ret;
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- UPDATEGEOMETRYSRID
--   <table>, <column>, <srid>
-----------------------------------------------------------------------
CREATEFUNCTION UpdateGeometrySRID(varchar,varchar,integer)
	RETURNS text
	AS '
DECLARE
	ret  text;
BEGIN
	SELECT UpdateGeometrySRID('''','''',$1,$2,$3) into ret;
	RETURN ret;
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; -- WITH (isstrict);

-----------------------------------------------------------------------
-- UPDATE_GEOMETRY_STATS()
-----------------------------------------------------------------------
--
-- Only meaningful for PG<75.
-- Gather statisticts about geometry columns for use
-- with cost estimator.
--
-- It is defined also for PG>=75 for back-compatibility
--
-----------------------------------------------------------------------
#if USE_VERSION >= 80
CREATEFUNCTION update_geometry_stats() RETURNS text
AS ' SELECT ''update_geometry_stats() has been obsoleted. Statistics are automatically built running the ANALYZE command''::text' LANGUAGE 'sql';
#else
CREATEFUNCTION update_geometry_stats()
RETURNS text
AS
'
DECLARE
	result text;
	stated integer;
BEGIN

	UPDATE geometry_columns SET
#if USE_VERSION >= 73
		stats = (build_histogram2d(create_histogram2d(
			find_extent(f_table_schema, f_table_name, f_geometry_column), 40), f_table_schema, f_table_name, f_geometry_column))
		FROM pg_class c, pg_attribute a, pg_namespace n
		WHERE n.nspname = f_table_schema::name
		AND c.relname = f_table_name::name
		AND c.relnamespace = n.oid
#else
		stats = (build_histogram2d(create_histogram2d(
			find_extent(f_table_name, f_geometry_column),
			40), f_table_name, f_geometry_column))
		FROM pg_class c, pg_attribute a
		WHERE c.relname = f_table_name::name
#endif
		AND a.attname = f_geometry_column::name
		AND a.attrelid = c.oid
		AND geometry_columns.attrelid is not null;

	GET DIAGNOSTICS stated = ROW_COUNT;

	result = ''stats:'' || stated::text;

	return result;
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT; 
#endif

-----------------------------------------------------------------------
-- UPDATE_GEOMETRY_STATS( <table>, <column> )
-----------------------------------------------------------------------
--
-- Only meaningful for PG<75.
-- Gather statisticts about a geometry column for use
-- with cost estimator.
--
-- It is defined also for PG>=75 for back-compatibility
--
-----------------------------------------------------------------------
#if USE_VERSION >= 80
CREATEFUNCTION update_geometry_stats(varchar,varchar) RETURNS text
AS 'SELECT update_geometry_stats();' LANGUAGE 'sql' ;
#else
CREATEFUNCTION update_geometry_stats(varchar,varchar) RETURNS text
AS
'
DECLARE
	tablename aliAS for $1;
	columnname aliAS for $2;
	stated integer;
	result text;
BEGIN

	EXECUTE ''UPDATE geometry_columns SET
#if USE_VERSION >= 73
			stats = (build_histogram2d(create_histogram2d(
				find_extent(f_table_schema,
					f_table_name,
					f_geometry_column), 40),
					f_table_schema, f_table_name,
					f_geometry_column))
			FROM pg_class c, pg_attribute a, pg_namespace n
			WHERE n.nspname = f_table_schema::name
			AND c.relname = f_table_name::name
			AND a.attname = f_geometry_column::name
			AND c.relnamespace = n.oid
			AND a.attrelid = c.oid
#else
			stats = (build_histogram2d(create_histogram2d(
				find_extent(f_table_name, f_geometry_column),
				40), f_table_name, f_geometry_column))
			FROM pg_class c, pg_attribute a
			WHERE c.relname = f_table_name::name
			AND a.attname = f_geometry_column::name
			AND a.attrelid = c.oid
#endif
			AND f_table_name = '' || quote_literal(tablename) || ''
			AND f_geometry_column = '' || quote_literal(columnname)
			|| '' AND geometry_columns.attrelid is not null'';

	GET DIAGNOSTICS stated = ROW_COUNT;

	result = ''stats:'' || stated::text;

	return result;
END;
'
LANGUAGE 'plpgsql' _VOLATILE_STRICT;

#endif 

-----------------------------------------------------------------------
-- FIND_SRID( <schema>, <table>, <geom col> )
-----------------------------------------------------------------------
CREATEFUNCTION find_srid(varchar,varchar,varchar) RETURNS int4 AS
'DECLARE
   schem text;
   tabl text;
   sr int4;
BEGIN
   IF $1 IS NULL THEN
      RAISE EXCEPTION ''find_srid() - schema is NULL!'';
   END IF;
   IF $2 IS NULL THEN
      RAISE EXCEPTION ''find_srid() - table name is NULL!'';
   END IF;
   IF $3 IS NULL THEN
      RAISE EXCEPTION ''find_srid() - column name is NULL!'';
   END IF;
   schem = $1;
   tabl = $2;
-- if the table contains a . and the schema is empty
-- split the table into a schema and a table
-- otherwise drop through to default behavior
   IF ( schem = '''' and tabl LIKE ''%.%'' ) THEN
     schem = substr(tabl,1,strpos(tabl,''.'')-1);
     tabl = substr(tabl,length(schem)+2);
   ELSE
     schem = schem || ''%'';
   END IF;

   select SRID into sr from geometry_columns where f_table_schema like schem and f_table_name = tabl and f_geometry_column = $3;
   IF NOT FOUND THEN
       RAISE EXCEPTION ''find_srid() - couldnt find the corresponding SRID - is the geometry registered in the GEOMETRY_COLUMNS table?  Is there an uppercase/lowercase missmatch?'';
   END IF;
  return sr;
END;
'
LANGUAGE 'plpgsql' _IMMUTABLE_STRICT; -- WITH (iscachable); 


---------------------------------------------------------------
-- PROJ support
---------------------------------------------------------------

CREATEFUNCTION get_proj4_from_srid(integer) RETURNS text AS
'
BEGIN
	RETURN proj4text::text FROM spatial_ref_sys WHERE srid= $1;
END;
'
LANGUAGE 'plpgsql' _IMMUTABLE_STRICT; -- WITH (iscachable,isstrict);



CREATEFUNCTION transform_geometry(geometry,text,text,int)
	RETURNS geometry
	AS '@MODULE_FILENAME@','transform_geom'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION transform(geometry,integer)
	RETURNS geometry
	AS '@MODULE_FILENAME@','transform'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);


-----------------------------------------------------------------------
-- POSTGIS_VERSION()
-----------------------------------------------------------------------

CREATEFUNCTION postgis_version() RETURNS text
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE;

CREATEFUNCTION postgis_proj_version() RETURNS text
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE;

--
-- IMPORTANT:
-- Starting at 1.1.0 this function is used by postgis_proc_upgrade.pl
-- to extract version of postgis being installed.
-- Do not modify this w/out also changing postgis_proc_upgrade.pl
--
CREATEFUNCTION postgis_scripts_installed() RETURNS text
        AS 'SELECT ''@POSTGIS_SCRIPTS_VERSION@''::text AS version'
        LANGUAGE 'sql' _IMMUTABLE;

CREATEFUNCTION postgis_lib_version() RETURNS text
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE; -- a new lib will require a new session

-- NOTE: starting at 1.1.0 this is the same of postgis_lib_version()
CREATEFUNCTION postgis_scripts_released() RETURNS text
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE;

CREATEFUNCTION postgis_uses_stats() RETURNS bool
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE;

CREATEFUNCTION postgis_geos_version() RETURNS text
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE;

CREATEFUNCTION postgis_jts_version() RETURNS text
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE;

CREATEFUNCTION postgis_scripts_build_date() RETURNS text
        AS 'SELECT ''@POSTGIS_BUILD_DATE@''::text AS version'
        LANGUAGE 'sql' _IMMUTABLE;

CREATEFUNCTION postgis_lib_build_date() RETURNS text
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE;



CREATEFUNCTION postgis_full_version() RETURNS text
AS '
DECLARE
	libver text;
	projver text;
	geosver text;
	jtsver text;
	usestats bool;
	dbproc text;
	relproc text;
	fullver text;
BEGIN
	SELECT postgis_lib_version() INTO libver;
	SELECT postgis_proj_version() INTO projver;
	SELECT postgis_geos_version() INTO geosver;
	SELECT postgis_jts_version() INTO jtsver;
	SELECT postgis_uses_stats() INTO usestats;
	SELECT postgis_scripts_installed() INTO dbproc;
	SELECT postgis_scripts_released() INTO relproc;

	fullver = ''POSTGIS="'' || libver || ''"'';

	IF  geosver IS NOT NULL THEN
		fullver = fullver || '' GEOS="'' || geosver || ''"'';
	END IF;

	IF  jtsver IS NOT NULL THEN
		fullver = fullver || '' JTS="'' || jtsver || ''"'';
	END IF;

	IF  projver IS NOT NULL THEN
		fullver = fullver || '' PROJ="'' || projver || ''"'';
	END IF;

	IF usestats THEN
		fullver = fullver || '' USE_STATS'';
	END IF;

	-- fullver = fullver || '' DBPROC="'' || dbproc || ''"'';
	-- fullver = fullver || '' RELPROC="'' || relproc || ''"'';

	IF dbproc != relproc THEN
		fullver = fullver || '' (procs from '' || dbproc || '' need upgrade)'';
	END IF;

	RETURN fullver;
END
'
LANGUAGE 'plpgsql' _IMMUTABLE;

---------------------------------------------------------------
-- CASTS
---------------------------------------------------------------

CREATEFUNCTION box2d(geometry)
        RETURNS box2d
        AS '@MODULE_FILENAME@','LWGEOM_to_BOX2DFLOAT4'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box3d(geometry)
        RETURNS box3d
        AS '@MODULE_FILENAME@','LWGEOM_to_BOX3D'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box(geometry)
        RETURNS box
        AS '@MODULE_FILENAME@','LWGEOM_to_BOX'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box2d(box3d)
        RETURNS box2d
        AS '@MODULE_FILENAME@','BOX3D_to_BOX2DFLOAT4'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box3d(box2d)
        RETURNS box3d
        AS '@MODULE_FILENAME@','BOX2DFLOAT4_to_BOX3D'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION box(box3d)
        RETURNS box
        AS '@MODULE_FILENAME@','BOX3D_to_BOX'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION text(geometry)
        RETURNS text
        AS '@MODULE_FILENAME@','LWGEOM_to_text'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- this is kept for backward-compatibility
CREATEFUNCTION box3dtobox(box3d)
        RETURNS box
        AS 'SELECT box($1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry(box2d)
        RETURNS geometry
        AS '@MODULE_FILENAME@','BOX2DFLOAT4_to_LWGEOM'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry(box3d)
        RETURNS geometry
        AS '@MODULE_FILENAME@','BOX3D_to_LWGEOM'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry(text)
        RETURNS geometry
        AS '@MODULE_FILENAME@','parse_WKT_lwgeom'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry(chip)
	RETURNS geometry
	AS '@MODULE_FILENAME@','CHIP_to_LWGEOM'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION geometry(bytea)
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_from_bytea'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION bytea(geometry)
	RETURNS bytea
	AS '@MODULE_FILENAME@','LWGEOM_to_bytea'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION text(bool)
	RETURNS text
	AS '@MODULE_FILENAME@','BOOL_to_text'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- 7.3+ explicit casting definitions
#if USE_VERSION >= 73
CREATE CAST (geometry AS box2d) WITH FUNCTION box2d(geometry) AS IMPLICIT;
CREATE CAST (geometry AS box3d) WITH FUNCTION box3d(geometry) AS IMPLICIT;
CREATE CAST (geometry AS box) WITH FUNCTION box(geometry) AS IMPLICIT;
CREATE CAST (box3d AS box2d) WITH FUNCTION box2d(box3d) AS IMPLICIT;
CREATE CAST (box2d AS box3d) WITH FUNCTION box3d(box2d) AS IMPLICIT;
CREATE CAST (box2d AS geometry) WITH FUNCTION geometry(box2d) AS IMPLICIT;
CREATE CAST (box3d AS box) WITH FUNCTION box(box3d) AS IMPLICIT;
CREATE CAST (box3d AS geometry) WITH FUNCTION geometry(box3d) AS IMPLICIT;
CREATE CAST (text AS geometry) WITH FUNCTION geometry(text) AS IMPLICIT;
CREATE CAST (geometry AS text) WITH FUNCTION text(geometry) AS IMPLICIT;
CREATE CAST (chip AS geometry) WITH FUNCTION geometry(chip) AS IMPLICIT;
CREATE CAST (bytea AS geometry) WITH FUNCTION geometry(bytea) AS IMPLICIT;
CREATE CAST (geometry AS bytea) WITH FUNCTION bytea(geometry) AS IMPLICIT;
CREATE CAST (bool AS text) WITH FUNCTION text(bool) AS IMPLICIT;
#endif

---------------------------------------------------------------
-- Algorithms
---------------------------------------------------------------

CREATEFUNCTION simplify(geometry, float8)
   RETURNS geometry
   AS '@MODULE_FILENAME@', 'LWGEOM_simplify2d'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- SnapToGrid(input, xoff, yoff, xsize, ysize)
CREATEFUNCTION SnapToGrid(geometry, float8, float8, float8, float8)
   RETURNS geometry
   AS '@MODULE_FILENAME@', 'LWGEOM_snaptogrid'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- SnapToGrid(input, xsize, ysize) # offsets=0
CREATEFUNCTION SnapToGrid(geometry, float8, float8)
   RETURNS geometry
   AS 'SELECT SnapToGrid($1, 0, 0, $2, $3)'
   LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- SnapToGrid(input, size) # xsize=ysize=size, offsets=0
CREATEFUNCTION SnapToGrid(geometry, float8)
   RETURNS geometry
   AS 'SELECT SnapToGrid($1, 0, 0, $2, $2)'
   LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- SnapToGrid(input, point_offsets, xsize, ysize, zsize, msize)
CREATEFUNCTION SnapToGrid(geometry, geometry, float8, float8, float8, float8)
   RETURNS geometry
   AS '@MODULE_FILENAME@', 'LWGEOM_snaptogrid_pointoff'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION segmentize(geometry, float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_segmentize2d'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

---------------------------------------------------------------
-- LRS
---------------------------------------------------------------

CREATEFUNCTION line_interpolate_point(geometry, float8)
   RETURNS geometry
   AS '@MODULE_FILENAME@', 'LWGEOM_line_interpolate_point'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION line_substring(geometry, float8, float8)
   RETURNS geometry
   AS '@MODULE_FILENAME@', 'LWGEOM_line_substring'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION line_locate_point(geometry, geometry)
   RETURNS float8
   AS '@MODULE_FILENAME@', 'LWGEOM_line_locate_point'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION locate_between_measures(geometry, float8, float8)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_locate_between_m'
	LANGUAGE 'C' _IMMUTABLE_STRICT;

CREATEFUNCTION locate_along_measure(geometry, float8)
	RETURNS geometry
	AS 'SELECT locate_between_measures($1, $2, $2)'
	LANGUAGE 'sql' _IMMUTABLE_STRICT;

---------------------------------------------------------------
-- GEOS
---------------------------------------------------------------

CREATEFUNCTION intersection(geometry,geometry)
   RETURNS geometry
   AS '@MODULE_FILENAME@','intersection'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION buffer(geometry,float8)
   RETURNS geometry
   AS '@MODULE_FILENAME@','buffer'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION buffer(geometry,float8,integer)
   RETURNS geometry
   AS '@MODULE_FILENAME@','buffer'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);
   
CREATEFUNCTION convexhull(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@','convexhull'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);
  
  
CREATEFUNCTION difference(geometry,geometry)
	RETURNS geometry
        AS '@MODULE_FILENAME@','difference'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);
   
CREATEFUNCTION boundary(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@','boundary'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION symdifference(geometry,geometry)
        RETURNS geometry
        AS '@MODULE_FILENAME@','symdifference'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);


CREATEFUNCTION symmetricdifference(geometry,geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@','symdifference'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);


CREATEFUNCTION GeomUnion(geometry,geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@','geomunion'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATE AGGREGATE MemGeomUnion (
	basetype = geometry,
	sfunc = geomunion,
	stype = geometry
	);

CREATEFUNCTION unite_garray (geometry[])
	RETURNS geometry
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable); 

CREATE AGGREGATE GeomUnion (
	sfunc = geom_accum,
	basetype = geometry,
	stype = geometry[],
	finalfunc = unite_garray
	);


CREATEFUNCTION relate(geometry,geometry)
   RETURNS text
   AS '@MODULE_FILENAME@','relate_full'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION relate(geometry,geometry,text)
   RETURNS boolean
   AS '@MODULE_FILENAME@','relate_pattern'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION disjoint(geometry,geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION touches(geometry,geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION intersects(geometry,geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION crosses(geometry,geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION within(geometry,geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION contains(geometry,geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION overlaps(geometry,geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION IsValid(geometry)
   RETURNS boolean
   AS '@MODULE_FILENAME@', 'isvalid'
   LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GEOSnoop(geometry)
   RETURNS geometry
   AS '@MODULE_FILENAME@', 'GEOSnoop'
   LANGUAGE 'C' _VOLATILE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION JTSnoop(geometry)
   RETURNS geometry
   AS '@MODULE_FILENAME@', 'JTSnoop'
   LANGUAGE 'C' _VOLATILE_STRICT; -- WITH (isstrict,iscachable);

-- This is also available w/out GEOS 
CREATEFUNCTION Centroid(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION IsRing(geometry)
	RETURNS boolean
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PointOnSurface(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);
	
CREATEFUNCTION IsSimple(geometry)
	RETURNS boolean
	AS '@MODULE_FILENAME@', 'issimple'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION Equals(geometry,geometry)
	RETURNS boolean
	AS '@MODULE_FILENAME@','geomequals'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-----------------------------------------------------------------------
-- SVG OUTPUT
-----------------------------------------------------------------------
CREATEFUNCTION AsSVG(geometry,int4,int4)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','assvg_geometry'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsSVG(geometry,int4)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','assvg_geometry'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsSVG(geometry)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','assvg_geometry'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-----------------------------------------------------------------------
-- GML OUTPUT
-----------------------------------------------------------------------
-- AsGML(geom, precision, version)
CREATEFUNCTION AsGML(geometry, int4, int4)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','LWGEOM_asGML'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- AsGML(geom, precision) / version=2
CREATEFUNCTION AsGML(geometry, int4)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','LWGEOM_asGML'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

-- AsGML(geom) / precision=15 version=2
CREATEFUNCTION AsGML(geometry)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','LWGEOM_asGML'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

------------------------------------------------------------------------
-- OGC defined
------------------------------------------------------------------------

CREATEFUNCTION NumPoints(geometry)
	RETURNS int4
	AS '@MODULE_FILENAME@', 'LWGEOM_numpoints_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION NumGeometries(geometry)
	RETURNS int4
	AS '@MODULE_FILENAME@', 'LWGEOM_numgeometries_collection'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION GeometryN(geometry,integer)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_geometryn_collection'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION Dimension(geometry)
	RETURNS int4
	AS '@MODULE_FILENAME@', 'LWGEOM_dimension'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION ExterioRring(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_exteriorring_polygon'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION NumInteriorRings(geometry)
	RETURNS integer
	AS '@MODULE_FILENAME@','LWGEOM_numinteriorrings_polygon'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION NumInteriorRing(geometry)
	RETURNS integer
	AS '@MODULE_FILENAME@','LWGEOM_numinteriorrings_polygon'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION InteriorRingN(geometry,integer)
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_interiorringn_polygon'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION GeometryType(geometry)
	RETURNS text
	AS '@MODULE_FILENAME@', 'LWGEOM_getTYPE'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION PointN(geometry,integer)
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_pointn_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION X(geometry)
	RETURNS float8
	AS '@MODULE_FILENAME@','LWGEOM_x_point'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION Y(geometry)
	RETURNS float8
	AS '@MODULE_FILENAME@','LWGEOM_y_point'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION Z(geometry)
	RETURNS float8
	AS '@MODULE_FILENAME@','LWGEOM_z_point'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION M(geometry)
	RETURNS float8
	AS '@MODULE_FILENAME@','LWGEOM_m_point'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION StartPoint(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_startpoint_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION EndPoint(geometry)
	RETURNS geometry
	AS '@MODULE_FILENAME@', 'LWGEOM_endpoint_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION IsClosed(geometry)
	RETURNS boolean
	AS '@MODULE_FILENAME@', 'LWGEOM_isclosed_linestring'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION IsEmpty(geometry)
	RETURNS boolean
	AS '@MODULE_FILENAME@', 'LWGEOM_isempty'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict);

CREATEFUNCTION SRID(geometry) 
	RETURNS int4
	AS '@MODULE_FILENAME@','LWGEOM_getSRID'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);
	
CREATEFUNCTION SetSRID(geometry,int4) 
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_setSRID'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);	
	
CREATEFUNCTION AsBinary(geometry)
	RETURNS bytea
	AS '@MODULE_FILENAME@','LWGEOM_asBinary'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsBinary(geometry,text)
	RETURNS bytea
	AS '@MODULE_FILENAME@','LWGEOM_asBinary'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION AsText(geometry)
	RETURNS TEXT
	AS '@MODULE_FILENAME@','LWGEOM_asText'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeometryFromText(text)
        RETURNS geometry
        AS '@MODULE_FILENAME@','LWGEOM_from_text'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeometryFromText(text, int4)
        RETURNS geometry
        AS '@MODULE_FILENAME@','LWGEOM_from_text'
        LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomFromText(text)
	RETURNS geometry AS 'SELECT geometryfromtext($1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomFromText(text, int4)
	RETURNS geometry AS 'SELECT geometryfromtext($1, $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PointFromText(text)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1)) = ''POINT''
	THEN GeomFromText($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PointFromText(text, int4)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1, $2)) = ''POINT''
	THEN GeomFromText($1,$2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LineFromText(text)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1)) = ''LINESTRING''
	THEN GeomFromText($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LineFromText(text, int4)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1, $2)) = ''LINESTRING''
	THEN GeomFromText($1,$2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LineStringFromText(text)
	RETURNS geometry
	AS 'SELECT LineFromText($1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LineStringFromText(text, int4)
	RETURNS geometry
	AS 'SELECT LineFromText($1, $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolyFromText(text)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1)) = ''POLYGON''
	THEN GeomFromText($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolyFromText(text, int4)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1, $2)) = ''POLYGON''
	THEN GeomFromText($1,$2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolygonFromText(text, int4)
	RETURNS geometry
	AS 'SELECT PolyFromText($1, $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolygonFromText(text)
	RETURNS geometry
	AS 'SELECT PolyFromText($1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MLineFromText(text, int4)
	RETURNS geometry
	AS '
	SELECT CASE
	WHEN geometrytype(GeomFromText($1, $2)) = ''MULTILINESTRING''
	THEN GeomFromText($1,$2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MLineFromText(text)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1)) = ''MULTILINESTRING''
	THEN GeomFromText($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiLineStringFromText(text)
	RETURNS geometry
	AS 'SELECT MLineFromText($1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiLineStringFromText(text, int4)
	RETURNS geometry
	AS 'SELECT MLineFromText($1, $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPointFromText(text, int4)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1,$2)) = ''MULTIPOINT''
	THEN GeomFromText($1,$2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPointFromText(text)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1)) = ''MULTIPOINT''
	THEN GeomFromText($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPointFromText(text, int4)
	RETURNS geometry
	AS 'SELECT MPointFromText($1, $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPointFromText(text)
	RETURNS geometry
	AS 'SELECT MPointFromText($1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPolyFromText(text, int4)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1, $2)) = ''MULTIPOLYGON''
	THEN GeomFromText($1,$2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPolyFromText(text)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromText($1)) = ''MULTIPOLYGON''
	THEN GeomFromText($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPolygonFromText(text, int4)
	RETURNS geometry
	AS 'SELECT MPolyFromText($1, $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPolygonFromText(text)
	RETURNS geometry
	AS 'SELECT MPolyFromText($1)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomCollFromText(text, int4)
	RETURNS geometry
	AS '
	SELECT CASE
	WHEN geometrytype(GeomFromText($1, $2)) = ''GEOMETRYCOLLECTION''
	THEN GeomFromText($1,$2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomCollFromText(text)
	RETURNS geometry
	AS '
	SELECT CASE
	WHEN geometrytype(GeomFromText($1)) = ''GEOMETRYCOLLECTION''
	THEN GeomFromText($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomFromWKB(bytea)
	RETURNS geometry
	AS '@MODULE_FILENAME@','LWGEOM_from_WKB'
	LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomFromWKB(bytea, int)
	RETURNS geometry
	AS 'SELECT setSRID(GeomFromWKB($1), $2)'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PointFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''POINT''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PointFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''POINT''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LineFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''LINESTRING''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LineFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''LINESTRING''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LinestringFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''LINESTRING''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION LinestringFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''LINESTRING''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolyFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''POLYGON''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolyFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''POLYGON''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolygonFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1,$2)) = ''POLYGON''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION PolygonFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''POLYGON''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPointFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1,$2)) = ''MULTIPOINT''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPointFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''MULTIPOINT''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPointFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1,$2)) = ''MULTIPOINT''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPointFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''MULTIPOINT''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiLineFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''MULTILINESTRING''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiLineFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''MULTILINESTRING''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MLineFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''MULTILINESTRING''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MLineFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''MULTILINESTRING''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPolyFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''MULTIPOLYGON''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MPolyFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''MULTIPOLYGON''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPolyFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1, $2)) = ''MULTIPOLYGON''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION MultiPolyFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE WHEN geometrytype(GeomFromWKB($1)) = ''MULTIPOLYGON''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomCollFromWKB(bytea, int)
	RETURNS geometry
	AS '
	SELECT CASE
	WHEN geometrytype(GeomFromWKB($1, $2)) = ''GEOMETRYCOLLECTION''
	THEN GeomFromWKB($1, $2)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

CREATEFUNCTION GeomCollFromWKB(bytea)
	RETURNS geometry
	AS '
	SELECT CASE
	WHEN geometrytype(GeomFromWKB($1)) = ''GEOMETRYCOLLECTION''
	THEN GeomFromWKB($1)
	ELSE NULL END
	'
	LANGUAGE 'SQL' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);

--
-- SFSQL 1.1
--
-- BdPolyFromText(multiLineStringTaggedText String, SRID Integer): Polygon
--
--  Construct a Polygon given an arbitrary
--  collection of closed linestrings as a
--  MultiLineString text representation.
--
-- This is a PLPGSQL function rather then an SQL function
-- To avoid double call of BuildArea (one to get GeometryType
-- and another to actual return, in a CASE WHEN construct).
-- Also, we profit from plpgsql to RAISE exceptions.
--
CREATE OR REPLACE FUNCTION BdPolyFromText(text, integer)
RETURNS geometry
AS '
DECLARE
	geomtext alias for $1;
	srid alias for $2;
	mline geometry;
	geom geometry;
BEGIN
	mline := MultiLineStringFromText(geomtext, srid);

	IF mline IS NULL
	THEN
		RAISE EXCEPTION ''Input is not a MultiLinestring'';
	END IF;

	geom := BuildArea(mline);

	IF GeometryType(geom) != ''POLYGON''
	THEN
		RAISE EXCEPTION ''Input returns more then a single polygon, try using BdMPolyFromText instead'';
	END IF;

	RETURN geom;
END;
'
LANGUAGE 'plpgsql' _IMMUTABLE_STRICT; 

--
-- SFSQL 1.1
--
-- BdMPolyFromText(multiLineStringTaggedText String, SRID Integer): MultiPolygon
--
--  Construct a MultiPolygon given an arbitrary
--  collection of closed linestrings as a
--  MultiLineString text representation.
--
-- This is a PLPGSQL function rather then an SQL function
-- To raise an exception in case of invalid input.
--
CREATEFUNCTION BdMPolyFromText(text, integer)
RETURNS geometry
AS '
DECLARE
	geomtext alias for $1;
	srid alias for $2;
	mline geometry;
	geom geometry;
BEGIN
	mline := MultiLineStringFromText(geomtext, srid);

	IF mline IS NULL
	THEN
		RAISE EXCEPTION ''Input is not a MultiLinestring'';
	END IF;

	geom := multi(BuildArea(mline));

	RETURN geom;
END;
'
LANGUAGE 'plpgsql' _IMMUTABLE_STRICT; 

#include "long_xact.sql"

---------------------------------------------------------------
-- END
---------------------------------------------------------------

COMMIT;

