[postgis-commits] svn - r2797 - in trunk: . lwgeom

postgis-commits at postgis.refractions.net postgis-commits at postgis.refractions.net
Sat May 31 02:56:46 PDT 2008


Author: mcayland
Date: 2008-05-31 02:56:44 -0700 (Sat, 31 May 2008)
New Revision: 2797

Modified:
   trunk/configure.in
   trunk/lwgeom/liblwgeom.c
   trunk/lwgeom/liblwgeom.h
   trunk/lwgeom/long_xact.c
   trunk/lwgeom/lwcollection.c
   trunk/lwgeom/lwcompound.c
   trunk/lwgeom/lwcurve.c
   trunk/lwgeom/lwcurvepoly.c
   trunk/lwgeom/lwgeom.c
   trunk/lwgeom/lwgeom_api.c
   trunk/lwgeom/lwgeom_box2dfloat4.c
   trunk/lwgeom/lwgeom_box3d.c
   trunk/lwgeom/lwgeom_btree.c
   trunk/lwgeom/lwgeom_debug.c
   trunk/lwgeom/lwgeom_dump.c
   trunk/lwgeom/lwgeom_estimate.c
   trunk/lwgeom/lwgeom_functions_analytic.c
   trunk/lwgeom/lwgeom_functions_basic.c
   trunk/lwgeom/lwgeom_functions_lrs.c
   trunk/lwgeom/lwgeom_geos_c.c
   trunk/lwgeom/lwgeom_gist.c
   trunk/lwgeom/lwgeom_gml.c
   trunk/lwgeom/lwgeom_inout.c
   trunk/lwgeom/lwgeom_ogc.c
   trunk/lwgeom/lwgeom_pg.c
   trunk/lwgeom/lwgeom_pg.h
   trunk/lwgeom/lwgeom_rtree.c
   trunk/lwgeom/lwgeom_spheroid.c
   trunk/lwgeom/lwgeom_sqlmm.c
   trunk/lwgeom/lwgeom_transform.c
   trunk/lwgeom/lwgparse.c
   trunk/lwgeom/lwline.c
   trunk/lwgeom/lwmpoly.c
   trunk/lwgeom/lwmsurface.c
   trunk/lwgeom/lwpoint.c
   trunk/lwgeom/lwpoly.c
   trunk/lwgeom/lwpostgis.sql.in.c
   trunk/lwgeom/measures.c
   trunk/lwgeom/ptarray.c
   trunk/postgis_config.h.in
Log:
Commit new PostGIS debugging infrastructure. These changes unify all the debug logging to use a new set of macros: LWDEBUG()/LWDEBUGF() for LWGEOM functions, and POSTGIS_DEBUG()/POSTGIS_DEBUGF() for PostgreSQL functions. To enable debugging, run configure with --enable-debug and then remake the entire project. If --enable-debug is omitted during configure, the above macros evaluate to (void)0, and hence should be removed by the compiler during optimisation. Also: contains minor warning cleanups and a fix for the ST_Dwithin SQL definition.

Modified: trunk/configure.in
===================================================================
--- trunk/configure.in	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/configure.in	2008-05-31 09:56:44 UTC (rev 2797)
@@ -301,6 +301,26 @@
 
 
 dnl
+dnl Allow the user to enable debugging with --enable-debug
+dnl
+dnl Currently 5 levels are defined (each increasing in complexity):
+dnl   - 1: Reserved 
+dnl   - 2: Output function names upon entry (where defined) 
+dnl   - 3: Normal function debugging 
+dnl   - 4: Verbose function debugging 
+dnl   - 5: Memory allocation/deallocation calls
+dnl
+dnl All levels include the output of all preceding levels. We default to level 4, but the
+dnl developer is encouraged to manually alter postgis_config.h as required.
+dnl
+
+AC_ARG_ENABLE([debug], AC_HELP_STRING([--enable-debug], [Enable verbose debugging messages]), 
+	[POSTGIS_DEBUG_LEVEL=4], [POSTGIS_DEBUG_LEVEL=0]) 
+
+AC_DEFINE_UNQUOTED([POSTGIS_DEBUG_LEVEL], [$POSTGIS_DEBUG_LEVEL], [PostGIS library debug level (0=disabled)])
+
+
+dnl
 dnl Define version macros
 dnl
 

Modified: trunk/lwgeom/liblwgeom.c
===================================================================
--- trunk/lwgeom/liblwgeom.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/liblwgeom.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -5,7 +5,6 @@
 #define CONTEXT_PG 0
 #define CONTEXT_SA 1
 
-/* #define PGIS_DEBUG_ALLOCS 1 */
 
 
 #ifdef STANDALONE
@@ -35,6 +34,7 @@
 lwreporter lwnotice = pg_notice;
 #endif
 
+
 static char *lwgeomTypeName[] = {
 	"Unknown",
 	"Point",
@@ -133,21 +133,15 @@
 void *
 lwalloc(size_t size)
 {
-#ifdef PGIS_DEBUG_ALLOCS
 	void *mem = lwalloc_var(size);
-	lwnotice("lwalloc: %d@%p", size, mem);
+	LWDEBUGF(5, "lwalloc: %d@%p", size, mem);
 	return mem;
-#else /* ! PGIS_DEBUG_ALLOCS */
-	return lwalloc_var(size);
-#endif
 }
 
 void *
 lwrealloc(void *mem, size_t size)
 {
-#ifdef PGIS_DEBUG_ALLOCS
-	lwnotice("lwrealloc: %d@%p", size, mem);
-#endif
+	LWDEBUGF(5, "lwrealloc: %d@%p", size, mem);
 	return lwrealloc_var(mem, size);
 }
 
@@ -168,16 +162,12 @@
 	int len;
 	int i;
 
-#ifdef PGIS_DEBUG
-	lwnotice("input: %s", str);
-#endif
+	LWDEBUGF(3, "input: %s", str);
 	
 	ptr = strchr(str, '.');
 	if ( ! ptr ) return; /* no dot, no decimal digits */
 
-#ifdef PGIS_DEBUG
-	lwnotice("ptr: %s", ptr);
-#endif
+	LWDEBUGF(3, "ptr: %s", ptr);
 
 	len = strlen(ptr);
 	for (i=len-1; i; i--)
@@ -191,9 +181,7 @@
 		else *totrim = '\0';
 	}
 	
-#ifdef PGIS_DEBUG
-	lwnotice("output: %s", str);
-#endif
+	LWDEBUGF(3, "output: %s", str);
 }
 
 char

Modified: trunk/lwgeom/liblwgeom.h
===================================================================
--- trunk/lwgeom/liblwgeom.h	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/liblwgeom.h	2008-05-31 09:56:44 UTC (rev 2797)
@@ -1,15 +1,11 @@
 #ifndef _LIBLWGEOM_H
 #define _LIBLWGEOM_H 1
 
+#include "../postgis_config.h"
 #include <stdio.h>
 #include "compat.h"
 
 #define INTEGRITY_CHECKS 1
-/* #define DEBUG_ALLOCS 1 */
-/* #define PGIS_DEBUG 1
-#define PGIS_DEBUG_CALLS 1 */
-/*#define PGIS_DEBUG_ALLOCS 1 */
-/* #define DEBUG_CALLS 1 */
 
 /*
  * Floating point comparitors.
@@ -63,6 +59,35 @@
 extern lwreporter lwerror;
 extern lwreporter lwnotice;
 
+/* Debug macros */
+#if POSTGIS_DEBUG_LEVEL > 0
+
+/* Display a notice at the given debug level */
+#define LWDEBUG(level, msg) \
+        do { \
+                if (POSTGIS_DEBUG_LEVEL >= level) \
+                        lwnotice("[%s:%s:%d] " msg, __FILE__, __func__, __LINE__); \
+        } while (0);
+
+/* Display a formatted notice at the given debug level (like printf, with variadic arguments) */
+#define LWDEBUGF(level, msg, ...) \
+        do { \
+                if (POSTGIS_DEBUG_LEVEL >= level) \
+                        lwnotice("[%s:%s:%d] " msg, __FILE__, __func__, __LINE__, __VA_ARGS__); \
+        } while (0);
+
+#else
+
+/* Empty prototype that can be optimised away by the compiler for non-debug builds */
+#define LWDEBUG(level, msg) \
+        ((void) 0)
+
+/* Empty prototype that can be optimised away by the compiler for non-debug builds */
+#define LWDEBUGF(level, msg, ...) \
+        ((void) 0)
+
+#endif
+
 /******************************************************************/
 
 typedef unsigned char uchar;

Modified: trunk/lwgeom/long_xact.c
===================================================================
--- trunk/lwgeom/long_xact.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/long_xact.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -1,3 +1,5 @@
+#include "lwgeom_pg.h"
+
 #include "postgres.h"
 #include "executor/spi.h"       /* this is what you need to work with SPI */
 #include "commands/trigger.h"   /* ... and triggers */
@@ -3,5 +5,4 @@
 #include "utils/lsyscache.h"	/* for get_namespace_name() */
 
-/*#define PGIS_DEBUG 1*/
 
 #define ABORT_ON_AUTH_FAILURE 1
@@ -83,15 +84,11 @@
 	pk_id = SPI_getvalue(trigdata->tg_trigtuple, tupdesc,
 		SPI_fnumber(tupdesc, colname));
 
-#if PGIS_DEBUG
-	elog(NOTICE,"check_authorization called");
-#endif
+	POSTGIS_DEBUG(3, "check_authorization called");
 
 	sprintf(query,"SELECT authid FROM \"%s\" WHERE expires >= now() AND toid = '%d' AND rid = '%s'", authtable, trigdata->tg_relation->rd_id, pk_id);
 
-#if PGIS_DEBUG > 1
-	elog(NOTICE,"about to execute :%s", query);
-#endif
+	POSTGIS_DEBUGF(3 ,"about to execute :%s", query);
 
 	SPIcode = SPI_exec(query,0);
 	if (SPIcode !=SPI_OK_SELECT )
@@ -99,9 +96,8 @@
 
 	if (!SPI_processed )
 	{
-#if PGIS_DEBUG
-		elog(NOTICE,"there is NO lock on row '%s'", pk_id);
-#endif
+		POSTGIS_DEBUGF(3, "there is NO lock on row '%s'", pk_id);
+
 		SPI_finish();
 		return PointerGetDatum(rettuple_ok);
 	}
@@ -113,9 +109,7 @@
 	tuple = tuptable->vals[0];
 	lockcode = SPI_getvalue(tuple, tupdesc, 1);
 
-#if PGIS_DEBUG
-	elog(NOTICE, "there is a lock on row '%s' (auth: '%s').", pk_id, lockcode);
-#endif
+	POSTGIS_DEBUGF(3, "there is a lock on row '%s' (auth: '%s').", pk_id, lockcode);
 
 	/*
 	 * check to see if temp_lock_have_table table exists
@@ -132,9 +126,7 @@
 
 	sprintf(query, "SELECT * FROM temp_lock_have_table WHERE xideq( transid, getTransactionID() ) AND lockcode ='%s'", lockcode);
 
-#if PGIS_DEBUG
-	elog(NOTICE,"about to execute :%s", query);
-#endif
+	POSTGIS_DEBUGF(3, "about to execute :%s", query);
 
 	SPIcode = SPI_exec(query,0);
 	if (SPIcode != SPI_OK_SELECT )
@@ -142,9 +134,8 @@
 
 	if (SPI_processed >0)
 	{
-#if PGIS_DEBUG
-		elog(NOTICE,"I own the lock - I can modify the row");
-#endif
+		POSTGIS_DEBUG(3, "I own the lock - I can modify the row");
+
 		SPI_finish();
 		return PointerGetDatum(rettuple_ok);
 	}

Modified: trunk/lwgeom/lwcollection.c
===================================================================
--- trunk/lwgeom/lwcollection.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwcollection.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -15,7 +15,6 @@
 #include <string.h>
 #include "liblwgeom.h"
 
-/*#define PGIS_DEBUG_CALLS 1 */
 
 #define CHECK_LWGEOM_ZM 1
 
@@ -30,9 +29,7 @@
 	unsigned int i;
 #endif
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcollection_construct called with %d, %d, %p, %d, %p.", type, SRID, bbox, ngeoms, geoms);
-#endif        
+        LWDEBUGF(2, "lwcollection_construct called with %d, %d, %p, %d, %p.", type, SRID, bbox, ngeoms, geoms);
 
 	hasz = 0;
 	hasm = 0;
@@ -42,14 +39,13 @@
 		hasm = TYPE_HASM(geoms[0]->type);
 #ifdef CHECK_LWGEOM_ZM
 		zm = TYPE_GETZM(geoms[0]->type);
-#ifdef PGIS_DEBUG
-                lwnotice("lwcollection_construct type[0]=%d", geoms[0]->type);
-#endif
+
+                LWDEBUGF(3, "lwcollection_construct type[0]=%d", geoms[0]->type);
+
 		for (i=1; i<ngeoms; i++)
 		{
-#ifdef PGIS_DEBUG
-                        lwnotice("lwcollection_construct type=[%d]=%d", i, geoms[i]->type);
-#endif
+                        LWDEBUGF(3, "lwcollection_construct type=[%d]=%d", i, geoms[i]->type);
+
 			if ( zm != TYPE_GETZM(geoms[i]->type) )
 				lwerror("lwcollection_construct: mixed dimension geometries: %d/%d", zm, TYPE_GETZM(geoms[i]->type));
 		}
@@ -144,22 +140,17 @@
 	if ( col->SRID != -1 ) size += 4; /* SRID */
 	if ( col->bbox ) size += sizeof(BOX2DFLOAT4);
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwcollection_serialize_size[%p]: start size: %d", col, size);
-#endif
+	LWDEBUGF(2, "lwcollection_serialize_size[%p]: start size: %d", col, size);
 
 
 	for (i=0; i<col->ngeoms; i++)
 	{
 		size += lwgeom_serialize_size(col->geoms[i]);
-#ifdef PGIS_DEBUG_CALLS
-		lwnotice("lwcollection_serialize_size[%p]: with geom%d: %d", col, i, size);
-#endif
+
+		LWDEBUGF(3, "lwcollection_serialize_size[%p]: with geom%d: %d", col, i, size);
 	}
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwcollection_serialize_size[%p]:  returning %d", col, size);
-#endif
+	LWDEBUGF(3, "lwcollection_serialize_size[%p]:  returning %d", col, size);
 
 	return size; 
 }
@@ -178,10 +169,8 @@
 	uchar *loc;
 	int i;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwcollection_serialize_buf called (%s with %d elems)",
+	LWDEBUGF(2, "lwcollection_serialize_buf called (%s with %d elems)",
 		lwgeom_typename(TYPE_GETTYPE(coll->type)), coll->ngeoms);
-#endif
 
 	hasSRID = (coll->SRID != -1);
 
@@ -221,9 +210,7 @@
 
 	if (retsize) *retsize = size;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwcollection_serialize_buf returning");
-#endif
+	LWDEBUG(3, "lwcollection_serialize_buf returning");
 }
 
 int
@@ -342,9 +329,7 @@
 	unsigned int i, j;
 	unsigned int *hit;
 
-#if PGIS_DEBUG_CALLS
-	lwnotice("lwcollection_same called");
-#endif /* PGIS_DEBUG_CALLS */
+	LWDEBUG(2, "lwcollection_same called");
 
 	if ( TYPE_GETTYPE(c1->type) != TYPE_GETTYPE(c2->type) ) return 0;
 	if ( c1->ngeoms != c2->ngeoms ) return 0;

Modified: trunk/lwgeom/lwcompound.c
===================================================================
--- trunk/lwgeom/lwcompound.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwcompound.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -1,120 +1,118 @@
-/**********************************************************************
- * $Id$
- *
- * PostGIS - Spatial Types for PostgreSQL
- * http://postgis.refractions.net
- * Copyright 2001-2006 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.
- * 
- **********************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "liblwgeom.h"
-
-LWCOMPOUND *
-lwcompound_deserialize(uchar *serialized)
-{
-        LWCOMPOUND *result;
-        LWGEOM_INSPECTED *insp;
-        int type = lwgeom_getType(serialized[0]);
-        int i;
-
-        if(type != COMPOUNDTYPE)
-        {
-                lwerror("lwcompound_deserialize called on non compound: %d", type);
-                return NULL;
-        }
-
-        insp = lwgeom_inspect(serialized);
-
-        result = lwalloc(sizeof(LWCOMPOUND));
-        result->type = insp->type;
-        result->SRID = insp->SRID;
-        result->ngeoms = insp->ngeometries;
-        result->geoms = lwalloc(sizeof(LWGEOM *)*insp->ngeometries);
-
-        if(lwgeom_hasBBOX(serialized[0]))
-        {
-                result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
-                memcpy(result->bbox, serialized + 1, sizeof(BOX2DFLOAT4));
-        }
-        else result->bbox = NULL;
-
-        for(i = 0; i < insp->ngeometries; i++)
-        {
-                if(lwgeom_getType(insp->sub_geoms[i][0]) == LINETYPE)
-                        result->geoms[i] = (LWGEOM *)lwline_deserialize(insp->sub_geoms[i]);
-                else
-                        result->geoms[i] = (LWGEOM *)lwcurve_deserialize(insp->sub_geoms[i]);
-                if(TYPE_NDIMS(result->geoms[i]->type) != TYPE_NDIMS(result->type))
-                {
-                        lwerror("Mixed dimensions (compound:%d, line/curve%d:%d)",
-                            TYPE_NDIMS(result->type), i,
-                            TYPE_NDIMS(result->geoms[i]->type)
-                        );
-                        lwfree(result);
-                        return NULL;
-                }
-        }
-        return result;
-}
-
-/*
- * Add 'what' to this string at position 'where'
- * where=0 == prepend
- * where=-1 == append
- * Returns a COMPOUND or a GEOMETRYCOLLECTION
- */
-LWGEOM *
-lwcompound_add(const LWCOMPOUND *to, uint32 where, const LWGEOM *what)
-{
-        LWCOLLECTION *col;
-        LWGEOM **geoms;
-        int newtype;
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcompound_add called.");
-#endif
-
-        if(where != -1 && where != 0)
-        {
-                lwerror("lwcompound_add only supports 0 or -1 as a second argument, not %d", where);
-                return NULL;
-        }
-
-        /* dimensions compatibility are checked by caller */
-
-        /* Construct geoms array */
-        geoms = lwalloc(sizeof(LWGEOM *)*2);
-        if(where == -1) /* append */
-        {
-                geoms[0] = lwgeom_clone((LWGEOM *)to);
-                geoms[1] = lwgeom_clone(what);
-        }
-        else /* prepend */
-        {
-                geoms[0] = lwgeom_clone(what);
-                geoms[1] = lwgeom_clone((LWGEOM *)to);
-        }
-
-        /* reset SRID and wantbbox flag from component types */
-        geoms[0]->SRID = geoms[1]->SRID = -1;
-        TYPE_SETHASSRID(geoms[0]->type, 0);
-        TYPE_SETHASSRID(geoms[1]->type, 0);
-        TYPE_SETHASBBOX(geoms[0]->type, 0);
-        TYPE_SETHASBBOX(geoms[1]->type, 0);
-
-        /* Find appropriate geom type */
-        if(TYPE_GETTYPE(what->type) == LINETYPE || TYPE_GETTYPE(what->type) == CURVETYPE) newtype = COMPOUNDTYPE;
-        else newtype = COLLECTIONTYPE;
-
-        col = lwcollection_construct(newtype,
-                to->SRID, NULL, 2, geoms);
-
-        return (LWGEOM *)col;
-}
-
+/**********************************************************************
+ * $Id$
+ *
+ * PostGIS - Spatial Types for PostgreSQL
+ * http://postgis.refractions.net
+ * Copyright 2001-2006 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.
+ * 
+ **********************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "liblwgeom.h"
+
+LWCOMPOUND *
+lwcompound_deserialize(uchar *serialized)
+{
+        LWCOMPOUND *result;
+        LWGEOM_INSPECTED *insp;
+        int type = lwgeom_getType(serialized[0]);
+        int i;
+
+        if(type != COMPOUNDTYPE)
+        {
+                lwerror("lwcompound_deserialize called on non compound: %d", type);
+                return NULL;
+        }
+
+        insp = lwgeom_inspect(serialized);
+
+        result = lwalloc(sizeof(LWCOMPOUND));
+        result->type = insp->type;
+        result->SRID = insp->SRID;
+        result->ngeoms = insp->ngeometries;
+        result->geoms = lwalloc(sizeof(LWGEOM *)*insp->ngeometries);
+
+        if(lwgeom_hasBBOX(serialized[0]))
+        {
+                result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
+                memcpy(result->bbox, serialized + 1, sizeof(BOX2DFLOAT4));
+        }
+        else result->bbox = NULL;
+
+        for(i = 0; i < insp->ngeometries; i++)
+        {
+                if(lwgeom_getType(insp->sub_geoms[i][0]) == LINETYPE)
+                        result->geoms[i] = (LWGEOM *)lwline_deserialize(insp->sub_geoms[i]);
+                else
+                        result->geoms[i] = (LWGEOM *)lwcurve_deserialize(insp->sub_geoms[i]);
+                if(TYPE_NDIMS(result->geoms[i]->type) != TYPE_NDIMS(result->type))
+                {
+                        lwerror("Mixed dimensions (compound:%d, line/curve%d:%d)",
+                            TYPE_NDIMS(result->type), i,
+                            TYPE_NDIMS(result->geoms[i]->type)
+                        );
+                        lwfree(result);
+                        return NULL;
+                }
+        }
+        return result;
+}
+
+/*
+ * Add 'what' to this string at position 'where'
+ * where=0 == prepend
+ * where=-1 == append
+ * Returns a COMPOUND or a GEOMETRYCOLLECTION
+ */
+LWGEOM *
+lwcompound_add(const LWCOMPOUND *to, uint32 where, const LWGEOM *what)
+{
+        LWCOLLECTION *col;
+        LWGEOM **geoms;
+        int newtype;
+
+        LWDEBUG(2, "lwcompound_add called.");
+
+        if(where != -1 && where != 0)
+        {
+                lwerror("lwcompound_add only supports 0 or -1 as a second argument, not %d", where);
+                return NULL;
+        }
+
+        /* dimensions compatibility are checked by caller */
+
+        /* Construct geoms array */
+        geoms = lwalloc(sizeof(LWGEOM *)*2);
+        if(where == -1) /* append */
+        {
+                geoms[0] = lwgeom_clone((LWGEOM *)to);
+                geoms[1] = lwgeom_clone(what);
+        }
+        else /* prepend */
+        {
+                geoms[0] = lwgeom_clone(what);
+                geoms[1] = lwgeom_clone((LWGEOM *)to);
+        }
+
+        /* reset SRID and wantbbox flag from component types */
+        geoms[0]->SRID = geoms[1]->SRID = -1;
+        TYPE_SETHASSRID(geoms[0]->type, 0);
+        TYPE_SETHASSRID(geoms[1]->type, 0);
+        TYPE_SETHASBBOX(geoms[0]->type, 0);
+        TYPE_SETHASBBOX(geoms[1]->type, 0);
+
+        /* Find appropriate geom type */
+        if(TYPE_GETTYPE(what->type) == LINETYPE || TYPE_GETTYPE(what->type) == CURVETYPE) newtype = COMPOUNDTYPE;
+        else newtype = COLLECTIONTYPE;
+
+        col = lwcollection_construct(newtype,
+                to->SRID, NULL, 2, geoms);
+
+        return (LWGEOM *)col;
+}
+

Modified: trunk/lwgeom/lwcurve.c
===================================================================
--- trunk/lwgeom/lwcurve.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwcurve.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -30,8 +30,6 @@
 void lwcurve_setPoint4d(LWCURVE *curve, unsigned int index, POINT4D *newpoint);
 
 
-/*#define PGIS_DEBUG_CALLS 1 */
-/*#define PGIS_DEBUG 1 */
 
 #ifndef MAXFLOAT
   #define MAXFLOAT      3.402823466e+38F
@@ -99,43 +97,39 @@
 
         if(lwgeom_hasBBOX(type))
         {
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_deserialize: input has bbox");
-#endif
+                LWDEBUG(3, "lwcurve_deserialize: input has bbox");
+
                 result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
                 memcpy(result->bbox, loc, sizeof(BOX2DFLOAT4));
                 loc += sizeof(BOX2DFLOAT4);               
          }
          else
          {
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_deserialize: input lacks bbox");           
-#endif               
+                LWDEBUG(3, "lwcurve_deserialize: input lacks bbox");           
+               
                 result->bbox = NULL;
          }
 
          if(lwgeom_hasSRID(type))
          {
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_deserialize: input has srid");
-#endif
+                LWDEBUG(3, "lwcurve_deserialize: input has srid");
+
                 result->SRID = lw_get_int32(loc);               
                 loc += 4; /* type + SRID */
          }
          else
          {
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_deserialize: input lacks srid");
-#endif
+                LWDEBUG(3, "lwcurve_deserialize: input lacks srid");
+
                 result->SRID = -1;                
          }
 
          /* we've read the type (1 byte) and SRID (4 bytes, if present) */
 
          npoints = lw_get_uint32(loc);
-#ifdef PGIS_DEBUG
-         lwnotice("curve npoints = %d", npoints);
-#endif         
+
+         LWDEBUGF(3, "curve npoints = %d", npoints);
+         
          loc += 4;
          pa = pointArray_construct(loc, TYPE_HASZ(type), TYPE_HASM(type), npoints);
          result->points = pa;
@@ -178,10 +172,8 @@
         int ptsize;
         size_t size;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurve_serialize_buf(%p, %p, %p) called",
+        LWDEBUGF(2, "lwcurve_serialize_buf(%p, %p, %p) called",
                 curve, buf, retsize);
-#endif
 
         if(curve == NULL) 
         {
@@ -204,19 +196,14 @@
                 hasSRID, CURVETYPE, curve->bbox ? 1 : 0);
         loc = buf+1;
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwcurve_serialize_buf added type (%d)", curve->type);
-#endif
+        LWDEBUGF(3, "lwcurve_serialize_buf added type (%d)", curve->type);
 
         if(curve->bbox)
         {
                 memcpy(loc, curve->bbox, sizeof(BOX2DFLOAT4));
                 loc += sizeof(BOX2DFLOAT4);
 
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_serialize_buf added BBOX");
-#endif
-
+                LWDEBUG(3, "lwcurve_serialize_buf added BBOX");
         }                
 
         if(hasSRID)
@@ -224,36 +211,27 @@
                 memcpy(loc, &curve->SRID, sizeof(int32));
                 loc += sizeof(int32);
 
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_serialize_buf added SRID");
-#endif
-
+                LWDEBUG(3, "lwcurve_serialize_buf added SRID");
         }
 
         memcpy(loc, &curve->points->npoints, sizeof(uint32));
         loc += sizeof(uint32);
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwcurve_serialize_buf added npoints (%d)",
+        LWDEBUGF(3, "lwcurve_serialize_buf added npoints (%d)",
             curve->points->npoints);
-#endif
 
         /* copy in points */
         size = curve->points->npoints * ptsize;
         memcpy(loc, getPoint_internal(curve->points, 0), size);
         loc += size;
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwcurve_serialize_buf copied serialized_pointlist (%d bytes)",
+        LWDEBUGF(3, "lwcurve_serialize_buf copied serialized_pointlist (%d bytes)",
                 ptsize * curve->points->npoints);        
-#endif
 
         if(retsize) *retsize = loc-buf;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurve_serialize_buf returning (loc: %p, size: %d)",
+        LWDEBUGF(3, "lwcurve_serialize_buf returning (loc: %p, size: %d)",
                 loc, loc-buf);
-#endif
 }
 
 /* find length of this deserialized curve */
@@ -262,9 +240,7 @@
 {
         size_t size = 1; /* type */
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurve_serialize_size called");        
-#endif
+        LWDEBUG(2, "lwcurve_serialize_size called");        
 
         if(curve->SRID != -1) size += 4; /* SRID */
         if(curve->bbox) size += sizeof(BOX2DFLOAT4);
@@ -272,9 +248,7 @@
         size += 4; /* npoints */
         size += pointArray_ptsize(curve->points) * curve->points->npoints;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurve_serialize_size returning %d", size);
-#endif
+        LWDEBUGF(3, "lwcurve_serialize_size returning %d", size);
 
         return size;
 }
@@ -293,9 +267,7 @@
         int i;
         BOX3D *box;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcircle_compute_box3d called.");
-#endif
+        LWDEBUG(2, "lwcircle_compute_box3d called.");
 
         center = lwalloc(sizeof(POINT4D));
         radius = lwcircle_center(p1, p2, p3, &center);
@@ -305,9 +277,7 @@
         top = center->y + radius;
         left = center->x - radius;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcircle_compute_box3d: top=%.16f, left=%.16f", top, left);
-#endif
+        LWDEBUGF(3, "lwcircle_compute_box3d: top=%.16f, left=%.16f", top, left);
         */
 
         x1 = MAXFLOAT;
@@ -344,9 +314,7 @@
                 sweep = 0.0;
         }
 
-#ifdef PGIS_DEBUG
-        lwnotice("a1 %.16f, a2 %.16f, a3 %.16f, sweep %.16f", a1, a2, a3, sweep);
-#endif
+        LWDEBUGF(3, "a1 %.16f, a2 %.16f, a3 %.16f, sweep %.16f", a1, a2, a3, sweep);
 
         angle = 0.0;
         for(i=0; i < 6; i++)
@@ -389,18 +357,16 @@
                         if(sweep < 0.0 && (angle < a3 || angle > a1)) continue;
                 }
 
-#ifdef PGIS_DEBUG
-                lwnotice("lwcircle_compute_box3d: potential extreame %d (%.16f, %.16f)", i, xe, ye);
-#endif
+                LWDEBUGF(3, "lwcircle_compute_box3d: potential extreame %d (%.16f, %.16f)", i, xe, ye);
+
                 x1 = (x1 < xe) ? x1 : xe;
                 y1 = (y1 < ye) ? y1 : ye;
                 x2 = (x2 > xe) ? x2 : xe;
                 y2 = (y2 > ye) ? y2 : ye;
         }
-#ifdef PGIS_DEBUG
-        lwnotice("lwcircle_compute_box3d: extreames found (%.16f %.16f, %.16f %.16f)", x1, y1, x2, y2);
-#endif
 
+        LWDEBUGF(3, "lwcircle_compute_box3d: extreames found (%.16f %.16f, %.16f %.16f)", x1, y1, x2, y2);
+
         /*
         x1 = center->x + x1 * radius;
         x2 = center->x + x2 * radius;
@@ -436,9 +402,7 @@
         POINT4D *p2 = lwalloc(sizeof(POINT4D));
         POINT4D *p3 = lwalloc(sizeof(POINT4D));
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurve_compute_box3d called.");
-#endif
+        LWDEBUG(2, "lwcurve_compute_box3d called.");
 
         /* initialize box values */
         box = lwalloc(sizeof(BOX3D));
@@ -459,9 +423,8 @@
                 box->ymax = (box->ymax > tmp->ymax) ? box->ymax : tmp->ymax;
                 box->zmin = (box->zmin < tmp->zmin) ? box->zmin : tmp->zmin;
                 box->zmax = (box->zmax > tmp->zmax) ? box->zmax : tmp->zmax;
-#ifdef PGIS_DEBUG_CALLS
-                lwnotice("curve %d x=(%.16f,%.16f) y=(%.16f,%.16f) z=(%.16f,%.16f)", i/2, box->xmin, box->xmax, box->ymin, box->ymax, box->zmin, box->zmax);
-#endif
+
+                LWDEBUGF(4, "curve %d x=(%.16f,%.16f) y=(%.16f,%.16f) z=(%.16f,%.16f)", i/2, box->xmin, box->xmax, box->ymin, box->ymax, box->zmin, box->zmax);
         }
 
         
@@ -471,12 +434,9 @@
 int
 lwcurve_compute_box2d_p(LWCURVE *curve, BOX2DFLOAT4 *result)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurve_compute_box2d_p called.");
-#endif
-
         BOX3D *box = lwcurve_compute_box3d(curve);
+        LWDEBUG(2, "lwcurve_compute_box2d_p called.");
+
         if(box == NULL) return 0;
         box3d_to_box2df_p(box, result);
         return 1;
@@ -497,9 +457,8 @@
         const uchar *loc;
         uint32 npoints;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwgeom_size_curve called");
-#endif
+        LWDEBUG(2, "lwgeom_size_curve called");
+
         if(lwgeom_getType(type) != CURVETYPE)
                 lwerror("lwgeom_size_curve::attempt to find the length of a non-curve");
 
@@ -522,9 +481,7 @@
 
         result += TYPE_NDIMS(type) * sizeof(double) * npoints;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwgeom_size_curve returning %d", result);
-#endif        
+        LWDEBUGF(3, "lwgeom_size_curve returning %d", result);
 
         return result;
 }
@@ -707,9 +664,7 @@
         pa = pointArray_construct(newpoints, zmflag&2, zmflag&1,
                 mpoint->ngeoms);
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwcurve_from_lwmpoint: constructed pointarray for %d points, %d zmflag", mpoint->ngeoms, zmflag);
-#endif
+        LWDEBUGF(3, "lwcurve_from_lwmpoint: constructed pointarray for %d points, %d zmflag", mpoint->ngeoms, zmflag);
         
         return lwcurve_construct(SRID, NULL, pa);
 }
@@ -750,13 +705,3 @@
 }
 
 
-
-
-
-
-
-
-
-
-
-

Modified: trunk/lwgeom/lwcurvepoly.c
===================================================================
--- trunk/lwgeom/lwcurvepoly.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwcurvepoly.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -1,89 +1,86 @@
-/**********************************************************************
- * $Id$
- *
- * PostGIS - Spatial Types for PostgreSQL
- * http://postgis.refractions.net
- * Copyright 2001-2006 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.
- * 
- **********************************************************************/
-
-/* basic LWCURVEPOLY manipulation */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "liblwgeom.h"
-
-/*#define PGIS_DEBUG_CALLS 1 */
-
-LWCURVEPOLY *
-lwcurvepoly_deserialize(uchar *srl)
-{
-        LWCURVEPOLY *result;
-        LWGEOM_INSPECTED *insp;
-        int type = lwgeom_getType(srl[0]);
-        int i;
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurvepoly_deserialize called.");
-#endif
-
-        if(type != CURVEPOLYTYPE)
-        {
-                lwerror("lwcurvepoly_deserialize called on NON curvepoly: %d",
-                        type);
-                return NULL;
-        }
-
-        insp = lwgeom_inspect(srl);
-
-        result = lwalloc(sizeof(LWCURVEPOLY));
-        result->type = insp->type;
-        result->SRID = insp->SRID;
-        result->nrings = insp->ngeometries;
-        result->rings = lwalloc(sizeof(LWGEOM *)*insp->ngeometries);
-
-        if(lwgeom_hasBBOX(srl[0]))
-        {
-                result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
-                memcpy(result->bbox, srl + 1, sizeof(BOX2DFLOAT4));
-        }
-        else result->bbox = NULL;
-
-        for(i = 0; i < insp->ngeometries; i++)
-        {
-                result->rings[i] = lwgeom_deserialize(insp->sub_geoms[i]);
-                if(lwgeom_getType(result->rings[i]->type) != CURVETYPE 
-                        && lwgeom_getType(result->rings[i]->type) != LINETYPE)
-                {
-                        lwerror("Only Circular curves and Linestrings are currently supported as rings, not %s (%d)", lwgeom_typename(result->rings[i]->type), result->rings[i]->type);
-                        lwfree(result);
-                        lwfree(insp);
-                        return NULL;
-                }
-                if(TYPE_NDIMS(result->rings[i]->type) != TYPE_NDIMS(result->type))
-                {
-                        lwerror("Mixed dimensions (curvepoly %d, ring %d)",
-                                TYPE_NDIMS(result->type), i, 
-                                TYPE_NDIMS(result->rings[i]->type));
-                        lwfree(result);
-                        lwfree(insp);
-                        return NULL;
-                }
-        }
-        return result;
-}
-
-LWGEOM *
-lwcurvepoly_add(const LWCURVEPOLY *to, uint32 where, const LWGEOM *what)
-{
-        /* TODO */
-        lwerror("lwcurvepoly_add not yet implemented.");
-        return NULL;
-}
-
-
-
+/**********************************************************************
+ * $Id$
+ *
+ * PostGIS - Spatial Types for PostgreSQL
+ * http://postgis.refractions.net
+ * Copyright 2001-2006 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.
+ * 
+ **********************************************************************/
+
+/* basic LWCURVEPOLY manipulation */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "liblwgeom.h"
+
+
+LWCURVEPOLY *
+lwcurvepoly_deserialize(uchar *srl)
+{
+        LWCURVEPOLY *result;
+        LWGEOM_INSPECTED *insp;
+        int type = lwgeom_getType(srl[0]);
+        int i;
+
+        LWDEBUG(3, "lwcurvepoly_deserialize called.");
+
+        if(type != CURVEPOLYTYPE)
+        {
+                lwerror("lwcurvepoly_deserialize called on NON curvepoly: %d",
+                        type);
+                return NULL;
+        }
+
+        insp = lwgeom_inspect(srl);
+
+        result = lwalloc(sizeof(LWCURVEPOLY));
+        result->type = insp->type;
+        result->SRID = insp->SRID;
+        result->nrings = insp->ngeometries;
+        result->rings = lwalloc(sizeof(LWGEOM *)*insp->ngeometries);
+
+        if(lwgeom_hasBBOX(srl[0]))
+        {
+                result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
+                memcpy(result->bbox, srl + 1, sizeof(BOX2DFLOAT4));
+        }
+        else result->bbox = NULL;
+
+        for(i = 0; i < insp->ngeometries; i++)
+        {
+                result->rings[i] = lwgeom_deserialize(insp->sub_geoms[i]);
+                if(lwgeom_getType(result->rings[i]->type) != CURVETYPE 
+                        && lwgeom_getType(result->rings[i]->type) != LINETYPE)
+                {
+                        lwerror("Only Circular curves and Linestrings are currently supported as rings, not %s (%d)", lwgeom_typename(result->rings[i]->type), result->rings[i]->type);
+                        lwfree(result);
+                        lwfree(insp);
+                        return NULL;
+                }
+                if(TYPE_NDIMS(result->rings[i]->type) != TYPE_NDIMS(result->type))
+                {
+                        lwerror("Mixed dimensions (curvepoly %d, ring %d)",
+                                TYPE_NDIMS(result->type), i, 
+                                TYPE_NDIMS(result->rings[i]->type));
+                        lwfree(result);
+                        lwfree(insp);
+                        return NULL;
+                }
+        }
+        return result;
+}
+
+LWGEOM *
+lwcurvepoly_add(const LWCURVEPOLY *to, uint32 where, const LWGEOM *what)
+{
+        /* TODO */
+        lwerror("lwcurvepoly_add not yet implemented.");
+        return NULL;
+}
+
+
+

Modified: trunk/lwgeom/lwgeom.c
===================================================================
--- trunk/lwgeom/lwgeom.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -18,17 +18,13 @@
 #include "liblwgeom.h"
 #include "wktparse.h"
 
-/*#define PGIS_DEBUG_CALLS 1*/
-/*#define PGIS_DEBUG 1*/
 
 LWGEOM *
 lwgeom_deserialize(uchar *srl)
 {
 	int type = lwgeom_getType(srl[0]);
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwgeom_deserialize got %d - %s", type, lwgeom_typename(type));
-#endif
+	LWDEBUGF(2, "lwgeom_deserialize got %d - %s", type, lwgeom_typename(type));
 
 	switch (type)
 	{
@@ -57,11 +53,8 @@
                 case MULTISURFACETYPE:
                         return (LWGEOM *)lwmsurface_deserialize(srl);
 		default:
-#ifdef PGIS_DEBUG
-                        lwerror("lwgeom_deserialize: Unknown geometry type: %d", type);
-#else
 			lwerror("Unknown geometry type: %d", type);
-#endif
+
 			return NULL;
 	}
 
@@ -72,9 +65,7 @@
 {
 	int type = TYPE_GETTYPE(lwgeom->type);
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwgeom_serialize_size(%s) called", lwgeom_typename(type));
-#endif
+	LWDEBUGF(2, "lwgeom_serialize_size(%s) called", lwgeom_typename(type));
 
 	switch (type)
 	{
@@ -96,11 +87,8 @@
 		case COLLECTIONTYPE:
 			return lwcollection_serialize_size((LWCOLLECTION *)lwgeom);
 		default:
-#ifdef PGIS_DEBUG
-                        lwerror("lwgeom_serialize_size: Unknown geometry type: %d", type);
-#else
 			lwerror("Unknown geometry type: %d", type);
-#endif
+
 			return 0;
 	}
 }
@@ -110,10 +98,9 @@
 {
 	int type = TYPE_GETTYPE(lwgeom->type);
 
-#ifdef PGIS_DEBUG_CALLS 
-	lwnotice("lwgeom_serialize_buf called with a %s",
+	LWDEBUGF(2, "lwgeom_serialize_buf called with a %s",
 			lwgeom_typename(type));
-#endif
+
 	switch (type)
 	{
 		case POINTTYPE:
@@ -140,11 +127,7 @@
 				retsize);
 			break;
 		default:
-#ifdef PGIS_DEBUG
-                        lwerror("lwgeom_serialize_buf: Unknown geometry type: %d", type);
-#else
 			lwerror("Unknown geometry type: %d", type);
-#endif
 			return;
 	}
 	return;
@@ -159,7 +142,7 @@
 
 	lwgeom_serialize_buf(lwgeom, serialized, &retsize);
 
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL > 0
 	if ( retsize != size )
 	{
 		lwerror("lwgeom_serialize: computed size %d, returned size %d",
@@ -220,9 +203,8 @@
 int
 lwgeom_compute_box2d_p(LWGEOM *lwgeom, BOX2DFLOAT4 *buf)
 {
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwgeom_compute_box2d_p called of %p of type %d.", lwgeom, TYPE_GETTYPE(lwgeom->type));
-#endif
+        LWDEBUGF(2, "lwgeom_compute_box2d_p called of %p of type %d.", lwgeom, TYPE_GETTYPE(lwgeom->type));
+
 	switch(TYPE_GETTYPE(lwgeom->type))
 	{
 		case POINTTYPE:
@@ -346,20 +328,16 @@
 
 	/* Drop bounding box (always a copy) */
 	if ( lwgeom->bbox ) {
-#ifdef PGIS_DEBUG
-                lwnotice("lwgeom_release: releasing bbox.");
-#endif
+                LWDEBUG(3, "lwgeom_release: releasing bbox.");
+
                 lwfree(lwgeom->bbox);
         }
 
 	/* Collection */
 	if ( (col=lwgeom_as_lwcollection(lwgeom)) )
 	{
+                LWDEBUG(3, "lwgeom_release: Releasing collection.");
 
-#ifdef PGIS_DEBUG
-                lwnotice("lwgeom_release: Releasing collection.");
-#endif
-
 		for (i=0; i<col->ngeoms; i++)
 		{
 			lwgeom_release(col->geoms[i]);
@@ -376,9 +354,8 @@
 LWGEOM *
 lwgeom_clone(const LWGEOM *lwgeom)
 {
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwgeom_clone called with %p, %d", lwgeom, TYPE_GETTYPE(lwgeom->type));
-#endif
+        LWDEBUGF(2, "lwgeom_clone called with %p, %d", lwgeom, TYPE_GETTYPE(lwgeom->type));
+
 	switch(TYPE_GETTYPE(lwgeom->type))
 	{
 		case POINTTYPE:
@@ -420,12 +397,10 @@
 		return NULL;
 	}
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwgeom_add(%s, %d, %s) called",
+	LWDEBUGF(2, "lwgeom_add(%s, %d, %s) called",
 		lwgeom_typename(TYPE_GETTYPE(to->type)),
 		where,
 		lwgeom_typename(TYPE_GETTYPE(what->type)));
-#endif
 
 	switch(TYPE_GETTYPE(to->type))
 	{
@@ -538,7 +513,7 @@
 	char *hexewkb;
 	long int i;
 	LWGEOM *ret;
-    SERIALIZED_LWGEOM *serialized_lwgeom;
+	SERIALIZED_LWGEOM *serialized_lwgeom;
 
 	/* "HEXify" the EWKB */
 	hexewkb = lwalloc(hexewkblen+1);
@@ -546,7 +521,7 @@
 	hexewkb[hexewkblen] = '\0';
 
 	/* Rely on grammar parser to construct a LWGEOM */
-    serialized_lwgeom = parse_lwgeom_wkt(hexewkb);
+	serialized_lwgeom = parse_lwgeom_wkt(hexewkb);
 
 	/* Free intermediate HEXified representation */
 	lwfree(hexewkb);
@@ -568,25 +543,21 @@
 char
 lwgeom_same(const LWGEOM *lwgeom1, const LWGEOM *lwgeom2)
 {
-#if PGIS_DEBUG
-		lwnotice("lwgeom_same(%s, %s) called",
-			lwgeom_typename(TYPE_GETTYPE(lwgeom1->type)),
-			lwgeom_typename(TYPE_GETTYPE(lwgeom2->type)));
-#endif
+	LWDEBUGF(2, "lwgeom_same(%s, %s) called",
+		lwgeom_typename(TYPE_GETTYPE(lwgeom1->type)),
+		lwgeom_typename(TYPE_GETTYPE(lwgeom2->type)));
 
 	if ( TYPE_GETTYPE(lwgeom1->type) != TYPE_GETTYPE(lwgeom2->type) )
 	{
-#if PGIS_DEBUG
-		lwnotice(" type differ");
-#endif
+		LWDEBUG(3, " type differ");
+
 		return 0;
 	}
 
 	if ( TYPE_GETZM(lwgeom1->type) != TYPE_GETZM(lwgeom2->type) )
 	{
-#if PGIS_DEBUG
-		lwnotice(" ZM flags differ");
-#endif
+		LWDEBUG(3, " ZM flags differ");
+
 		return 0;
 	}
 
@@ -596,9 +567,8 @@
 		/*lwnotice("bbox1:%p, bbox2:%p", lwgeom1->bbox, lwgeom2->bbox);*/
 		if ( ! box2d_same(lwgeom1->bbox, lwgeom2->bbox) )
 		{
-#if PGIS_DEBUG
-			lwnotice(" bounding boxes differ");
-#endif
+			LWDEBUG(3, " bounding boxes differ");
+
 			return 0;
 		}
 	}

Modified: trunk/lwgeom/lwgeom_api.c
===================================================================
--- trunk/lwgeom/lwgeom_api.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_api.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -13,7 +13,6 @@
  */
 #define PARANOIA_LEVEL 1
 
-/* #define PGIS_DEBUG 1 */
 
 
 /**********************************************************************
@@ -331,11 +330,9 @@
 box3d_union_p(BOX3D *b1, BOX3D *b2, BOX3D *ubox)
 {
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("box3d_union_p called: (xmin, xmax), (ymin, ymax), (zmin, zmax)");
-        lwnotice("b1: (%.16f, %.16f),(%.16f, %.16f),(%.16f, %.16f)", b1->xmin, b1->xmax, b1->ymin, b1->ymax, b1->zmin, b1->zmax);
-        lwnotice("b2: (%.16f, %.16f),(%.16f, %.16f),(%.16f, %.16f)", b2->xmin, b2->xmax, b2->ymin, b2->ymax, b2->zmin, b2->zmax);
-#endif
+        LWDEBUG(2, "box3d_union_p called: (xmin, xmax), (ymin, ymax), (zmin, zmax)");
+        LWDEBUGF(4, "b1: (%.16f, %.16f),(%.16f, %.16f),(%.16f, %.16f)", b1->xmin, b1->xmax, b1->ymin, b1->ymax, b1->zmin, b1->zmax);
+        LWDEBUGF(4, "b2: (%.16f, %.16f),(%.16f, %.16f),(%.16f, %.16f)", b2->xmin, b2->xmax, b2->ymin, b2->ymax, b2->zmin, b2->zmax);
 
 	if ( (b1 == NULL) && (b2 == NULL) )
 	{
@@ -410,38 +407,28 @@
 	uchar *loc;
 	BOX3D box3d;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("getbox2d_p call");
-#endif
+	LWDEBUG(2, "getbox2d_p call");
 
 	loc = srl+1;
 
 	if (lwgeom_hasBBOX(type))
 	{
 		/*woot - this is easy */
-#ifdef PGIS_DEBUG
-		lwnotice("getbox2d_p: has box");
-#endif
+		LWDEBUG(4, "getbox2d_p: has box");
 		memcpy(box, loc, sizeof(BOX2DFLOAT4));
 		return 1;
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("getbox2d_p: has no box - computing");
-#endif
+	LWDEBUG(4, "getbox2d_p: has no box - computing");
 
 	/* We have to actually compute it! */
 	if ( ! compute_serialized_box3d_p(srl, &box3d) ) return 0;
 
-#ifdef PGIS_DEBUG
-	lwnotice("getbox2d_p: compute_serialized_box3d returned %p", box3d);
-#endif
+	LWDEBUGF(4, "getbox2d_p: compute_serialized_box3d returned %p", box3d);
 
 	if ( ! box3d_to_box2df_p(&box3d, box) ) return 0;
 
-#ifdef PGIS_DEBUG
-	lwnotice("getbox2d_p: box3d converted to box2d");
-#endif
+	LWDEBUG(4, "getbox2d_p: box3d converted to box2d");
 
 	return 1;
 }
@@ -490,17 +477,13 @@
 	}
 #endif
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("getPoint4d_p called.");
-#endif
+        LWDEBUG(4, "getPoint4d_p called.");
 
 	/* Get a pointer to nth point offset and zmflag */
 	ptr=getPoint_internal(pa, n);
 	zmflag=TYPE_GETZM(pa->dims);
 
-#ifdef PGIS_DEBUG
-        lwnotice("ptr %p, zmflag %d", ptr, zmflag);
-#endif
+        LWDEBUGF(4, "ptr %p, zmflag %d", ptr, zmflag);
 
 	switch (zmflag)
 	{
@@ -577,15 +560,13 @@
 
 	if ( (n<0) || (n>=pa->npoints))
 	{
-		lwnotice("%d out of numpoint range (%d)", n, pa->npoints);
+		LWDEBUGF(4, "%d out of numpoint range (%d)", n, pa->npoints);
 		return 0; /*error */
 	}
 #endif
 
-#ifdef PGIS_DEBUG
-	lwnotice("getPoint3dz_p called on array of %d-dimensions / %u pts",
+	LWDEBUGF(2, "getPoint3dz_p called on array of %d-dimensions / %u pts",
 		TYPE_NDIMS(pa->dims), pa->npoints);
-#endif
 
 	/* Get a pointer to nth point offset */
 	ptr=getPoint_internal(pa, n);
@@ -635,10 +616,8 @@
 	}
 #endif 
 
-#ifdef PGIS_DEBUG
-	lwnotice("getPoint3dm_p(%d) called on array of %d-dimensions / %u pts",
+	LWDEBUGF(2, "getPoint3dm_p(%d) called on array of %d-dimensions / %u pts",
 		n, TYPE_NDIMS(pa->dims), pa->npoints);
-#endif
 
 
 	/* Get a pointer to nth point offset and zmflag */
@@ -792,9 +771,9 @@
 	uint32 npoints)
 {
 	POINTARRAY  *pa;
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("pointArray_construct called.");
-#endif
+	
+	LWDEBUG(2, "pointArray_construct called.");
+
 	pa = (POINTARRAY*)lwalloc(sizeof(POINTARRAY));
 
 	pa->dims = 0;
@@ -803,9 +782,8 @@
 
 	pa->serialized_pointlist = points;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("pointArray_construct returning %p", pa);
-#endif
+	LWDEBUGF(4, "pointArray_construct returning %p", pa);
+
 	return pa;
 }
 
@@ -817,10 +795,9 @@
 int
 pointArray_ptsize(const POINTARRAY *pa)
 {
-#ifdef PGIS_DEBUG_CALLS
-	/*lwnotice("pointArray_ptsize: TYPE_NDIMS(pa->dims)=%x\n",
-		TYPE_NDIMS(pa->dims));*/
-#endif
+	LWDEBUGF(2, "pointArray_ptsize: TYPE_NDIMS(pa->dims)=%x\n",
+		TYPE_NDIMS(pa->dims));
+
 	return sizeof(double)*TYPE_NDIMS(pa->dims);
 }
 
@@ -861,11 +838,8 @@
 int
 lwgeom_getType(uchar type)
 {
+        LWDEBUGF(2, "lwgeom_getType %d", type);
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwgeom_getType %d", type);
-#endif
-
 	return (type & 0x0F);
 }
 
@@ -952,9 +926,7 @@
 	const uchar *loc;
 	int 	t;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_inspect: serialized@%p", serialized_form);
-#endif
+	LWDEBUGF(2, "lwgeom_inspect: serialized@%p", serialized_form);
 
 	if (serialized_form == NULL)
 		return NULL;
@@ -993,10 +965,8 @@
 	result->ngeometries = lw_get_uint32(loc);
 	loc +=4;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_inspect: geometry is a collection of %d elements",
+	LWDEBUGF(3, "lwgeom_inspect: geometry is a collection of %d elements",
 		result->ngeometries);
-#endif
 
 	if ( ! result->ngeometries ) return result;
 
@@ -1004,9 +974,7 @@
 	result->sub_geoms = sub_geoms;
 	sub_geoms[0] = (uchar *)loc;
 
-#ifdef PGIS_DEBUG
-	lwnotice("subgeom[0] @ %p (+%d)", sub_geoms[0], sub_geoms[0]-serialized_form);
-#endif
+	LWDEBUGF(3, "subgeom[0] @ %p (+%d)", sub_geoms[0], sub_geoms[0]-serialized_form);
 
 	for (t=1;t<result->ngeometries; t++)
 	{
@@ -1014,11 +982,8 @@
 		int sub_length = lwgeom_size_subgeom(sub_geoms[t-1], -1);
 		sub_geoms[t] = sub_geoms[t-1] + sub_length;
                 
-#ifdef PGIS_DEBUG
-		lwnotice("subgeom[%d] @ %p (+%d)",
+		LWDEBUGF(3, "subgeom[%d] @ %p (+%d)",
 			t, sub_geoms[t], sub_geoms[0]-serialized_form);
-#endif
-
 	}
 
 	return result;
@@ -1512,43 +1477,35 @@
 	int sub_size;
 	int result = 1; /* type */
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_size called");
-#endif
+	LWDEBUG(2, "lwgeom_size called");
 
 	if (type == POINTTYPE)
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_size: is a point");
-#endif
+		LWDEBUG(3, "lwgeom_size: is a point");
+
 		return lwgeom_size_point(serialized_form);
 	}
 	else if (type == LINETYPE)
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_size: is a line");
-#endif
+		LWDEBUG(3, "lwgeom_size: is a line");
+
 		return lwgeom_size_line(serialized_form);
 	}
         else if(type == CURVETYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("lwgeom_size: is a curve");
-#endif
+                LWDEBUG(3, "lwgeom_size: is a curve");
+
                 return lwgeom_size_curve(serialized_form);
         }
 	else if (type == POLYGONTYPE)
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_size: is a polygon");
-#endif
+		LWDEBUG(3, "lwgeom_size: is a polygon");
+
 		return lwgeom_size_poly(serialized_form);
 	} 
         else if (type == COMPOUNDTYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("lwgeom_size: is a compound curve");
-#endif
+                LWDEBUG(3, "lwgeom_size: is a compound curve");
         }
 
 	if ( type == 0 )
@@ -1564,17 +1521,13 @@
 	 *       be recursing...
 	 */
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_size called on a geoemtry with type %d", type);
-#endif
+	LWDEBUGF(3, "lwgeom_size called on a geoemtry with type %d", type);
 
 	loc = serialized_form+1;
 
 	if (lwgeom_hasBBOX((uchar) serialized_form[0]))
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_size: has bbox");
-#endif
+		LWDEBUG(3, "lwgeom_size: has bbox");
 
 		loc += sizeof(BOX2DFLOAT4);
 		result +=sizeof(BOX2DFLOAT4);
@@ -1582,9 +1535,8 @@
 
 	if (lwgeom_hasSRID( (uchar) serialized_form[0]) )
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_size: has srid");
-#endif
+		LWDEBUG(3, "lwgeom_size: has srid");
+
 		result +=4;
 		loc +=4;
 	}
@@ -1594,23 +1546,20 @@
 	loc +=4;
 	result += 4; /* numgeoms */
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_size called on a geoemtry with %d elems (result so far: %d)", ngeoms, result);
-#endif
+	LWDEBUGF(3, "lwgeom_size called on a geoemtry with %d elems (result so far: %d)", ngeoms, result);
 
 	for (t=0;t<ngeoms;t++)
 	{
 		sub_size = lwgeom_size(loc);
-#ifdef PGIS_DEBUG
-		lwnotice(" subsize %d", sub_size);
-#endif
+
+		LWDEBUGF(3, " subsize %d", sub_size);
+
 		loc += sub_size;
 		result += sub_size;
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_size returning %d", result);
-#endif
+	LWDEBUGF(3, "lwgeom_size returning %d", result);
+
 	return result;
 }
 
@@ -1683,20 +1632,18 @@
 	int sub_size;
 	char nboxes=0;
 
-#ifdef PGIS_DEBUG
-lwnotice("compute_serialized_box3d called on type %d", type);
-#endif
+	LWDEBUGF(2, "compute_serialized_box3d called on type %d", type);
 
 	if (type == POINTTYPE)
 	{
 		LWPOINT *pt = lwpoint_deserialize(srl);
-#ifdef PGIS_DEBUG
-lwnotice("compute_serialized_box3d: lwpoint deserialized");
-#endif
+
+		LWDEBUG(3, "compute_serialized_box3d: lwpoint deserialized");
+
 		result = lwpoint_compute_box3d(pt);
-#ifdef PGIS_DEBUG
-lwnotice("compute_serialized_box3d: bbox found");
-#endif
+
+		LWDEBUG(3, "compute_serialized_box3d: bbox found");
+
 		pfree_point(pt);
 		return result;
 	}
@@ -1754,9 +1701,11 @@
 	{
 		if ( compute_serialized_box3d_p(loc, &b1) ) 
 		{
-#ifdef PGIS_DEBUG
-			lwnotice("Geom %d have box:"); printBOX3D(&b1);
+			LWDEBUG(3, "Geom %d have box:"); 
+#if POSTGIS_DEBUG_LEVEL >= 3
+			printBOX3D(&b1);
 #endif
+
 			if (result)
 			{
 				nboxes += box3d_union_p(result, &b1, result);
@@ -2039,9 +1988,9 @@
 	if ( TYPE_HASBBOX(type) ) flags[flagno++] = 'B';
 	if ( TYPE_HASSRID(type) ) flags[flagno++] = 'S';
 	flags[flagno] = '\0';
-#ifdef PGIS_DEBUG
-	lwnotice("Flags: %s - returning %p", flags, flags);
-#endif
+
+	LWDEBUGF(4, "Flags: %s - returning %p", flags, flags);
+
 	return flags;
 }
 
@@ -2194,9 +2143,7 @@
 		lwalloc, lwerror);
 
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("parse_lwgeom_wkt with %s",wkt_input);
-#endif
+	LWDEBUGF(2, "parse_lwgeom_wkt with %s",wkt_input);
 
 	if (serialized_form == NULL)
 	{

Modified: trunk/lwgeom/lwgeom_box2dfloat4.c
===================================================================
--- trunk/lwgeom/lwgeom_box2dfloat4.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_box2dfloat4.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -16,7 +16,6 @@
 #include "stringBuffer.h"
 
 
-/* #define PGIS_DEBUG */
 
 /* forward defs */
 Datum BOX2DFLOAT4_in(PG_FUNCTION_ARGS);

Modified: trunk/lwgeom/lwgeom_box3d.c
===================================================================
--- trunk/lwgeom/lwgeom_box3d.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_box3d.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -19,7 +19,6 @@
 #include "liblwgeom.h"
 
 
-/*#define PGIS_DEBUG */
 
 #define SHOW_DIGS_DOUBLE 15
 #define MAX_DIGS_DOUBLE (SHOW_DIGS_DOUBLE + 6 + 1 + 3 +1)

Modified: trunk/lwgeom/lwgeom_btree.c
===================================================================
--- trunk/lwgeom/lwgeom_btree.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_btree.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -27,7 +27,6 @@
 Datum lwgeom_gt(PG_FUNCTION_ARGS);
 Datum lwgeom_cmp(PG_FUNCTION_ARGS);
 
-/* #define PGIS_DEBUG */
 
 #if POSTGIS_PGSQL_VERSION == 72
 #define BTREE_SRID_MISMATCH_SEVERITY NOTICE
@@ -47,9 +46,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_lt called");
-#endif
+	POSTGIS_DEBUG(2, "lwgeom_lt called");
 
 	if (pglwgeom_getSRID(geom1) != pglwgeom_getSRID(geom2))
 	{
@@ -62,16 +59,12 @@
 		PG_RETURN_NULL();
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_lt passed getSRID test");
-#endif
+	POSTGIS_DEBUG(3, "lwgeom_lt passed getSRID test");
 
 	getbox2d_p(SERIALIZED_FORM(geom1), &box1);
 	getbox2d_p(SERIALIZED_FORM(geom2), &box2);
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_lt getbox2d_p passed");
-#endif
+	POSTGIS_DEBUG(3, "lwgeom_lt getbox2d_p passed");
 
 	if  ( ! FPeq(box1.xmin , box2.xmin) ) {
 		if  (box1.xmin < box2.xmin)
@@ -104,9 +97,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_le called");
-#endif
+	POSTGIS_DEBUG(2, "lwgeom_le called");
 
 	if (pglwgeom_getSRID(geom1) != pglwgeom_getSRID(geom2))
 	{
@@ -184,9 +175,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_eq called");
-#endif
+	POSTGIS_DEBUG(2, "lwgeom_eq called");
 
 	if (pglwgeom_getSRID(geom1) != pglwgeom_getSRID(geom2))
 	{
@@ -244,9 +233,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_ge called");
-#endif
+	POSTGIS_DEBUG(2, "lwgeom_ge called");
 
 	if (pglwgeom_getSRID(geom1) != pglwgeom_getSRID(geom2))
 	{
@@ -316,9 +303,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_gt called");
-#endif
+	POSTGIS_DEBUG(2, "lwgeom_gt called");
 
 	if (pglwgeom_getSRID(geom1) != pglwgeom_getSRID(geom2))
 	{
@@ -384,9 +369,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_cmp called");
-#endif
+	POSTGIS_DEBUG(2, "lwgeom_cmp called");
 
 	if (pglwgeom_getSRID(geom1) != pglwgeom_getSRID(geom2))
 	{

Modified: trunk/lwgeom/lwgeom_debug.c
===================================================================
--- trunk/lwgeom/lwgeom_debug.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_debug.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -82,9 +82,7 @@
 	int i;
 	char *pad="";
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwcollection_summary called");
-#endif
+	LWDEBUG(2, "lwcollection_summary called");
 
 	result = (char *)lwalloc(size);
 
@@ -98,16 +96,14 @@
 		tmp = lwgeom_summary(col->geoms[i], offset+2);
 		size += strlen(tmp)+1;
 		result = lwrealloc(result, size);
-#if PGIS_DEBUG > 1
-		lwnotice("Reallocated %d bytes for result", size);
-#endif
+
+		LWDEBUGF(4, "Reallocated %d bytes for result", size);
+
 		strcat(result, tmp);
 		lwfree(tmp);
 	}
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwcollection_summary returning");
-#endif
+	LWDEBUG(3, "lwcollection_summary returning");
 
 	return result;
 }
@@ -121,9 +117,7 @@
 	int i;
 	char *pad="";
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoly_summary called");
-#endif
+	LWDEBUG(2, "lwpoly_summary called");
 
 	result = lwalloc(size);
 
@@ -139,9 +133,7 @@
 		strcat(result,tmp);
 	}
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoly_summary returning");
-#endif
+	LWDEBUG(3, "lwpoly_summary returning");
 
 	return result;
 }

Modified: trunk/lwgeom/lwgeom_dump.c
===================================================================
--- trunk/lwgeom/lwgeom_dump.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_dump.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -24,7 +24,6 @@
 #include "profile.h"
 #include "wktparse.h"
 
-/*#define PGIS_DEBUG 1 */
 
 Datum LWGEOM_dump(PG_FUNCTION_ARGS);
 Datum LWGEOM_dump_rings(PG_FUNCTION_ARGS);

Modified: trunk/lwgeom/lwgeom_estimate.c
===================================================================
--- trunk/lwgeom/lwgeom_estimate.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_estimate.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -26,7 +26,6 @@
 #include "liblwgeom.h"
 #include "lwgeom_pg.h"
 
-/*#define DEBUG_GEOMETRY_STATS 1*/
 
 
 #if POSTGIS_PGSQL_VERSION >= 80
@@ -242,10 +241,8 @@
 	sprintf(result,"HISTOGRAM2D(%.15g,%.15g,%.15g,%.15g,%i,%.15g;",
 		histo->xmin,histo->ymin,histo->xmax,histo->ymax,histo->boxesPerSide,histo->avgFeatureArea );
 
-#if PGIS_DEBUG
-	elog(NOTICE,"so far: %s",result);
-	elog(NOTICE,"buffsize=%i, size=%i",size,histo->size);
-#endif
+	POSTGIS_DEBUGF(3, "so far: %s",result);
+	POSTGIS_DEBUGF(3, "buffsize=%i, size=%i",size,histo->size);
 
 	for (t=0;t<histo->boxesPerSide*histo->boxesPerSide;t++)
 	{
@@ -255,11 +252,9 @@
 	}
 
 	strcat(result,")");
-#if PGIS_DEBUG
-	elog(NOTICE,"about to return string (len=%i): -%s-",strlen(result),result);
-	elog(NOTICE, "result@%x", result);
-#endif
 
+	POSTGIS_DEBUGF(3, "about to return string (len=%d): -%s-", (int)strlen(result),result);
+	POSTGIS_DEBUGF(3, "result@%p", result);
 
 	PG_RETURN_CSTRING(result);
 }
@@ -351,12 +346,9 @@
 	xmax = histo->xmax;
 	ymax = histo->ymax;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " build_histogram2d: histogram extent = %g %g, %g %g",
+	POSTGIS_DEBUGF(3, " build_histogram2d: histogram extent = %g %g, %g %g",
 		histo->xmin, histo->ymin, histo->xmax, histo->ymax);
-#endif
 
-
 	result = (LWHISTOGRAM2D *) malloc(histo->size);
 	memcpy(result,histo,histo->size);
 
@@ -380,12 +372,9 @@
 	columnname = DatumGetCString(DirectFunctionCall1(textout,
 		PointerGetDatum(PG_GETARG_DATUM(2))));
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE,"Start build_histogram2d with %i items already existing", sum_area_numb);
-	elog(NOTICE,"table=\"%s\", column = \"%s\"", tablename, columnname);
-#endif
+	POSTGIS_DEBUGF(3, "Start build_histogram2d with %i items already existing", sum_area_numb);
+	POSTGIS_DEBUGF(3, "table=\"%s\", column = \"%s\"", tablename, columnname);
 
-
 	SPIcode = SPI_connect();
 
 	if (SPIcode  != SPI_OK_CONNECT)
@@ -421,16 +410,14 @@
 	while (moredata==TRUE)
 	{
 
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE,"about to fetch...");
-#endif
+
+		POSTGIS_DEBUG(3, "about to fetch...");
+
 		SPI_cursor_fetch(SPIportal, TRUE, tuplimit);
 
 		ntuples = SPI_processed;
 
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE,"processing %d records", ntuples);
-#endif
+		POSTGIS_DEBUGF(3, "processing %d records", ntuples);
 
 		if (ntuples > 0) {
 
@@ -484,10 +471,8 @@
 					 * if the area of the intersect between the box and the grid square > 5% of
 					 */
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE,"box is : (%.15g,%.15g to %.15g,%.15g)",box->low.x,box->low.y, box->high.x, box->high.y);
-	elog(NOTICE,"        search is in x: %i to %i   y: %i to %i",x_idx_min, x_idx_max, y_idx_min,y_idx_max);
-#endif
+					POSTGIS_DEBUGF(3, "box is : (%.15g,%.15g to %.15g,%.15g)",box->xmin,box->ymin, box->xmax, box->ymax);
+					POSTGIS_DEBUGF(3, "        search is in x: %i to %i   y: %i to %i",x_idx_min, x_idx_max, y_idx_min,y_idx_max);
 
 					for (y= y_idx_min; y<=y_idx_max;y++)
 					{
@@ -498,17 +483,15 @@
 							intersect_y = LW_MIN(box->ymax, ymin+ (y+1) * (ymax-ymin)/histo->boxesPerSide ) - LW_MAX(box->ymin, ymin+ y*(ymax-ymin)/histo->boxesPerSide ) ;
 
 							/* for a point, intersect_x=0, intersect_y=0, box_area =0*/
-#if DEBUG_GEOMETRY_STATS
-elog(NOTICE,"x=%i,y=%i, intersect_x= %.15g, intersect_y = %.15g",x,y,intersect_x,intersect_y);
-#endif
+							POSTGIS_DEBUGF(3, "x=%i,y=%i, intersect_x= %.15g, intersect_y = %.15g",x,y,intersect_x,intersect_y);
+
 							if ( (intersect_x>=0) && (intersect_y>=0) )
 							{
 								area_intersect = intersect_x*intersect_y;
 								if (area_intersect >= box_area*0.05)
 								{
-#if DEBUG_GEOMETRY_STATS
-elog(NOTICE,"bump");
-#endif
+									POSTGIS_DEBUG(3, "bump");
+
 									bump++;
 									result->value[x+y*histo->boxesPerSide]++;
 								}
@@ -543,9 +526,7 @@
 		PG_RETURN_NULL() ;
 	}
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE,"finishing up build_histogram2d ");
-#endif
+	POSTGIS_DEBUG(3, "finishing up build_histogram2d ");
 
 	/*pfree(tablename);*/
 	/*pfree(columnname);*/
@@ -556,10 +537,8 @@
 		total+=result->value[t];
 	}
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE ,"histogram finishes with %i items in it - acutally added %i rows and %i bumps\n",total,sum_area_numb_new,bump);
-	elog(NOTICE,"done build_histogram2d ");
-#endif
+	POSTGIS_DEBUGF(3, "histogram finishes with %i items in it - acutally added %i rows and %i bumps\n",total,sum_area_numb_new,bump);
+	POSTGIS_DEBUG(3, "done build_histogram2d ");
 
 
 	/* re-calculate statistics on avg bbox size */
@@ -696,10 +675,8 @@
 	}
 
 
-#if DEBUG_GEOMETRY_STATS
-elog(NOTICE,"start estimate_histogram2d: ");
-elog(NOTICE,"box is : (%.15g,%.15g to %.15g,%.15g)",box->low.x,box->low.y, box->high.x, box->high.y);
-#endif
+	POSTGIS_DEBUG(3, "start estimate_histogram2d: ");
+	POSTGIS_DEBUGF(3, "box is : (%.15g,%.15g to %.15g,%.15g)",box->xmin, box->ymin, box->xmax, box->ymax);
 
 	box_area = (box->xmax-box->xmin)*(box->ymax-box->ymin);
 
@@ -728,9 +705,7 @@
 
 	/* The {x,y}_idx_{min,max} define the grid squares that the box intersects */
 
-#if DEBUG_GEOMETRY_STATS
-elog(NOTICE," search is in x: %i to %i   y: %i to %i",x_idx_min, x_idx_max, y_idx_min,y_idx_max);
-#endif
+	POSTGIS_DEBUGF(3, " search is in x: %i to %i   y: %i to %i",x_idx_min, x_idx_max, y_idx_min,y_idx_max);
 
 	for (y= y_idx_min; y<=y_idx_max;y++)
 	{
@@ -773,10 +748,9 @@
 PG_FUNCTION_INFO_V1(LWGEOM_gist_joinsel);
 Datum LWGEOM_gist_joinsel(PG_FUNCTION_ARGS)
 {
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "LWGEOM_gist_joinsel called (returning %f)",
+	POSTGIS_DEBUGF(2, "LWGEOM_gist_joinsel called (returning %f)",
 		DEFAULT_GEOMETRY_JOINSEL);
-#endif
+
 	PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_JOINSEL);
 }
 
@@ -854,9 +828,7 @@
 	 */
 
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "LWGEOM_gist_joinsel called with jointype %d", jointype);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_gist_joinsel called with jointype %d", jointype);
 
 	/*
 	 * We'll only respond to an inner join/unknown context join
@@ -889,17 +861,14 @@
 	relid2 = getrelid(var2->varno, root->parse->rtable);
 #endif
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "Working with relations oids: %d %d", relid1, relid2);
-#endif
+	POSTGIS_DEBUGF(3, "Working with relations oids: %d %d", relid1, relid2);
 	
 	/* Read the stats tuple from the first column */
 	stats1_tuple = SearchSysCache(STATRELATT, ObjectIdGetDatum(relid1), Int16GetDatum(var1->varattno), 0, 0);
 	if ( ! stats1_tuple )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " No statistics, returning default geometry join selectivity");
-#endif
+		POSTGIS_DEBUG(3, " No statistics, returning default geometry join selectivity");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_JOINSEL);
 	}
 
@@ -909,9 +878,8 @@
 		STATISTIC_KIND_GEOMETRY, InvalidOid, NULL, NULL,
 		(float4 **)gs1ptr, &geomstats1_nvalues) )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " STATISTIC_KIND_GEOMETRY stats not found - returning default geometry join selectivity");
-#endif
+		POSTGIS_DEBUG(3, " STATISTIC_KIND_GEOMETRY stats not found - returning default geometry join selectivity");
+
 		ReleaseSysCache(stats1_tuple);
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_JOINSEL);
 	}
@@ -921,9 +889,8 @@
 	stats2_tuple = SearchSysCache(STATRELATT, ObjectIdGetDatum(relid2), Int16GetDatum(var2->varattno), 0, 0);
 	if ( ! stats2_tuple )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " No statistics, returning default geometry join selectivity");
-#endif
+		POSTGIS_DEBUG(3, " No statistics, returning default geometry join selectivity");
+
 		free_attstatsslot(0, NULL, 0, (float *)geomstats1,
 			geomstats1_nvalues);
 		ReleaseSysCache(stats1_tuple);
@@ -935,9 +902,8 @@
 		STATISTIC_KIND_GEOMETRY, InvalidOid, NULL, NULL,
 		(float4 **)gs2ptr, &geomstats2_nvalues) )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " STATISTIC_KIND_GEOMETRY stats not found - returning default geometry join selectivity");
-#endif
+		POSTGIS_DEBUG(3, " STATISTIC_KIND_GEOMETRY stats not found - returning default geometry join selectivity");
+
 		free_attstatsslot(0, NULL, 0, (float *)geomstats1,
 			geomstats1_nvalues);
 		ReleaseSysCache(stats2_tuple);
@@ -952,20 +918,16 @@
 	 */
 	calculate_column_intersection(&search_box, geomstats1, geomstats2);
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE," -- geomstats1 box: %.15g %.15g, %.15g %.15g",geomstats1->xmin,geomstats1->ymin,geomstats1->xmax,geomstats1->ymax);
-	elog(NOTICE," -- geomstats2 box: %.15g %.15g, %.15g %.15g",geomstats2->xmin,geomstats2->ymin,geomstats2->xmax,geomstats2->ymax);
-	elog(NOTICE," -- calculated intersection box is : %.15g %.15g, %.15g %.15g",search_box.xmin,search_box.ymin,search_box.xmax,search_box.ymax);
-#endif
+	POSTGIS_DEBUGF(3, " -- geomstats1 box: %.15g %.15g, %.15g %.15g",geomstats1->xmin,geomstats1->ymin,geomstats1->xmax,geomstats1->ymax);
+	POSTGIS_DEBUGF(3, " -- geomstats2 box: %.15g %.15g, %.15g %.15g",geomstats2->xmin,geomstats2->ymin,geomstats2->xmax,geomstats2->ymax);
+	POSTGIS_DEBUGF(3, " -- calculated intersection box is : %.15g %.15g, %.15g %.15g",search_box.xmin,search_box.ymin,search_box.xmax,search_box.ymax);
 
 
 	/* Do the selectivity */
 	selectivity1 = estimate_selectivity(&search_box, geomstats1);
 	selectivity2 = estimate_selectivity(&search_box, geomstats2);
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "selectivity1: %.15g   selectivity2: %.15g", selectivity1, selectivity2);
-#endif
+	POSTGIS_DEBUGF(3, "selectivity1: %.15g   selectivity2: %.15g", selectivity1, selectivity2);
 
 	/* Free the statistic tuples */
 	free_attstatsslot(0, NULL, 0, (float *)geomstats1, geomstats1_nvalues);
@@ -1020,11 +982,9 @@
 	rows_returned = 2 * ((num1_tuples * selectivity1) +
 		(num2_tuples * selectivity2));
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "Rows from rel1: %f", num1_tuples * selectivity1);
-	elog(NOTICE, "Rows from rel2: %f", num2_tuples * selectivity2);
-	elog(NOTICE, "Estimated rows returned: %f", rows_returned);
-#endif
+	POSTGIS_DEBUGF(3, "Rows from rel1: %f", num1_tuples * selectivity1);
+	POSTGIS_DEBUGF(3, "Rows from rel2: %f", num2_tuples * selectivity2);
+	POSTGIS_DEBUGF(3, "Estimated rows returned: %f", rows_returned);
 
 	/*
 	 * One (or both) tuple count is zero...
@@ -1035,9 +995,8 @@
 	 */
 	if ( ! total_tuples )
 	{
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "Total tuples == 0, returning default join selectivity");
-#endif
+		POSTGIS_DEBUG(3, "Total tuples == 0, returning default join selectivity");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_JOINSEL);
 	}
 
@@ -1143,54 +1102,44 @@
 	PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 #endif
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE,"LWGEOM_gist_sel was called");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_gist_sel was called");
 
 	if (!get_restriction_var(args, varRelid, &var, &other, &varonleft))
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE,"get_restriction_var FAILED -returning early");
-#endif
+		POSTGIS_DEBUG(3, "get_restriction_var FAILED -returning early");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
 	relid = getrelid(var->varno, root->rtable);
 	if (relid == InvalidOid)
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE,"getrelid FAILED (invalid oid) -returning early");
-#endif
+		POSTGIS_DEBUG(3, "getrelid FAILED (invalid oid) -returning early");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE,"operator's oid = %i (this should be GEOMETRY && GEOMETRY)",operator);
-	elog(NOTICE,"relations' oid = %i (this should be the relation that the && is working on) ",relid);
-	elog(NOTICE,"varatt oid = %i (basically relations column #) ",var->varattno);
-#endif
+	POSTGIS_DEBUGF(3, "operator's oid = %i (this should be GEOMETRY && GEOMETRY)",operator);
+	POSTGIS_DEBUGF(3, "relations' oid = %i (this should be the relation that the && is working on) ",relid);
+	POSTGIS_DEBUGF(3, "varatt oid = %i (basically relations column #) ",var->varattno);
 
 
 	if (IsA(other, Const) &&((Const *) other)->constisnull)
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE,"other operand of && is NULL - returning early");
-#endif
+		POSTGIS_DEBUG(3, "other operand of && is NULL - returning early");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
 	if (IsA(other, Const))
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE,"The other side of the && is a constant with type (oid) = %i and length %i.  This should be GEOMETRY with length -1 (variable length)",((Const*)other)->consttype,((Const*)other)->constlen);
-#endif
+		POSTGIS_DEBUGF(3, "The other side of the && is a constant with type (oid) = %i and length %i.  This should be GEOMETRY with length -1 (variable length)",((Const*)other)->consttype,((Const*)other)->constlen);
 
 	}
 	else
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE,"the other side of && isnt a constant - returning early");
-#endif
+		POSTGIS_DEBUG(3, "the other side of && isnt a constant - returning early");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
@@ -1200,15 +1149,12 @@
 	if ( ! getbox2d_p(in+4, &search_box) )
 	{
 		/* empty geom */
-#if DEBUG_GEOMETRY_STATS 
-		elog(NOTICE, "search box is EMPTY");
-#endif
+		POSTGIS_DEBUG("search box is EMPTY");
+
 		PG_RETURN_FLOAT8(0.0);
 	}
 
-#if DEBUG_GEOMETRY_STATS 
-	elog(NOTICE,"requested search box is : (%.15g %.15g, %.15g %.15g)",search_box->xmin,search_box->ymin,search_box->xmax,search_box->ymax);
-#endif
+	POSTGIS_DEBUGF(3, "requested search box is : (%.15g %.15g, %.15g %.15g)",search_box->xmin,search_box->ymin,search_box->xmax,search_box->ymax);
 
 
 	SPIcode = SPI_connect();
@@ -1219,9 +1165,9 @@
 	}
 
 	sprintf(sql,"SELECT stats FROM GEOMETRY_COLUMNS WHERE attrelid=%u AND varattnum=%i",relid,var->varattno);
-#if DEBUG_GEOMETRY_STATS 
-	elog(NOTICE,"sql:%s",sql);
-#endif
+
+	POSTGIS_DEBUGF(3, "sql:%s",sql);
+
 	SPIcode = SPI_exec(sql, 1 );
 	if (SPIcode  != SPI_OK_SELECT )
 	{
@@ -1233,9 +1179,9 @@
 	if (SPI_processed !=1)
 	{
 		SPI_finish();
-#if DEBUG_GEOMETRY_STATS 
-		elog(NOTICE,"LWGEOM_gist_sel: geometry_columns didnt return a unique value");
-#endif
+
+		POSTGIS_DEBUG(3, "LWGEOM_gist_sel: geometry_columns didnt return a unique value");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL) ;
 	}
 
@@ -1246,38 +1192,35 @@
 	if (isnull)
 	{
 		SPI_finish();
-#if DEBUG_GEOMETRY_STATS 
-		elog(NOTICE,"LWGEOM_gist_sel: geometry_columns returned a null histogram");
-#endif
+
+		POSTGIS_DEBUG(3, "LWGEOM_gist_sel: geometry_columns returned a null histogram");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL) ;
 	}
-#if DEBUG_GEOMETRY_STATS 
-elog(NOTICE,"LWGEOM_gist_sel: checking against estimate_histogram2d");
-#endif
 
+	POSTGIS_DEBUG(3, "LWGEOM_gist_sel: checking against estimate_histogram2d");
+
+
 	/* now we have the histogram, and our search box - use the estimate_histogram2d(histo,box) to get the result! */
 	myest = DatumGetFloat8( DirectFunctionCall2( estimate_lwhistogram2d, datum, PointerGetDatum(&search_box) ) );
 
 	if ( (myest<0) || (myest!=myest) ) /* <0?  or NaN? */
 	{
-#if DEBUG_GEOMETRY_STATS 
-		elog(NOTICE,"LWGEOM_gist_sel: got something crazy back from estimate_histogram2d");
-#endif
+		POSTGIS_DEBUG(3, "LWGEOM_gist_sel: got something crazy back from estimate_histogram2d");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL) ;
 	}
 
 	SPIcode =SPI_finish();
 	if (SPIcode  != SPI_OK_FINISH )
 	{
-#if DEBUG_GEOMETRY_STATS 
-		elog(NOTICE,"LWGEOM_gist_sel: couldnt disconnect from SPI");
-#endif
+		POSTGIS_DEBUG(3, "LWGEOM_gist_sel: couldnt disconnect from SPI");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL) ;
 	}
 
-#if DEBUG_GEOMETRY_STATS 
-elog(NOTICE,"LWGEOM_gist_sel: finished, returning with %lf",myest);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_gist_sel: finished, returning with %lf",myest);
+
         PG_RETURN_FLOAT8(myest);
 }
 
@@ -1335,9 +1278,7 @@
 	memcpy(col, VARDATA(txcol), VARSIZE(txcol)-VARHDRSZ);
 	col[VARSIZE(txcol)-VARHDRSZ]='\0';
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "LWGEOM_estimated_extent called");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_estimated_extent called");
 
 	/* Connect to SPI manager */
 	SPIcode = SPI_connect();
@@ -1360,9 +1301,7 @@
 		sprintf(query, "SELECT stats FROM geometry_columns WHERE f_table_name = '%s' AND f_geometry_column = '%s'", tbl, col);
 	}
 
-#if DEBUG_GEOMETRY_STATS > 1
-	elog(NOTICE, " query: %s", query);
-#endif
+	POSTGIS_DEBUGF(4, " query: %s", query);
 
 	SPIcode = SPI_exec(query, 1);
 	if (SPIcode != SPI_OK_SELECT )
@@ -1380,9 +1319,9 @@
 	if (SPI_processed == 0)
 	{
 		SPI_finish();
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " %d stat rows", SPI_processed);
-#endif
+
+		POSTGIS_DEBUG(3, " %d stat rows", SPI_processed);
+
 		PG_RETURN_NULL() ;
 	}
 
@@ -1393,18 +1332,16 @@
 	if (isnull)
 	{
 		SPI_finish();
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " stats are NULL");
-#endif
+
+		POSTGIS_DEBUG(3, " stats are NULL");
+
 		PG_RETURN_NULL();
 	}
 
 	histo = (LWHISTOGRAM2D *)PG_DETOAST_DATUM(datum);
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " histogram extent = %g %g, %g %g", histo->xmin,
+	POSTGIS_DEBUGF(3, " histogram extent = %g %g, %g %g", histo->xmin,
 		histo->ymin, histo->xmax, histo->ymax);
-#endif
 
 	/*
 	 * Construct box2dfloat4.
@@ -1418,10 +1355,8 @@
 	box->xmax = histo->xmax;
 	box->ymax = histo->ymax;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " histogram extent = %f %f, %f %f", box->xmin,
+	POSTGIS_DEBUGF(3, " histogram extent = %f %f, %f %f", box->xmin,
 		box->ymin, box->xmax, box->ymax);
-#endif
 
 	SPIcode = SPI_finish();
 	if (SPIcode != SPI_OK_FINISH )
@@ -1467,9 +1402,8 @@
 		box->ymax < geomstats->ymin ||
 		box->ymin > geomstats->ymax )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " search_box does not overlaps histogram, returning 0");
-#endif
+		POSTGIS_DEBUG(3, " search_box does not overlaps histogram, returning 0");
+
 		return 0.0;
 	}
 
@@ -1481,9 +1415,8 @@
 		box->ymax >= geomstats->ymax &&
 		box->ymin <= geomstats->ymin )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " search_box contains histogram, returning 1");
-#endif
+		POSTGIS_DEBUG(3, " search_box contains histogram, returning 1");
+
 		return 1.0;
 	}
 
@@ -1493,10 +1426,8 @@
 	histocols = geomstats->cols;
 	historows = geomstats->rows;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " histogram has %d cols, %d rows", histocols, historows);
-	elog(NOTICE, " histogram geosize is %fx%f", geow, geoh);
-#endif
+	POSTGIS_DEBUGF(3, " histogram has %d cols, %d rows", histocols, historows);
+	POSTGIS_DEBUGF(3, " histogram geosize is %fx%f", geow, geoh);
 
 	cell_area = (geow*geoh) / (histocols*historows);
 	box_area = (box->xmax-box->xmin)*(box->ymax-box->ymin);
@@ -1505,17 +1436,15 @@
 	/* Find first overlapping column */
 	x_idx_min = (box->xmin-geomstats->xmin) / geow * histocols;
 	if (x_idx_min < 0) {
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " search_box overlaps %d columns on the left of histogram grid", -x_idx_min);
-#endif
+		POSTGIS_DEBUGF(3, " search_box overlaps %d columns on the left of histogram grid", -x_idx_min);
+
 		/* should increment the value somehow */
 		x_idx_min = 0;
 	}
 	if (x_idx_min >= histocols)
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " search_box overlaps %d columns on the right of histogram grid", x_idx_min-histocols+1);
-#endif
+		POSTGIS_DEBUGF(3, " search_box overlaps %d columns on the right of histogram grid", x_idx_min-histocols+1);
+
 		/* should increment the value somehow */
 		x_idx_min = histocols-1;
 	}
@@ -1524,17 +1453,15 @@
 	y_idx_min = (box->ymin-geomstats->ymin) / geoh * historows;
 	if (y_idx_min <0)
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " search_box overlaps %d columns on the bottom of histogram grid", -y_idx_min);
-#endif
+		POSTGIS_DEBUGF(3, " search_box overlaps %d columns on the bottom of histogram grid", -y_idx_min);
+
 		/* should increment the value somehow */
 		y_idx_min = 0;
 	}
 	if (y_idx_min >= historows)
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " search_box overlaps %d columns on the top of histogram grid", y_idx_min-historows+1);
-#endif
+		POSTGIS_DEBUGF(3, " search_box overlaps %d columns on the top of histogram grid", y_idx_min-historows+1);
+
 		/* should increment the value somehow */
 		y_idx_min = historows-1;
 	}
@@ -1589,21 +1516,18 @@
 			AOI = intersect_x*intersect_y;
 			gain = AOI/cell_area;
 
-#if DEBUG_GEOMETRY_STATS > 1
-			elog(NOTICE, " [%d,%d] cell val %.15f",
+			POSTGIS_DEBUGF(4, " [%d,%d] cell val %.15f",
 					x, y, val);
-			elog(NOTICE, " [%d,%d] AOI %.15f",
+			POSTGIS_DEBUGF(4, " [%d,%d] AOI %.15f",
 					x, y, AOI);
-			elog(NOTICE, " [%d,%d] gain %.15f",
+			POSTGIS_DEBUGF(4, " [%d,%d] gain %.15f",
 					x, y, gain);
-#endif
 
 			val *= gain;
 
-#if DEBUG_GEOMETRY_STATS > 1
-			elog(NOTICE, " [%d,%d] adding %.15f to value",
+			POSTGIS_DEBUGF(4, " [%d,%d] adding %.15f to value",
 				x, y, val);
-#endif
+
 			value += val;
 		}
 	}
@@ -1646,27 +1570,22 @@
 		(y_idx_max-y_idx_min+1);
 	avg_feat_cells = geomstats->avgFeatureCells;
 
-#if DEBUG_GEOMETRY_STATS
-elog(NOTICE, " search_box overlaps %f cells", overlapping_cells);
-elog(NOTICE, " avg feat overlaps %f cells", avg_feat_cells);
-#endif
+	POSTGIS_DEBUGF(3, " search_box overlaps %f cells", overlapping_cells);
+	POSTGIS_DEBUGF(3, " avg feat overlaps %f cells", avg_feat_cells);
 
 	if ( ! overlapping_cells )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " no overlapping cells, returning 0.0");
-#endif
+		POSTGIS_DEBUG(3, " no overlapping cells, returning 0.0");
+
 		return 0.0;
 	}
 
 	gain = 1/LW_MIN(overlapping_cells, avg_feat_cells);
 	selectivity = value*gain;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " SUM(ov_histo_cells)=%f", value);
-	elog(NOTICE, " gain=%f", gain);
-	elog(NOTICE, " selectivity=%f", selectivity);
-#endif
+	POSTGIS_DEBUGF(3, " SUM(ov_histo_cells)=%f", value);
+	POSTGIS_DEBUGF(3, " gain=%f", gain);
+	POSTGIS_DEBUGF(3, " selectivity=%f", selectivity);
 
 	/* prevent rounding overflows */
 	if (selectivity > 1.0) selectivity = 1.0;
@@ -1717,16 +1636,13 @@
 	BOX2DFLOAT4 search_box;
 	float8 selectivity=0;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "LWGEOM_gist_sel called");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_gist_sel called");
 
         /* Fail if not a binary opclause (probably shouldn't happen) */
 	if (list_length(args) != 2)
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, "LWGEOM_gist_sel: not a binary opclause");
-#endif
+		POSTGIS_DEBUG(3, "LWGEOM_gist_sel: not a binary opclause");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
@@ -1747,9 +1663,8 @@
 
 	if ( ! IsA(other, Const) ) 
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " no constant arguments - returning default selectivity");
-#endif
+		POSTGIS_DEBUG(3, " no constant arguments - returning default selectivity");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
@@ -1761,9 +1676,8 @@
 	 */
 	if ( ! IsA(self, Var) ) 
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " no variable argument ? - returning default selectivity");
-#endif
+		POSTGIS_DEBUG(3, " no variable argument ? - returning default selectivity");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
@@ -1774,15 +1688,12 @@
 	in = (uchar *)PG_DETOAST_DATUM( ((Const*)other)->constvalue );
 	if ( ! getbox2d_p(in+4, &search_box) )
 	{
-#if DEBUG_GEOMETRY_STATS 
-		elog(NOTICE, "search box is EMPTY");
-#endif
+		POSTGIS_DEBUG(3, "search box is EMPTY");
+
 		PG_RETURN_FLOAT8(0.0);
 	}
 
-#if DEBUG_GEOMETRY_STATS > 1
-	elog(NOTICE," requested search box is : %.15g %.15g, %.15g %.15g",search_box.xmin,search_box.ymin,search_box.xmax,search_box.ymax);
-#endif
+	POSTGIS_DEBUGF(4, " requested search box is : %.15g %.15g, %.15g %.15g",search_box.xmin,search_box.ymin,search_box.xmax,search_box.ymax);
 
 	/*
 	 * Get pg_statistic row
@@ -1798,9 +1709,8 @@
 	stats_tuple = SearchSysCache(STATRELATT, ObjectIdGetDatum(relid), Int16GetDatum(self->varattno), 0, 0);
 	if ( ! stats_tuple )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " No statistics, returning default estimate");
-#endif
+		POSTGIS_DEBUG(3, " No statistics, returning default estimate");
+
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
 	}
 
@@ -1809,28 +1719,22 @@
 		STATISTIC_KIND_GEOMETRY, InvalidOid, NULL, NULL,
 		(float4 **)gsptr, &geomstats_nvalues) )
 	{
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " STATISTIC_KIND_GEOMETRY stats not found - returning default geometry selectivity");
-#endif
+		POSTGIS_DEBUG(3, " STATISTIC_KIND_GEOMETRY stats not found - returning default geometry selectivity");
+
 		ReleaseSysCache(stats_tuple);
 		PG_RETURN_FLOAT8(DEFAULT_GEOMETRY_SEL);
-
 	}
 
-#if DEBUG_GEOMETRY_STATS > 1
-		elog(NOTICE, " %d read from stats", geomstats_nvalues);
-#endif
+	POSTGIS_DEBUGF(4, " %d read from stats", geomstats_nvalues);
 
-#if DEBUG_GEOMETRY_STATS > 1
-	elog(NOTICE, " histo: xmin,ymin: %f,%f",
+	POSTGIS_DEBUGF(4, " histo: xmin,ymin: %f,%f",
 		geomstats->xmin, geomstats->ymin);
-	elog(NOTICE, " histo: xmax,ymax: %f,%f",
+	POSTGIS_DEBUGF(4, " histo: xmax,ymax: %f,%f",
 		geomstats->xmax, geomstats->ymax);
-	elog(NOTICE, " histo: cols: %f", geomstats->rows);
-	elog(NOTICE, " histo: rows: %f", geomstats->cols);
-	elog(NOTICE, " histo: avgFeatureArea: %f", geomstats->avgFeatureArea);
-	elog(NOTICE, " histo: avgFeatureCells: %f", geomstats->avgFeatureCells);
-#endif
+	POSTGIS_DEBUGF(4, " histo: cols: %f", geomstats->rows);
+	POSTGIS_DEBUGF(4, " histo: rows: %f", geomstats->cols);
+	POSTGIS_DEBUGF(4, " histo: avgFeatureArea: %f", geomstats->avgFeatureArea);
+	POSTGIS_DEBUGF(4, " histo: avgFeatureCells: %f", geomstats->avgFeatureCells);
 
 	/*
 	 * Do the estimation
@@ -1838,9 +1742,7 @@
 	selectivity = estimate_selectivity(&search_box, geomstats);
 
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " returning computed value: %f", selectivity);
-#endif
+	POSTGIS_DEBUGF(3, " returning computed value: %f", selectivity);
 
 	free_attstatsslot(0, NULL, 0, (float *)geomstats, geomstats_nvalues);
 	ReleaseSysCache(stats_tuple);
@@ -1910,11 +1812,9 @@
 	histocells = 160*stats->attr->attstattarget;
 
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "compute_geometry_stats called");
-	elog(NOTICE, " samplerows: %d", samplerows);
-	elog(NOTICE, " histogram cells: %d", histocells);
-#endif
+	POSTGIS_DEBUG(2, "compute_geometry_stats called");
+	POSTGIS_DEBUGF(3, " samplerows: %d", samplerows);
+	POSTGIS_DEBUGF(3, " histogram cells: %d", histocells);
 
 	/*
 	 * We might need less space, but don't think
@@ -1951,9 +1851,8 @@
 		if ( ! getbox2d_p(SERIALIZED_FORM(geom), &box) )
 		{
 			/* Skip empty geometry */
-#if DEBUG_GEOMETRY_STATS 
-			elog(NOTICE, " skipped empty geometry %d", i);
-#endif
+			POSTGIS_DEBUGF(3, " skipped empty geometry %d", i);
+
 			continue;
 		}
 
@@ -1965,9 +1864,8 @@
 			! finite(box.ymin) ||
 			! finite(box.ymax) )
 		{
-#if DEBUG_GEOMETRY_STATS 
-			elog(NOTICE, " skipped infinite geometry %d", i);
-#endif
+			POSTGIS_DEBUGF(3, " skipped infinite geometry %d", i);
+
 			continue;
 		}
 
@@ -2028,12 +1926,10 @@
 
 #if USE_STANDARD_DEVIATION
 
-#if DEBUG_GEOMETRY_STATS 
-	elog(NOTICE, " sample_extent: xmin,ymin: %f,%f",
+	POSTGIS_DEBUGF(3, " sample_extent: xmin,ymin: %f,%f",
 		sample_extent->xmin, sample_extent->ymin);
-	elog(NOTICE, " sample_extent: xmax,ymax: %f,%f",
+	POSTGIS_DEBUGF(3, " sample_extent: xmax,ymax: %f,%f",
 		sample_extent->xmax, sample_extent->ymax);
-#endif
 
 	/*
 	 * Second scan:
@@ -2058,13 +1954,11 @@
 	sdHIGx = sqrt(sdHIGx/notnull_cnt);
 	sdHIGy = sqrt(sdHIGy/notnull_cnt);
 
-#if DEBUG_GEOMETRY_STATS 
-	elog(NOTICE, " standard deviations:");
-	elog(NOTICE, "  LOWx - avg:%f sd:%f", avgLOWx, sdLOWx);
-	elog(NOTICE, "  LOWy - avg:%f sd:%f", avgLOWy, sdLOWy);
-	elog(NOTICE, "  HIGx - avg:%f sd:%f", avgHIGx, sdHIGx);
-	elog(NOTICE, "  HIGy - avg:%f sd:%f", avgHIGy, sdHIGy);
-#endif
+	POSTGIS_DEBUG(3, " standard deviations:");
+	POSTGIS_DEBUGF(3, "  LOWx - avg:%f sd:%f", avgLOWx, sdLOWx);
+	POSTGIS_DEBUGF(3, "  LOWy - avg:%f sd:%f", avgLOWy, sdLOWy);
+	POSTGIS_DEBUGF(3, "  HIGx - avg:%f sd:%f", avgHIGx, sdHIGx);
+	POSTGIS_DEBUGF(3, "  HIGy - avg:%f sd:%f", avgHIGy, sdHIGy);
 
 	histobox.xmin = LW_MAX((avgLOWx - SDFACTOR * sdLOWx),
 		sample_extent->xmin);
@@ -2075,12 +1969,10 @@
 	histobox.ymax = LW_MIN((avgHIGy + SDFACTOR * sdHIGy),
 		sample_extent->ymax); 
 
-#if DEBUG_GEOMETRY_STATS 
-	elog(NOTICE, " sd_extent: xmin,ymin: %f,%f",
+	POSTGIS_DEBUGF(3, " sd_extent: xmin,ymin: %f,%f",
 		histobox.xmin, histobox.ymin);
-	elog(NOTICE, " sd_extent: xmax,ymax: %f,%f",
+	POSTGIS_DEBUGF(3, " sd_extent: xmax,ymax: %f,%f",
 		histobox.xmin, histobox.ymax);
-#endif
 
 	/*
 	 * Third scan:
@@ -2097,9 +1989,8 @@
 			box->ymin > histobox.ymax ||
 			box->ymax < histobox.ymin )
 		{
-#if DEBUG_GEOMETRY_STATS > 1
-	elog(NOTICE, " feat %d is an hard deviant, skipped", i);
-#endif
+			POSTGIS_DEBUGF(4, " feat %d is an hard deviant, skipped", i);
+
 			sampleboxes[i] = NULL;
 			continue;
 		}
@@ -2146,12 +2037,10 @@
 #endif /* USE_STANDARD_DEVIATION */
 
 
-#if DEBUG_GEOMETRY_STATS 
-	elog(NOTICE, " histogram_extent: xmin,ymin: %f,%f",
+	POSTGIS_DEBUGF(3, " histogram_extent: xmin,ymin: %f,%f",
 		histobox.xmin, histobox.ymin);
-	elog(NOTICE, " histogram_extent: xmax,ymax: %f,%f",
+	POSTGIS_DEBUGF(3, " histogram_extent: xmax,ymax: %f,%f",
 		histobox.xmax, histobox.ymax);
-#endif
 
 
 	geow = histobox.xmax - histobox.xmin;
@@ -2181,11 +2070,10 @@
 		}
 		histocells = cols*rows;
 	}
-#if DEBUG_GEOMETRY_STATS 
-	elog(NOTICE, " computed histogram grid size (CxR): %dx%d (%d cells)", cols, rows, histocells);
-#endif
 
+	POSTGIS_DEBUGF(3, " computed histogram grid size (CxR): %dx%d (%d cells)", cols, rows, histocells);
 
+
 	/*
 	 * Create the histogram (GEOM_STATS)
 	 */
@@ -2209,10 +2097,8 @@
 	cell_height = geoh/rows;
 	cell_area = cell_width*cell_height;
 
-#if DEBUG_GEOMETRY_STATS > 2
-	elog(NOTICE, "cell_width: %f", cell_width);
-	elog(NOTICE, "cell_height: %f", cell_height);
-#endif
+	POSTGIS_DEBUGF(4, "cell_width: %f", cell_width);
+	POSTGIS_DEBUGF(4, "cell_height: %f", cell_height);
 	
 
 	/*
@@ -2238,11 +2124,9 @@
 		/* give backend a chance of interrupting us */
 		vacuum_delay_point();
 
-#if DEBUG_GEOMETRY_STATS > 2
-		elog(NOTICE, " feat %d box is %f %f, %f %f",
+		POSTGIS_DEBUGF(4, " feat %d box is %f %f, %f %f",
 				i, box->xmax, box->ymax,
 				box->xmin, box->ymin);
-#endif
 							
 		/* Find first overlapping column */
 		x_idx_min = (box->xmin-geomstats->xmin) / geow * cols;
@@ -2263,10 +2147,9 @@
 		y_idx_max = (box->ymax-geomstats->ymin) / geoh * rows;
 		if (y_idx_max <0) y_idx_max = 0;
 		if (y_idx_max >= rows) y_idx_max = rows-1;
-#if DEBUG_GEOMETRY_STATS > 2
-		elog(NOTICE, " feat %d overlaps columns %d-%d, rows %d-%d",
+
+		POSTGIS_DEBUGF(4, " feat %d overlaps columns %d-%d, rows %d-%d",
 				i, x_idx_min, x_idx_max, y_idx_min, y_idx_max);
-#endif
 
 		/*
 		 * the {x,y}_idx_{min,max}
@@ -2290,27 +2173,24 @@
 
 		examinedsamples++;
 	}
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " examined_samples: %d/%d", examinedsamples, samplerows);
-#endif
 
+	POSTGIS_DEBUGF(3, " examined_samples: %d/%d", examinedsamples, samplerows);
+
 	if ( ! examinedsamples ) {
 		elog(NOTICE, " no examined values, invalid stats");
 		stats->stats_valid = false;
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " no stats have been gathered");
-#endif
+
+		POSTGIS_DEBUG(3, " no stats have been gathered");
+
 		return;
 	}
 
 	/* what about null features (TODO) ? */
 	geomstats->avgFeatureCells = (float4)total_boxes_cells/examinedsamples;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " histo: total_boxes_cells: %d", total_boxes_cells);
-	elog(NOTICE, " histo: avgFeatureArea: %f", geomstats->avgFeatureArea);
-	elog(NOTICE, " histo: avgFeatureCells: %f", geomstats->avgFeatureCells);
-#endif
+	POSTGIS_DEBUGF(3, " histo: total_boxes_cells: %d", total_boxes_cells);
+	POSTGIS_DEBUGF(3, " histo: avgFeatureArea: %f", geomstats->avgFeatureArea);
+	POSTGIS_DEBUGF(3, " histo: avgFeatureCells: %f", geomstats->avgFeatureCells);
 
 
 	/*
@@ -2323,19 +2203,18 @@
 	for (i=0; i<histocells; i++)
 		geomstats->value[i] /= examinedsamples;
 
-#if DEBUG_GEOMETRY_STATS > 1
 	{
 		int x, y;
 		for (x=0; x<cols; x++)
 		{
 			for (y=0; y<rows; y++)
 			{
-				elog(NOTICE, " histo[%d,%d] = %.15f", x, y, geomstats->value[x+y*cols]);
+				POSTGIS_DEBUGF(4, " histo[%d,%d] = %.15f", x, y, geomstats->value[x+y*cols]);
 			}
 		}
 	}
-#endif
 
+
 	/*
 	 * Write the statistics data 
 	 */
@@ -2348,15 +2227,13 @@
 	stats->stawidth = total_width/notnull_cnt;
 	stats->stadistinct = -1.0;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " out: slot 0: kind %d (STATISTIC_KIND_GEOMETRY)",
+	POSTGIS_DEBUGF(3, " out: slot 0: kind %d (STATISTIC_KIND_GEOMETRY)",
 		stats->stakind[0]);
-	elog(NOTICE, " out: slot 0: op %d (InvalidOid)", stats->staop[0]);
-	elog(NOTICE, " out: slot 0: numnumbers %d", stats->numnumbers[0]);
-	elog(NOTICE, " out: null fraction: %d/%d=%g", null_cnt, samplerows, stats->stanullfrac);
-	elog(NOTICE, " out: average width: %d bytes", stats->stawidth);
-	elog(NOTICE, " out: distinct values: all (no check done)");
-#endif
+	POSTGIS_DEBUGF(3, " out: slot 0: op %d (InvalidOid)", stats->staop[0]);
+	POSTGIS_DEBUGF(3, " out: slot 0: numnumbers %d", stats->numnumbers[0]);
+	POSTGIS_DEBUGF(3, " out: null fraction: %d/%d=%g", null_cnt, samplerows, stats->stanullfrac);
+	POSTGIS_DEBUGF(3, " out: average width: %d bytes", stats->stawidth);
+	POSTGIS_DEBUG(3, " out: distinct values: all (no check done)");
 
 	stats->stats_valid = true;
 }
@@ -2394,18 +2271,14 @@
 	VacAttrStats *stats = (VacAttrStats *)PG_GETARG_POINTER(0);
 	Form_pg_attribute attr = stats->attr;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "lwgeom_analyze called");
-#endif
+	POSTGIS_DEBUG(2, "lwgeom_analyze called");
 
 	/* If the attstattarget column is negative, use the default value */
 	/* NB: it is okay to scribble on stats->attr since it's a copy */
         if (attr->attstattarget < 0)
                 attr->attstattarget = default_statistics_target;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " attribute stat target: %d", attr->attstattarget);
-#endif
+	POSTGIS_DEBUGF(3, " attribute stat target: %d", attr->attstattarget);
 
 	/*
 	 * There might be a reason not to analyze this column
@@ -2420,9 +2293,7 @@
 	stats->minrows = 300 * stats->attr->attstattarget;
 	stats->compute_stats = compute_geometry_stats;
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " minrows: %d", stats->minrows);
-#endif
+	POSTGIS_DEBUGF(3, " minrows: %d", stats->minrows);
 
 	/* Indicate we are done successfully */
 	PG_RETURN_BOOL(true);
@@ -2469,9 +2340,7 @@
 		PG_RETURN_NULL();
 	}
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, "LWGEOM_estimated_extent called");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_estimated_extent called");
 
 	/* Connect to SPI manager */
 	SPIcode = SPI_connect();
@@ -2500,11 +2369,11 @@
 	memcpy(col, VARDATA(txcol), VARSIZE(txcol)-VARHDRSZ);
 	col[VARSIZE(txcol)-VARHDRSZ]='\0';
 
-#if DEBUG_GEOMETRY_STATS
+#if POSTGIS_DEBUG_LEVEL > 0 
 	if ( txnsp ) {
-		elog(NOTICE, " schema:%s table:%s column:%s", nsp, tbl, col);
+		POSTGIS_DEBUGF(3, " schema:%s table:%s column:%s", nsp, tbl, col);
 	} else {
-		elog(NOTICE, " schema:current_schema() table:%s column:%s",
+		POSTGIS_DEBUGF(3, " schema:current_schema() table:%s column:%s",
 			tbl, col);
 	}
 #endif
@@ -2523,9 +2392,7 @@
 		sprintf(query, "SELECT has_table_privilege((SELECT usesysid FROM pg_user WHERE usename = session_user), '%s', 'select')", tbl);
 	}
 
-#if DEBUG_GEOMETRY_STATS > 1
-	elog(NOTICE, "permission check sql query is: %s", query);
-#endif
+	POSTGIS_DEBUGF(4, "permission check sql query is: %s", query);
 
 	SPIcode = SPI_exec(query, 1);
 	if (SPIcode != SPI_OK_SELECT)
@@ -2557,9 +2424,7 @@
 		sprintf(query, "SELECT s.stanumbers1[5:8] FROM pg_statistic s, pg_class c, pg_attribute a, pg_namespace n WHERE c.relname = '%s' AND a.attrelid = c.oid AND a.attname = '%s' AND n.nspname = current_schema() AND c.relnamespace = n.oid AND s.starelid=c.oid AND s.staattnum = a.attnum AND staattnum = attnum", tbl, col);
 	}
 
-#if DEBUG_GEOMETRY_STATS > 1
-	elog(NOTICE, " query: %s", query);
-#endif
+	POSTGIS_DEBUGF(4, " query: %s", query);
 
 	SPIcode = SPI_exec(query, 1);
 	if (SPIcode != SPI_OK_SELECT )
@@ -2571,9 +2436,9 @@
 	if (SPI_processed != 1)
 	{
 		SPI_finish();
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " %d stat rows", SPI_processed);
-#endif
+
+		POSTGIS_DEBUGF(3, " %d stat rows", SPI_processed);
+
 		PG_RETURN_NULL() ;
 	}
 
@@ -2584,9 +2449,9 @@
 	if (isnull)
 	{
 		SPI_finish();
-#if DEBUG_GEOMETRY_STATS
-		elog(NOTICE, " stats are NULL");
-#endif
+
+		POSTGIS_DEBUG(3, " stats are NULL");
+
 		PG_RETURN_NULL();
 	}
 	if ( ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array)) != 4 )
@@ -2595,9 +2460,7 @@
 		PG_RETURN_NULL();
 	}
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " stats array has %d elems", ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array)));
-#endif
+	POSTGIS_DEBUGF(3, " stats array has %d elems", ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array)));
 
 	/*
 	 * Construct box2dfloat4.
@@ -2609,10 +2472,8 @@
 	/* Construct the box */
 	memcpy(box, ARR_DATA_PTR(array), sizeof(BOX2DFLOAT4));
 
-#if DEBUG_GEOMETRY_STATS
-	elog(NOTICE, " histogram extent = %g %g, %g %g", box->xmin,
+	POSTGIS_DEBUGF(3, " histogram extent = %g %g, %g %g", box->xmin,
 		box->ymin, box->xmax, box->ymax);
-#endif
 
 	SPIcode = SPI_finish();
 	if (SPIcode != SPI_OK_FINISH )

Modified: trunk/lwgeom/lwgeom_functions_analytic.c
===================================================================
--- trunk/lwgeom/lwgeom_functions_analytic.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_functions_analytic.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -26,14 +26,7 @@
  * --strk at keybit.net;
  ***********************************************************************/
 
-#define VERBOSE 0
 
-#if VERBOSE > 0
-#define REPORT_POINTS_REDUCTION
-#define REPORT_RINGS_REDUCTION
-#define REPORT_RINGS_ADJUSTMENTS
-#endif
-
 /* Prototypes */
 void DP_findsplit2d(POINTARRAY *pts, int p1, int p2, int *split, double *dist);
 POINTARRAY *DP_simplify2d(POINTARRAY *inpts, double epsilon);
@@ -64,9 +57,7 @@
    POINT2D pa, pb, pk;
    double tmp;
 
-#if VERBOSE > 4
-elog(NOTICE, "DP_findsplit called");
-#endif
+   LWDEBUG(4, "DP_findsplit called");
 
    *dist = -1;
    *split = p1;
@@ -77,18 +68,14 @@
       getPoint2d_p(pts, p1, &pa);
       getPoint2d_p(pts, p2, &pb);
 
-#if VERBOSE > 4
-elog(NOTICE, "DP_findsplit: P%d(%f,%f) to P%d(%f,%f)",
-   p1, pa.x, pa.y, p2, pb.x, pb.y);
-#endif
+      LWDEBUGF(4, "DP_findsplit: P%d(%f,%f) to P%d(%f,%f)",
+      p1, pa.x, pa.y, p2, pb.x, pb.y);
 
       for (k=p1+1; k<p2; k++)
       {
          getPoint2d_p(pts, k, &pk);
 
-#if VERBOSE > 4
-elog(NOTICE, "DP_findsplit: P%d(%f,%f)", k, pk.x, pk.y);
-#endif
+         LWDEBUGF(4, "DP_findsplit: P%d(%f,%f)", k, pk.x, pk.y);
 
          /* distance computation */
          tmp = distance2d_pt_seg(&pk, &pa, &pb);
@@ -97,9 +84,8 @@
          {
             *dist = tmp;	/* record the maximum */
             *split = k;
-#if VERBOSE > 4
-elog(NOTICE, "DP_findsplit: P%d is farthest (%g)", k, *dist);
-#endif
+
+            LWDEBUGF(4, "DP_findsplit: P%d is farthest (%g)", k, *dist);
          }
       }
 
@@ -107,9 +93,7 @@
 
    else
    {
-#if VERBOSE > 3
-elog(NOTICE, "DP_findsplit: segment too short, no split/no dist");
-#endif
+      LWDEBUG(3, "DP_findsplit: segment too short, no split/no dist");
    }
 
 }
@@ -131,9 +115,7 @@
 	p1 = 0;
 	stack[++sp] = inpts->npoints-1;
 
-#if VERBOSE > 4
-	elog(NOTICE, "DP_simplify called input has %d pts and %d dims (ptsize: %d)", inpts->npoints, inpts->ndims, ptsize);
-#endif
+	LWDEBUGF(2, "DP_simplify called input has %d pts and %d dims (ptsize: %d)", inpts->npoints, inpts->dims, ptsize);
 
 	/* allocate space for output POINTARRAY */
 	outpts = palloc(sizeof(POINTARRAY));
@@ -143,19 +125,15 @@
 	memcpy(getPoint_internal(outpts, 0), getPoint_internal(inpts, 0),
 		ptsize);
 
-#if VERBOSE > 3
-	elog(NOTICE, "DP_simplify: added P0 to simplified point array (size 1)");
-#endif
+	LWDEBUG(3, "DP_simplify: added P0 to simplified point array (size 1)");
 
-
 	do
 	{
 
 		DP_findsplit2d(inpts, p1, stack[sp], &split, &dist);
-#if VERBOSE > 3
-		elog(NOTICE, "DP_simplify: farthest point from P%d-P%d is P%d (dist. %g)", p1, stack[sp], split, dist);
-#endif
 
+		LWDEBUGF(3, "DP_simplify: farthest point from P%d-P%d is P%d (dist. %g)", p1, stack[sp], split, dist);
+
 		if (dist > epsilon) {
 			stack[++sp] = split;
 		} else {
@@ -163,14 +141,13 @@
 			memcpy(getPoint_internal(outpts, outpts->npoints-1),
 				getPoint_internal(inpts, stack[sp]),
 				ptsize);
-#if VERBOSE > 3
-			elog(NOTICE, "DP_simplify: added P%d to simplified point array (size: %d)", stack[sp], outpts->npoints);
-#endif
+
+			LWDEBUGF(4, "DP_simplify: added P%d to simplified point array (size: %d)", stack[sp], outpts->npoints);
+
 			p1 = stack[sp--];
 		}
-#if VERBOSE > 5
-		elog(NOTICE, "stack pointer = %d", sp);
-#endif
+
+		LWDEBUGF(4, "stack pointer = %d", sp);
 	}
 	while (! (sp<0) );
 
@@ -200,9 +177,7 @@
 	POINTARRAY *opts;
 	LWLINE *oline;
 
-#if VERBOSE
-   elog(NOTICE, "simplify2d_lwline called");
-#endif
+	LWDEBUG(2, "simplify2d_lwline called");
 
 	ipts = iline->points;
 	opts = DP_simplify2d(ipts, dist);
@@ -219,9 +194,7 @@
 	LWPOLY *opoly;
 	int norings=0, ri;
 
-#ifdef REPORT_RINGS_REDUCTION
-	elog(NOTICE, "simplify_polygon3d: simplifying polygon with %d rings", ipoly->nrings);
-#endif
+	LWDEBUGF(2, "simplify_polygon3d: simplifying polygon with %d rings", ipoly->nrings);
 
 	orings = (POINTARRAY **)palloc(sizeof(POINTARRAY *)*ipoly->nrings);
 
@@ -245,18 +218,15 @@
 		if ( opts->npoints < 4 )
 		{
 			pfree(opts);
-#ifdef REPORT_RINGS_ADJUSTMENTS
-			elog(NOTICE, "simplify_polygon3d: ring%d skipped ( <4 pts )", ri);
-#endif
 
+			LWDEBUGF(3, "simplify_polygon3d: ring%d skipped ( <4 pts )", ri);
+
 			if ( ri ) continue;
 			else break;
 		}
 
 
-#ifdef REPORT_POINTS_REDUCTION
-		elog(NOTICE, "simplify_polygon3d: ring%d simplified from %d to %d points", ri, ipts->npoints, opts->npoints);
-#endif
+		LWDEBUGF(3, "simplify_polygon3d: ring%d simplified from %d to %d points", ri, ipts->npoints, opts->npoints);
 
 
 		/*
@@ -268,9 +238,7 @@
 
 	}
 
-#ifdef REPORT_RINGS_REDUCTION
-elog(NOTICE, "simplify_polygon3d: simplified polygon with %d rings", norings);
-#endif
+	LWDEBUGF(3, "simplify_polygon3d: simplified polygon with %d rings", norings);
 
 	if ( ! norings ) return NULL;
 
@@ -536,7 +504,7 @@
 Datum LWGEOM_snaptogrid(PG_FUNCTION_ARGS);
 Datum LWGEOM_snaptogrid_pointoff(PG_FUNCTION_ARGS);
 static int grid_isNull(const gridspec *grid);
-#if VERBOSE
+#if POSTGIS_DEBUG_LEVEL > 0 
 static void grid_print(const gridspec *grid, lwreporter printer);
 #endif
 
@@ -551,7 +519,7 @@
 	else return 0;
 }
 
-#if VERBOSE
+#if POSTGIS_DEBUG_LEVEL > 0 
 /* Print grid using given reporter */
 static void
 grid_print(const gridspec *grid, lwreporter printer)
@@ -578,9 +546,7 @@
 	DYNPTARRAY *dpa;
 	POINTARRAY *opa;
 
-#if VERBOSE
-	elog(NOTICE, "ptarray_grid called on %p", pa);
-#endif
+	LWDEBUGF(2, "ptarray_grid called on %p", pa);
 
 	dpa=dynptarray_create(pa->npoints, pa->dims);
 
@@ -651,22 +617,20 @@
 
 	nrings = 0;
 
-#ifdef REPORT_RINGS_REDUCTION
-	elog(NOTICE, "grid_polygon3d: applying grid to polygon with %d rings",
+	LWDEBUGF(3, "grid_polygon3d: applying grid to polygon with %d rings",
    		poly->nrings);
-#endif
 
 	for (ri=0; ri<poly->nrings; ri++)
 	{
 		POINTARRAY *ring = poly->rings[ri];
 		POINTARRAY *newring;
 
-#ifdef CHECK_RING_IS_CLOSE
+#if POSTGIS_DEBUG_LEVEL >= 4
 		POINT2D p1, p2;
 		getPoint2d_p(ring, 0, &p1);
 		getPoint2d_p(ring, ring->npoints-1, &p2);
 		if ( ! SAMEPOINT(&p1, &p2) )
-			elog(NOTICE, "Before gridding: first point != last point");
+			LWDEBUG(4, "Before gridding: first point != last point");
 #endif
 
 		newring = ptarray_grid(ring, grid);
@@ -675,28 +639,23 @@
 		if ( newring->npoints < 4 )
 		{
 			pfree(newring);
-#ifdef REPORT_RINGS_ADJUSTMENTS
-			elog(NOTICE, "grid_polygon3d: ring%d skipped ( <4 pts )", ri);
-#endif
+
+			LWDEBUGF(3, "grid_polygon3d: ring%d skipped ( <4 pts )", ri);
+
 			if ( ri ) continue;
 			else break; /* this is the external ring, no need to work on holes */
 		}
 
-#ifdef CHECK_RING_IS_CLOSE
+#if POSTGIS_DEBUG_LEVEL >= 4
 		getPoint2d_p(newring, 0, &p1);
 		getPoint2d_p(newring, newring->npoints-1, &p2);
 		if ( ! SAMEPOINT(&p1, &p2) )
-			elog(NOTICE, "After gridding: first point != last point");
+			LWDEBUG(4, "After gridding: first point != last point");
 #endif
 
+		LWDEBUGF(3, "grid_polygon3d: ring%d simplified from %d to %d points", ri,
+			ring->npoints, newring->npoints);
 
-
-#ifdef REPORT_POINTS_REDUCTION
-elog(NOTICE, "grid_polygon3d: ring%d simplified from %d to %d points", ri,
-	ring->npoints, newring->npoints);
-#endif
-
-
 		/*
 		 * Add ring to simplified ring array
 		 * (TODO: dinamic allocation of pts_per_ring)
@@ -713,9 +672,7 @@
 		newrings[nrings++] = newring;
 	}
 
-#ifdef REPORT_RINGS_REDUCTION
-elog(NOTICE, "grid_polygon3d: simplified polygon with %d rings", nrings);
-#endif
+	LWDEBUGF(3, "grid_polygon3d: simplified polygon with %d rings", nrings);
 
 	if ( ! nrings ) return NULL;
 
@@ -734,9 +691,7 @@
 	/* TODO: grid bounding box ? */
 	opoint = lwpoint_construct(point->SRID, NULL, opa);
 
-#if VERBOSE
-	elog(NOTICE, "lwpoint_grid called");
-#endif
+	LWDEBUG(2, "lwpoint_grid called");
 
 	return opoint;
 }
@@ -823,9 +778,7 @@
 
 	in_lwgeom = lwgeom_deserialize(SERIALIZED_FORM(in_geom));
 
-#if VERBOSE
-	elog(NOTICE, "SnapToGrid got a %s", lwgeom_typename(TYPE_GETTYPE(in_lwgeom->type)));
-#endif
+	POSTGIS_DEBUGF(3, "SnapToGrid got a %s", lwgeom_typename(TYPE_GETTYPE(in_lwgeom->type)));
 
    	out_lwgeom = lwgeom_grid(in_lwgeom, &grid);
 	if ( out_lwgeom == NULL ) PG_RETURN_NULL();
@@ -861,9 +814,7 @@
 	}
 #endif /* 0 */
 
-#if VERBOSE
-	elog(NOTICE, "SnapToGrid made a %s", lwgeom_typename(TYPE_GETTYPE(out_lwgeom->type)));
-#endif
+	POSTGIS_DEBUGF(3, "SnapToGrid made a %s", lwgeom_typename(TYPE_GETTYPE(out_lwgeom->type)));
 
 	out_geom = pglwgeom_serialize(out_lwgeom);
 
@@ -917,7 +868,7 @@
 	if (TYPE_HASM(in_lwpoint->type) ) grid.ipm = offsetpoint.m;
 	else grid.ipm=0;
 
-#if VERBOSE
+#if POSTGIS_DEBUG_LEVEL >= 4 
 	grid_print(&grid, lwnotice);
 #endif
 
@@ -929,9 +880,7 @@
 
 	in_lwgeom = lwgeom_deserialize(SERIALIZED_FORM(in_geom));
 
-#if VERBOSE
-	elog(NOTICE, "SnapToGrid got a %s", lwgeom_typename(TYPE_GETTYPE(in_lwgeom->type)));
-#endif
+	POSTGIS_DEBUGF(3, "SnapToGrid got a %s", lwgeom_typename(TYPE_GETTYPE(in_lwgeom->type)));
 
    	out_lwgeom = lwgeom_grid(in_lwgeom, &grid);
 	if ( out_lwgeom == NULL ) PG_RETURN_NULL();
@@ -967,9 +916,7 @@
 	}
 #endif /* 0 */
 
-#if VERBOSE
-	elog(NOTICE, "SnapToGrid made a %s", lwgeom_typename(TYPE_GETTYPE(out_lwgeom->type)));
-#endif
+	POSTGIS_DEBUGF(3, "SnapToGrid made a %s", lwgeom_typename(TYPE_GETTYPE(out_lwgeom->type)));
 
 	out_geom = pglwgeom_serialize(out_lwgeom);
 
@@ -1119,22 +1066,19 @@
                 maxY = seg2->y;
                 minY = seg1->y;
         }
-#ifdef PGIS_DEBUG
-        lwnotice("maxX minX/maxY minY: %.8f %.8f/%.8f %.8f", maxX, minX, maxY, minY);
-#endif
 
+        LWDEBUGF(3, "maxX minX/maxY minY: %.8f %.8f/%.8f %.8f", maxX, minX, maxY, minY);
+
         if(maxX < point->x || minX > point->x)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("X value %.8f falls outside the range %.8f-%.8f", point->x, minX, maxX);
-#endif
+                LWDEBUGF(3, "X value %.8f falls outside the range %.8f-%.8f", point->x, minX, maxX);
+
                 return 0;
         }
         else if(maxY < point->y || minY > point->y)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Y value %.8f falls outside the range %.8f-%.8f", point->y, minY, maxY);
-#endif
+                LWDEBUGF(3, "Y value %.8f falls outside the range %.8f-%.8f", point->y, minY, maxY);
+
                 return 0;
         }
         return 1;
@@ -1153,10 +1097,9 @@
         POINT2D seg1;
         POINT2D seg2;
         LWMLINE *lines;
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("point_in_ring called.");
-#endif
 
+        LWDEBUG(2, "point_in_ring called.");
+
         lines = findLineSegments(root, point->y);
         if(!lines)
                 return -1;
@@ -1168,17 +1111,16 @@
 
 
                 side = determineSide(&seg1, &seg2, point);
-#ifdef PGIS_DEBUG
-                lwnotice("segment: (%.8f, %.8f),(%.8f, %.8f)", seg1.x, seg1.y, seg2.x, seg2.y);
-                lwnotice("side result: %.8f", side);
-                lwnotice("counterclockwise wrap %d, clockwise wrap %d", FP_CONTAINS_BOTTOM(seg1.y,point->y,seg2.y), FP_CONTAINS_BOTTOM(seg2.y,point->y,seg1.y));
-#endif
+
+                LWDEBUGF(3, "segment: (%.8f, %.8f),(%.8f, %.8f)", seg1.x, seg1.y, seg2.x, seg2.y);
+                LWDEBUGF(3, "side result: %.8f", side);
+                LWDEBUGF(3, "counterclockwise wrap %d, clockwise wrap %d", FP_CONTAINS_BOTTOM(seg1.y,point->y,seg2.y), FP_CONTAINS_BOTTOM(seg2.y,point->y,seg1.y));
+
                 /* zero length segments are ignored. */
                 if(((seg2.x-seg1.x)*(seg2.x-seg1.x)+(seg2.y-seg1.y)*(seg2.y-seg1.y)) < 1e-12*1e-12) 
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("segment is zero length... ignoring.");
-#endif
+                        LWDEBUG(3, "segment is zero length... ignoring.");
+
                         continue;
                 }
 
@@ -1187,9 +1129,8 @@
                 {
                         if(isOnSegment(&seg1, &seg2, point) == 1)
                         {
-#ifdef PGIS_DEBUG
-                                lwnotice("point on ring boundary between points %d, %d", i, i+1);
-#endif
+                                LWDEBUGF(3, "point on ring boundary between points %d, %d", i, i+1);
+
                                 return 0;
                         }
                 }
@@ -1200,9 +1141,8 @@
                  */
                 else if(FP_CONTAINS_BOTTOM(seg1.y,point->y,seg2.y) && side>0)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("incrementing winding number.");
-#endif
+                        LWDEBUG(3, "incrementing winding number.");
+
                         ++wn;
                 }
                 /*
@@ -1212,16 +1152,14 @@
                  */
                 else if(FP_CONTAINS_BOTTOM(seg2.y,point->y,seg1.y) && side<0)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("decrementing winding number.");
-#endif
+                        LWDEBUG(3, "decrementing winding number.");
+
                         --wn;
                 }
         }
 
-#ifdef PGIS_DEBUG
-        lwnotice("winding number %d", wn);
-#endif
+        LWDEBUGF(3, "winding number %d", wn);
+
         if(wn == 0)
         	return -1;
         return 1;
@@ -1240,10 +1178,9 @@
         double side;
         POINT2D seg1;
         POINT2D seg2;
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("point_in_ring called.");
-#endif
 
+        LWDEBUG(2, "point_in_ring called.");
+
         
         for(i=0; i<pts->npoints-1; i++)
         {
@@ -1252,17 +1189,16 @@
 
 
                 side = determineSide(&seg1, &seg2, point);
-#ifdef PGIS_DEBUG
-                lwnotice("segment: (%.8f, %.8f),(%.8f, %.8f)", seg1.x, seg1.y, seg2.x, seg2.y);
-                lwnotice("side result: %.8f", side);
-                lwnotice("counterclockwise wrap %d, clockwise wrap %d", FP_CONTAINS_BOTTOM(seg1.y,point->y,seg2.y), FP_CONTAINS_BOTTOM(seg2.y,point->y,seg1.y));
-#endif
+
+                LWDEBUGF(3, "segment: (%.8f, %.8f),(%.8f, %.8f)", seg1.x, seg1.y, seg2.x, seg2.y);
+                LWDEBUGF(3, "side result: %.8f", side);
+                LWDEBUGF(3, "counterclockwise wrap %d, clockwise wrap %d", FP_CONTAINS_BOTTOM(seg1.y,point->y,seg2.y), FP_CONTAINS_BOTTOM(seg2.y,point->y,seg1.y));
+
                 /* zero length segments are ignored. */
                 if(((seg2.x-seg1.x)*(seg2.x-seg1.x)+(seg2.y-seg1.y)*(seg2.y-seg1.y)) < 1e-12*1e-12) 
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("segment is zero length... ignoring.");
-#endif
+                        LWDEBUG(3, "segment is zero length... ignoring.");
+
                         continue;
                 }
 
@@ -1271,9 +1207,8 @@
                 {
                         if(isOnSegment(&seg1, &seg2, point) == 1)
                         {
-#ifdef PGIS_DEBUG
-                                lwnotice("point on ring boundary between points %d, %d", i, i+1);
-#endif
+                                LWDEBUGF(3, "point on ring boundary between points %d, %d", i, i+1);
+
                                 return 0;
                         }
                 }
@@ -1284,9 +1219,8 @@
                  */
                 else if(FP_CONTAINS_BOTTOM(seg1.y,point->y,seg2.y) && side>0)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("incrementing winding number.");
-#endif
+                        LWDEBUG(3, "incrementing winding number.");
+
                         ++wn;
                 }
                 /*
@@ -1296,16 +1230,14 @@
                  */
                 else if(FP_CONTAINS_BOTTOM(seg2.y,point->y,seg1.y) && side<0)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("decrementing winding number.");
-#endif
+                        LWDEBUG(3, "decrementing winding number.");
+
                         --wn;
                 }
         }
 
-#ifdef PGIS_DEBUG
-        lwnotice("winding number %d", wn);
-#endif
+        LWDEBUGF(3, "winding number %d", wn);
+
         if(wn == 0)
         	return -1;
         return 1;
@@ -1320,18 +1252,15 @@
         int i;
         POINT2D pt;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("point_in_polygon called for %p %d %p.", root, ringCount, point);
-#endif
+        LWDEBUGF(2, "point_in_polygon called for %p %d %p.", root, ringCount, point);
 
         getPoint2d_p(point->point, 0, &pt);
         /* assume bbox short-circuit has already been attempted */
         
         if(point_in_ring(root[0], &pt) != 1) 
         {
-#ifdef PGIS_DEBUG
-                lwnotice("point_in_polygon: outside exterior ring.");
-#endif
+                LWDEBUG(3, "point_in_polygon: outside exterior ring.");
+
                 return 0;
         }
 
@@ -1339,9 +1268,8 @@
         {
                 if(point_in_ring(root[i], &pt) != -1)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("point_in_polygon: within hole %d.", i);
-#endif
+                        LWDEBUGF(3, "point_in_polygon: within hole %d.", i);
+
                         return 0;
                 }
         }
@@ -1358,9 +1286,7 @@
         POINTARRAY *ring;
         POINT2D pt;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("point_in_polygon_deprecated called.");
-#endif
+        LWDEBUG(2, "point_in_polygon_deprecated called.");
 
         getPoint2d_p(point->point, 0, &pt);
         /* assume bbox short-circuit has already been attempted */
@@ -1370,9 +1296,8 @@
         /* if(point_in_ring(root, &pt) != 1)  */
         if(point_in_ring_deprecated(polygon->rings[0], &pt) != 1)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("point_in_polygon: outside exterior ring.");
-#endif
+                LWDEBUG(3, "point_in_polygon: outside exterior ring.");
+
                 return 0;
         }
 
@@ -1383,9 +1308,8 @@
                 /* if(point_in_ring(root, &pt) != -1) */
                 if(point_in_ring_deprecated(polygon->rings[i], &pt) != -1)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("point_in_polygon: within hole %d.", i);
-#endif
+                        LWDEBUGF(3, "point_in_polygon: within hole %d.", i);
+
                         return 0;
                 }
         }
@@ -1401,18 +1325,15 @@
         int i;
         POINT2D pt;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("point_outside_polygon called.");
-#endif
+        LWDEBUG(2, "point_outside_polygon called.");
 
         getPoint2d_p(point->point, 0, &pt);
         /* assume bbox short-circuit has already been attempted */
         
         if(point_in_ring(root[0], &pt) == -1)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("point_outside_polygon: outside exterior ring.");
-#endif
+                LWDEBUG(3, "point_outside_polygon: outside exterior ring.");
+
                 return 1;
         }
 
@@ -1420,9 +1341,8 @@
         {
                 if(point_in_ring(root[i], &pt) == 1)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("point_outside_polygon: within hole %d.", i);
-#endif
+                        LWDEBUGF(3, "point_outside_polygon: within hole %d.", i);
+
                         return 1;
                 }
         }
@@ -1439,9 +1359,7 @@
         POINTARRAY *ring;
         POINT2D pt;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("point_outside_polygon_deprecated called.");
-#endif
+        LWDEBUG(2, "point_outside_polygon_deprecated called.");
 
         getPoint2d_p(point->point, 0, &pt);
         /* assume bbox short-circuit has already been attempted */
@@ -1451,9 +1369,8 @@
         /* if(point_in_ring(root, &pt) == -1) */
         if(point_in_ring_deprecated(ring, &pt) == -1)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("point_outside_polygon_deprecated: outside exterior ring.");
-#endif
+                LWDEBUG(3, "point_outside_polygon_deprecated: outside exterior ring.");
+
                 return 1;
         }
 
@@ -1464,9 +1381,8 @@
                 /* if(point_in_ring(root, &pt) == 1)  */
                 if(point_in_ring_deprecated(ring, &pt) == 1)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("point_outside_polygon_deprecated: within hole %d.", i);
-#endif
+                        LWDEBUGF(3, "point_outside_polygon_deprecated: within hole %d.", i);
+
                         return 1;
                 }
         }
@@ -1482,9 +1398,7 @@
 {
         int i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("point_in_multipolygon called.");
-#endif
+        LWDEBUG(2, "point_in_multipolygon called.");
 
         for(i=1; i<mpolygon->ngeoms; i++)
         {

Modified: trunk/lwgeom/lwgeom_functions_basic.c
===================================================================
--- trunk/lwgeom/lwgeom_functions_basic.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_functions_basic.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -27,7 +27,6 @@
 #include "profile.h"
 #include "wktparse.h"
 
-/*#define PGIS_DEBUG 1*/
 
 Datum LWGEOM_mem_size(PG_FUNCTION_ARGS);
 Datum LWGEOM_summary(PG_FUNCTION_ARGS);
@@ -333,9 +332,7 @@
 	double area = 0.0;
 	int i;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "in LWGEOM_area_polygon");
-#endif
+	POSTGIS_DEBUG(2, "in LWGEOM_area_polygon");
 
 	for (i=0; i<inspected->ngeometries; i++)
 	{
@@ -351,9 +348,8 @@
                         area += lwgeom_curvepolygon_area(curvepoly);
                 }
                 lwgeom_release(tmp);
-#ifdef PGIS_DEBUG
-		elog(NOTICE, " LWGEOM_area_polygon found a poly (%f)", area);
-#endif
+
+		POSTGIS_DEBUGF(3, " LWGEOM_area_polygon found a poly (%f)", area);
 	}
 	
 	pfree_inspected(inspected);
@@ -378,18 +374,15 @@
 	double dist = 0.0;
 	int i;
 
-#ifdef PGIS_DEBUG
-elog(NOTICE, "in LWGEOM_length2d");
-#endif
+	POSTGIS_DEBUG(2, "in LWGEOM_length2d");
 
 	for (i=0; i<inspected->ngeometries; i++)
 	{
 		line = lwgeom_getline_inspected(inspected, i);
 		if ( line == NULL ) continue;
 		dist += lwgeom_pointarray_length2d(line->points);
-#ifdef PGIS_DEBUG
-elog(NOTICE, " LWGEOM_length2d found a line (%f)", dist);
-#endif
+
+		POSTGIS_DEBUGF(3, " LWGEOM_length2d found a line (%f)", dist);
 	}
 
 	pfree_inspected(inspected);
@@ -511,9 +504,7 @@
 	uchar *loc;
 
 		
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_force2d_recursive: call");
-#endif
+	LWDEBUG(2, "lwgeom_force2d_recursive: call");
 
 	type = lwgeom_getType(serialized[0]);
 
@@ -532,25 +523,23 @@
 		lwfree(newpts.serialized_pointlist);
 		lwfree(point);
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force2d_recursive returning");
-#endif
+		LWDEBUG(3, "lwgeom_force2d_recursive returning");
+
 		return;
 	}
 
 	if ( type == LINETYPE )
 	{
 		line = lwline_deserialize(serialized);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force2d_recursive: it's a line with %d points", line->points->npoints);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force2d_recursive: it's a line with %d points", line->points->npoints);
+
 		TYPE_SETZM(newpts.dims, 0, 0);
 		newpts.npoints = line->points->npoints;
 		newpts.serialized_pointlist = lwalloc(sizeof(POINT2D)*line->points->npoints);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force2d_recursive: %d bytes pointlist allocated", sizeof(POINT2D)*line->points->npoints);
-#endif
 
+		LWDEBUGF(3, "lwgeom_force2d_recursive: %d bytes pointlist allocated", sizeof(POINT2D)*line->points->npoints);
+
 		loc = newpts.serialized_pointlist;
 		for (j=0; j<line->points->npoints; j++)
 		{
@@ -564,25 +553,23 @@
 		lwfree(newpts.serialized_pointlist);
 		lwfree(line);
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force2d_recursive returning");
-#endif
+		LWDEBUG(3, "lwgeom_force2d_recursive returning");
+
 		return;
 	}
 
         if( type == CURVETYPE )
         {
                 curve = lwcurve_deserialize(serialized);
-#ifdef PGIS_DEBUG
-                elog(NOTICE, "lwgeom_force2d_recursize: it's a curve with %d points", curve->points->npoints);
-#endif
+
+                LWDEBUGF(3, "lwgeom_force2d_recursize: it's a curve with %d points", curve->points->npoints);
+
                 TYPE_SETZM(newpts.dims, 0, 0);
                 newpts.npoints = curve->points->npoints;
                 newpts.serialized_pointlist = lwalloc(sizeof(POINT2D)*curve->points->npoints);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force2d_recursive: %d bytes pointlist allocated", sizeof(POINT2D)*curve->points->npoints);
-#endif
 
+		LWDEBUGF(3, "lwgeom_force2d_recursive: %d bytes pointlist allocated", sizeof(POINT2D)*curve->points->npoints);
+
                 loc = newpts.serialized_pointlist;
                 for (j=0; j<curve->points->npoints; j++)
                 {
@@ -629,9 +616,8 @@
 		lwfree(poly);
 		/* TODO: free nrigs[*]->serialized_pointlist */
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force2d_recursive returning");
-#endif
+		LWDEBUG(3, "lwgeom_force2d_recursive returning");
+
 		return;
 	}
 
@@ -649,9 +635,7 @@
 	 * first and then call us again
 	 */
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force2d_recursive: it's a collection (%s)", lwgeom_typename(type));
-#endif
+	LWDEBUGF(3, "lwgeom_force2d_recursive: it's a collection (%s)", lwgeom_typename(type));
 
 
 	/* Add type */
@@ -662,9 +646,7 @@
 	totsize++;
 	loc=serialized+1;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_force2d_recursive: added collection type (%s[%s]) - size:%d", lwgeom_typename(type), lwgeom_typeflags(newtypefl), totsize);
-#endif
+	LWDEBUGF(3, "lwgeom_force2d_recursive: added collection type (%s[%s]) - size:%d", lwgeom_typename(type), lwgeom_typeflags(newtypefl), totsize);
 
 	if ( lwgeom_hasBBOX(serialized[0]) != lwgeom_hasBBOX(newtypefl) )
 		lwerror("typeflag mismatch in BBOX");
@@ -678,9 +660,8 @@
 		optr += sizeof(BOX2DFLOAT4);
 		totsize += sizeof(BOX2DFLOAT4);
 		loc += sizeof(BOX2DFLOAT4);
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_force2d_recursive: added collection bbox - size:%d", totsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force2d_recursive: added collection bbox - size:%d", totsize);
 	}
 
 	/* Add SRID if any */
@@ -690,9 +671,8 @@
 		optr += 4;
 		totsize += 4;
 		loc += 4;
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_force2d_recursive: added collection SRID - size:%d", totsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force2d_recursive: added collection SRID - size:%d", totsize);
 	}
 
 	/* Add numsubobjects */
@@ -700,13 +680,11 @@
 	optr += sizeof(uint32);
 	totsize += sizeof(uint32);
 	loc += sizeof(uint32);
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_force2d_recursive: added collection ngeoms - size:%d", totsize);
-#endif
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_force2d_recursive: inspecting subgeoms");
-#endif
+	LWDEBUGF(3, "lwgeom_force2d_recursive: added collection ngeoms - size:%d", totsize);
+
+	LWDEBUG(3, "lwgeom_force2d_recursive: inspecting subgeoms");
+
 	/* Now recurse for each subobject */
 	inspected = lwgeom_inspect(serialized);
 	for (i=0; i<inspected->ngeometries; i++)
@@ -715,16 +693,13 @@
 		lwgeom_force2d_recursive(subgeom, optr, &size);
 		totsize += size;
 		optr += size;
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force2d_recursive: added elem %d size: %d (tot: %d)",
-	i, size, totsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force2d_recursive: added elem %d size: %d (tot: %d)",
+			i, size, totsize);
 	}
 	pfree_inspected(inspected);
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force2d_recursive returning");
-#endif
+	LWDEBUG(3, "lwgeom_force2d_recursive returning");
 
 	if ( retsize ) *retsize = totsize;
 }
@@ -754,9 +729,7 @@
 	POINT3DZ point3dz;
 
 		
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_force3dz_recursive: call");
-#endif
+	LWDEBUG(2, "lwgeom_force3dz_recursive: call");
 
 	type = lwgeom_getType(serialized[0]);
 
@@ -772,18 +745,18 @@
 		point->point = &newpts;
 		TYPE_SETZM(point->type, 1, 0);
 		lwpoint_serialize_buf(point, optr, retsize);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force3dz_recursive: it's a point, size:%d", *retsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force3dz_recursive: it's a point, size:%d", *retsize);
+
 		return;
 	}
 
 	if ( type == LINETYPE )
 	{
 		line = lwline_deserialize(serialized);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force3dz_recursive: it's a line");
-#endif
+
+		LWDEBUG(3, "lwgeom_force3dz_recursive: it's a line");
+
 		TYPE_SETZM(newpts.dims, 1, 0);
 		newpts.npoints = line->points->npoints;
 		newpts.serialized_pointlist = lwalloc(sizeof(POINT3DZ)*line->points->npoints);
@@ -797,18 +770,18 @@
 		line->points = &newpts;
 		TYPE_SETZM(line->type, 1, 0);
 		lwline_serialize_buf(line, optr, retsize);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force3dz_recursive: it's a line, size:%d", *retsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force3dz_recursive: it's a line, size:%d", *retsize);
+
 		return;
 	}
 
         if ( type == CURVETYPE )
         {
                 curve = lwcurve_deserialize(serialized);
-#ifdef PGIS_DEBUG
-                elog(NOTICE, "lwgeom_force3dz_recursize: it's a curve");
-#endif
+
+                LWDEBUG(3, "lwgeom_force3dz_recursize: it's a curve");
+
                 TYPE_SETZM(newpts.dims, 1, 0);
                 newpts.npoints = curve->points->npoints;
                 newpts.serialized_pointlist = lwalloc(sizeof(POINT3DZ)*curve->points->npoints);
@@ -822,9 +795,9 @@
                 curve->points = &newpts;
                 TYPE_SETZM(curve->type, 1, 0);
                 lwcurve_serialize_buf(curve, optr, retsize);
-#ifdef PGIS_DEBUG
-                elog(NOTICE, "lwgeom_force3dz_recursive: it's a curve, size:%d", *retsize);
-#endif
+
+                LWDEBUGF(3, "lwgeom_force3dz_recursive: it's a curve, size:%d", *retsize);
+
                 return;
         }
 
@@ -856,9 +829,9 @@
 		poly->rings = nrings;
 		TYPE_SETZM(poly->type, 1, 0);
 		lwpoly_serialize_buf(poly, optr, retsize);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force3dz_recursive: it's a poly, size:%d", *retsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force3dz_recursive: it's a poly, size:%d", *retsize);
+
 		return;
 	}
 
@@ -867,9 +840,7 @@
 	 * first and then call us again
 	 */
 
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force3dz_recursive: it's a collection (type:%d)", type);
-#endif
+	LWDEBUGF(3, "lwgeom_force3dz_recursive: it's a collection (type:%d)", type);
 
 	/* Add type */
 	*optr = lwgeom_makeType_full(1, 0, lwgeom_hasSRID(serialized[0]),
@@ -901,9 +872,7 @@
 	optr += 4;
 	totsize += 4;
 
-#ifdef PGIS_DEBUG
-elog(NOTICE, " collection header size:%d", totsize);
-#endif
+	LWDEBUGF(3, " collection header size:%d", totsize);
 
 	/* Now recurse for each suboject */
 	inspected = lwgeom_inspect(serialized);
@@ -913,9 +882,8 @@
 		lwgeom_force3dz_recursive(subgeom, optr, &size);
 		totsize += size;
 		optr += size;
-#ifdef PGIS_DEBUG
-elog(NOTICE, " elem %d size: %d (tot: %d)", i, size, totsize);
-#endif
+
+		LWDEBUGF(3, " elem %d size: %d (tot: %d)", i, size, totsize);
 	}
 	pfree_inspected(inspected);
 
@@ -948,9 +916,7 @@
 	uchar *loc;
 
 		
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_force3dm_recursive: call");
-#endif
+	LWDEBUG(2, "lwgeom_force3dm_recursive: call");
 
 	type = lwgeom_getType(serialized[0]);
 
@@ -969,25 +935,23 @@
 		lwfree(newpts.serialized_pointlist);
 		lwfree(point);
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force3dm_recursive returning");
-#endif
+		LWDEBUG(3, "lwgeom_force3dm_recursive returning");
+
 		return;
 	}
 
 	if ( type == LINETYPE )
 	{
 		line = lwline_deserialize(serialized);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force3dm_recursive: it's a line with %d points", line->points->npoints);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force3dm_recursive: it's a line with %d points", line->points->npoints);
+
 		TYPE_SETZM(newpts.dims, 0, 1);
 		newpts.npoints = line->points->npoints;
 		newpts.serialized_pointlist = lwalloc(sizeof(POINT3DM)*line->points->npoints);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force3dm_recursive: %d bytes pointlist allocated", sizeof(POINT3DM)*line->points->npoints);
-#endif
 
+		LWDEBUGF(3, "lwgeom_force3dm_recursive: %d bytes pointlist allocated", sizeof(POINT3DM)*line->points->npoints);
+
 		loc = newpts.serialized_pointlist;
 		for (j=0; j<line->points->npoints; j++)
 		{
@@ -1001,18 +965,17 @@
 		lwfree(newpts.serialized_pointlist);
 		lwfree(line);
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force3dm_recursive returning");
-#endif
+		LWDEBUG(3, "lwgeom_force3dm_recursive returning");
+
 		return;
 	}
 
         if ( type == CURVETYPE )
         {
                 curve = lwcurve_deserialize(serialized);
-#ifdef PGIS_DEBUG
-                elog(NOTICE, "lwgeom_force3dm_recursize: it's a curve with %d points", curve->points->npoints);
-#endif
+
+                LWDEBUGF(3, "lwgeom_force3dm_recursize: it's a curve with %d points", curve->points->npoints);
+
                 TYPE_SETZM(newpts.dims, 0, 1);
                 newpts.npoints = curve->points->npoints;
                 newpts.serialized_pointlist = lwalloc(sizeof(POINT3DM)*curve->points->npoints);
@@ -1063,9 +1026,8 @@
 		lwfree(poly);
 		/* TODO: free nrigs[*]->serialized_pointlist */
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force3dm_recursive returning");
-#endif
+		LWDEBUG(3, "lwgeom_force3dm_recursive returning");
+
 		return;
 	}
 
@@ -1083,9 +1045,7 @@
 	 * first and then call us again
 	 */
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force3dm_recursive: it's a collection (%s)", lwgeom_typename(type));
-#endif
+	LWDEBUGF(3, "lwgeom_force3dm_recursive: it's a collection (%s)", lwgeom_typename(type));
 
 
 	/* Add type */
@@ -1096,9 +1056,7 @@
 	totsize++;
 	loc=serialized+1;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_force3dm_recursive: added collection type (%s[%s]) - size:%d", lwgeom_typename(type), lwgeom_typeflags(newtypefl), totsize);
-#endif
+	LWDEBUGF(3, "lwgeom_force3dm_recursive: added collection type (%s[%s]) - size:%d", lwgeom_typename(type), lwgeom_typeflags(newtypefl), totsize);
 
 	if ( lwgeom_hasBBOX(serialized[0]) != lwgeom_hasBBOX(newtypefl) )
 		lwerror("typeflag mismatch in BBOX");
@@ -1112,9 +1070,8 @@
 		optr += sizeof(BOX2DFLOAT4);
 		totsize += sizeof(BOX2DFLOAT4);
 		loc += sizeof(BOX2DFLOAT4);
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_force3dm_recursive: added collection bbox - size:%d", totsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force3dm_recursive: added collection bbox - size:%d", totsize);
 	}
 
 	/* Add SRID if any */
@@ -1124,9 +1081,8 @@
 		optr += 4;
 		totsize += 4;
 		loc += 4;
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_force3dm_recursive: added collection SRID - size:%d", totsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force3dm_recursive: added collection SRID - size:%d", totsize);
 	}
 
 	/* Add numsubobjects */
@@ -1134,13 +1090,11 @@
 	optr += sizeof(uint32);
 	totsize += sizeof(uint32);
 	loc += sizeof(uint32);
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_force3dm_recursive: added collection ngeoms - size:%d", totsize);
-#endif
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_force3dm_recursive: inspecting subgeoms");
-#endif
+	LWDEBUGF(3, "lwgeom_force3dm_recursive: added collection ngeoms - size:%d", totsize);
+
+	LWDEBUG(3, "lwgeom_force3dm_recursive: inspecting subgeoms");
+
 	/* Now recurse for each subobject */
 	inspected = lwgeom_inspect(serialized);
 	for (i=0; i<inspected->ngeometries; i++)
@@ -1149,16 +1103,13 @@
 		lwgeom_force3dm_recursive(subgeom, optr, &size);
 		totsize += size;
 		optr += size;
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force3dm_recursive: added elem %d size: %d (tot: %d)",
-	i, size, totsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force3dm_recursive: added elem %d size: %d (tot: %d)",
+			i, size, totsize);
 	}
 	pfree_inspected(inspected);
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_force3dm_recursive returning");
-#endif
+	LWDEBUG(3, "lwgeom_force3dm_recursive returning");
 
 	if ( retsize ) *retsize = totsize;
 }
@@ -1188,9 +1139,7 @@
 	uchar *loc;
 
 		
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_force4d_recursive: call");
-#endif
+	LWDEBUG(2, "lwgeom_force4d_recursive: call");
 
 	type = lwgeom_getType(serialized[0]);
 
@@ -1206,17 +1155,16 @@
 		point->point = &newpts;
 		TYPE_SETZM(point->type, 1, 1);
 		lwpoint_serialize_buf(point, optr, retsize);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force4d_recursive: it's a point, size:%d", *retsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force4d_recursive: it's a point, size:%d", *retsize);
+
 		return;
 	}
 
 	if ( type == LINETYPE )
 	{
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force4d_recursive: it's a line");
-#endif
+		LWDEBUG(3, "lwgeom_force4d_recursive: it's a line");
+
 		line = lwline_deserialize(serialized);
 		TYPE_SETZM(newpts.dims, 1, 1);
 		newpts.npoints = line->points->npoints;
@@ -1231,9 +1179,9 @@
 		line->points = &newpts;
 		TYPE_SETZM(line->type, 1, 1);
 		lwline_serialize_buf(line, optr, retsize);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force4d_recursive: it's a line, size:%d", *retsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force4d_recursive: it's a line, size:%d", *retsize);
+
 		return;
 	}
 
@@ -1253,9 +1201,9 @@
                 curve->points = &newpts;
                 TYPE_SETZM(curve->type, 1, 1);
                 lwcurve_serialize_buf(curve, optr, retsize);
-#ifdef PGIS_DEBUG
-                elog(NOTICE, "lwgeom_force4d_recursive: it's a curve, size:%d", *retsize);
-#endif
+
+                LWDEBUGF(3, "lwgeom_force4d_recursive: it's a curve, size:%d", *retsize);
+
                 return;
         }
 
@@ -1287,9 +1235,9 @@
 		poly->rings = nrings;
 		TYPE_SETZM(poly->type, 1, 1);
 		lwpoly_serialize_buf(poly, optr, retsize);
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force4d_recursive: it's a poly, size:%d", *retsize);
-#endif
+
+		LWDEBUGF(3, "lwgeom_force4d_recursive: it's a poly, size:%d", *retsize);
+
 		return;
 	}
 
@@ -1298,9 +1246,7 @@
 	 * first and then call us again
 	 */
 
-#ifdef PGIS_DEBUG
-elog(NOTICE, "lwgeom_force4d_recursive: it's a collection (type:%d)", type);
-#endif
+	LWDEBUGF(3, "lwgeom_force4d_recursive: it's a collection (type:%d)", type);
 
 	/* Add type */
 	*optr = lwgeom_makeType_full(
@@ -1334,9 +1280,7 @@
 	optr += 4;
 	totsize += 4;
 
-#ifdef PGIS_DEBUG
-elog(NOTICE, " collection header size:%d", totsize);
-#endif
+	LWDEBUGF(3, " collection header size:%d", totsize);
 
 	/* Now recurse for each suboject */
 	inspected = lwgeom_inspect(serialized);
@@ -1346,9 +1290,8 @@
 		lwgeom_force4d_recursive(subgeom, optr, &size);
 		totsize += size;
 		optr += size;
-#ifdef PGIS_DEBUG
-elog(NOTICE, " elem %d size: %d (tot: %d)", i, size, totsize);
-#endif
+
+		LWDEBUGF(3, " elem %d size: %d (tot: %d)", i, size, totsize);
 	}
 	pfree_inspected(inspected);
 
@@ -1435,16 +1378,12 @@
 	}
 	srl = lwalloc(size);
 
-#ifdef PGIS_DEBUG
-	lwnotice("LWGEOM_force_3dm: allocated %d bytes for result", size);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_force_3dm: allocated %d bytes for result", (int)size);
 
 	lwgeom_force3dm_recursive(SERIALIZED_FORM(geom),
 		srl, &size);
 
-#ifdef PGIS_DEBUG
-	lwnotice("LWGEOM_force_3dm: lwgeom_force3dm_recursive returned a %d sized geom", size);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_force_3dm: lwgeom_force3dm_recursive returned a %d sized geom", (int)size);
 
 	result = PG_LWGEOM_construct(srl, pglwgeom_getSRID(geom),
 		lwgeom_hasBBOX(geom->type));
@@ -1494,9 +1433,7 @@
 	int SRID;
 	BOX2DFLOAT4 *bbox;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_force_collection called");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_force_collection called");
 
 	/*
 	 * This funx is a no-op only if a bbox cache is already present
@@ -1552,9 +1489,7 @@
 	int SRID=-1;
 	BOX2DFLOAT4 *box;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_force_multi called");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_force_multi called");
 
 	/*
 	 * This funx is a no-op only if a bbox cache is already present
@@ -1644,12 +1579,12 @@
 
 	geom1 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	geom2 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
-  tolerance = PG_GETARG_FLOAT8(2);
+	tolerance = PG_GETARG_FLOAT8(2);
 
-  if( tolerance < 0 ) {		
-    elog(ERROR,"Tolerance cannot be less than zero\n");
+	if( tolerance < 0 ) {		
+		elog(ERROR,"Tolerance cannot be less than zero\n");
 		PG_RETURN_NULL();
-  }
+	}
 
 	if (pglwgeom_getSRID(geom1) != pglwgeom_getSRID(geom2))
 	{
@@ -1740,9 +1675,7 @@
 	LWGEOM *lwgeom;
 	PG_LWGEOM *ret;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_longitude_shift called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_longitude_shift called.");
 
 	geom = (PG_LWGEOM *)PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0));
 	lwgeom = pglwgeom_deserialize(geom);
@@ -1807,9 +1740,7 @@
 	BOX2DFLOAT4 *box=NULL;
 	int SRID;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_collect called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_collect called.");
 
 	/* return null if both geoms are null */
 	if ( (geom1_ptr == NULL) && (geom2_ptr == NULL) )
@@ -1835,9 +1766,7 @@
 	pglwgeom1 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	pglwgeom2 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_collect(%s, %s): call", lwgeom_typename(TYPE_GETTYPE(pglwgeom1->type)), lwgeom_typename(TYPE_GETTYPE(pglwgeom2->type)));
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_collect(%s, %s): call", lwgeom_typename(TYPE_GETTYPE(pglwgeom1->type)), lwgeom_typename(TYPE_GETTYPE(pglwgeom2->type)));
 	
 #if 0
 	if ( pglwgeom_getSRID(pglwgeom1) != pglwgeom_getSRID(pglwgeom2) )
@@ -1858,9 +1787,7 @@
 	if ( type1 == type2 && type1 < 4 ) outtype = type1+3;
 	else outtype = COLLECTIONTYPE;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, " outtype = %d", outtype);
-#endif
+	POSTGIS_DEBUGF(3, " outtype = %d", outtype);
 
 	/* COMPUTE_BBOX WHEN_SIMPLE */
 	if ( lwgeoms[0]->bbox && lwgeoms[1]->bbox )
@@ -1919,43 +1846,37 @@
 #endif /* POSTGIS_PGSQL_VERSION > 72 */
 
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_accum called");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_accum called");
 
 	datum = PG_GETARG_DATUM(0);
 	if ( (Pointer *)datum == NULL ) {
 		array = NULL;
 		nelems = 0;
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "geom_accum: NULL array");
-#endif
+
+		POSTGIS_DEBUG(3, "geom_accum: NULL array");
 	} else {
 		array = DatumGetArrayTypePCopy(datum);
 		/*array = PG_GETARG_ARRAYTYPE_P(0); */
 		nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "geom_accum: array of nelems=%d", nelems);
-#endif
+
+		POSTGIS_DEBUGF(3, "geom_accum: array of nelems=%d", nelems);
 	}
 
 	datum = PG_GETARG_DATUM(1);
 	/* Do nothing, return state array */
 	if ( (Pointer *)datum == NULL )
 	{
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "geom_accum: NULL geom, nelems=%d", nelems);
-#endif
+		POSTGIS_DEBUGF(3, "geom_accum: NULL geom, nelems=%d", nelems);
+
 		if ( array == NULL ) PG_RETURN_NULL();
 		PG_RETURN_ARRAYTYPE_P(array);
 	}
 
 	/* Make a DETOASTED copy of input geometry */
 	geom = (PG_LWGEOM *)PG_DETOAST_DATUM(datum);
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "geom_accum: detoasted geom: %p", (void*)geom);
-#endif
 
+	POSTGIS_DEBUGF(3, "geom_accum: detoasted geom: %p", (void*)geom);
+
 	/*
 	 * Might use a more optimized version instead of lwrealloc'ing
 	 * at every iteration. This is not the bottleneck anyway.
@@ -1964,10 +1885,10 @@
 	++nelems;
 	if ( nelems == 1 || ! array ) {
 		nbytes = ARR_OVERHEAD_NONULLS(1)+INTALIGN(VARSIZE(geom));
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "geom_accum: adding %p (nelems=%d; nbytes=%d)",
-			(void*)geom, nelems, nbytes);
-#endif
+
+		POSTGIS_DEBUGF(3, "geom_accum: adding %p (nelems=%d; nbytes=%d)",
+			(void*)geom, nelems, (int)nbytes);
+
 		result = lwalloc(nbytes);
 		if ( ! result )
 		{
@@ -1987,44 +1908,39 @@
 		memcpy(ARR_DIMS(result), &nelems, sizeof(int));
 		memcpy(ARR_LBOUND(result), &lbs, sizeof(int));
 		memcpy(ARR_DATA_PTR(result), geom, VARSIZE(geom));
-#ifdef PGIS_DEBUG
-		elog(NOTICE, " %d bytes memcopied", VARSIZE(geom));
-#endif
 
+		POSTGIS_DEBUGF(3, " %d bytes memcopied", VARSIZE(geom));
+
 	} else {
 		oldsize = VARSIZE(array);
 		nbytes = oldsize + INTALIGN(VARSIZE(geom));
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "geom_accum: old array size: %d, adding %ld bytes (nelems=%d; nbytes=%u)", ARR_SIZE(array), INTALIGN(VARSIZE(geom)), nelems, nbytes);
-#endif
+
+		POSTGIS_DEBUGF(3, "geom_accum: old array size: %d, adding %ld bytes (nelems=%d; nbytes=%u)", ARR_SIZE(array), INTALIGN(VARSIZE(geom)), nelems, (int)nbytes);
+
 		result = (ArrayType *) lwrealloc(array, nbytes);
 		if ( ! result )
 		{
 			elog(ERROR, "Out of virtual memory");
 			PG_RETURN_NULL();
 		}
-#ifdef PGIS_DEBUG
-		elog(NOTICE, " %d bytes allocated for array", nbytes);
-#endif
 
-#ifdef PGIS_DEBUG
-		elog(NOTICE, " array start  @ %p", (void*)result);
-		elog(NOTICE, " ARR_DATA_PTR @ %p (%d)",
+		POSTGIS_DEBUGF(3, " %d bytes allocated for array", (int)nbytes);
+
+		POSTGIS_DEBUGF(3, " array start  @ %p", (void*)result);
+		POSTGIS_DEBUGF(3, " ARR_DATA_PTR @ %p (%ld)",
 			ARR_DATA_PTR(result), (uchar *)ARR_DATA_PTR(result)-(uchar *)result);
-		elog(NOTICE, " next element @ %p", (uchar *)result+oldsize);
-#endif
+		POSTGIS_DEBUGF(3, " next element @ %p", (uchar *)result+oldsize);
+
 		SET_VARSIZE(result, nbytes);
 		memcpy(ARR_DIMS(result), &nelems, sizeof(int));
-#ifdef PGIS_DEBUG
-		elog(NOTICE, " writing next element starting @ %p",
+
+		POSTGIS_DEBUGF(3, " writing next element starting @ %p",
 			(void*)(result+oldsize));
-#endif
+
 		memcpy((uchar *)result+oldsize, geom, VARSIZE(geom));
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, " returning");
-#endif
+	POSTGIS_DEBUG(3, " returning");
 
 	PG_RETURN_ARRAYTYPE_P(result);
 
@@ -2054,14 +1970,8 @@
 	size_t offset;
 	BOX2DFLOAT4 *box=NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_collect_garray called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_collect_garray called.");
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_collect_garray called");
-#endif
-
 	/* Get input datum */
 	datum = PG_GETARG_DATUM(0);
 
@@ -2075,18 +1985,14 @@
 	/* Get actual ArrayType */
 	array = DatumGetArrayTypeP(datum);
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, " array is %d-bytes in size, %ld w/out header",
+	POSTGIS_DEBUGF(3, " array is %d-bytes in size, %ld w/out header",
 		ARR_SIZE(array), ARR_SIZE(array)-ARR_OVERHEAD_NONULLS(ARR_NDIM(array)));
-#endif
 
 
 	/* Get number of geometries in array */
 	nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_collect_garray: array has %d elements", nelems);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_collect_garray: array has %d elements", nelems);
 
 	/* Return null on 0-elements input array */
 	if ( nelems == 0 )
@@ -2110,10 +2016,9 @@
 		offset += INTALIGN(VARSIZE(geom));
 
 		lwgeoms[i] = lwgeom_deserialize(SERIALIZED_FORM(geom));
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_collect_garray: geom %d deserialized", i);
-#endif
 
+		POSTGIS_DEBUGF(3, "LWGEOM_collect_garray: geom %d deserialized", i);
+
 		if ( ! i )
 		{
 			/* Get first geometry SRID */
@@ -2173,9 +2078,7 @@
 
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_collect_garray: outtype = %d", outtype);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_collect_garray: outtype = %d", outtype);
 
 	outlwg = (LWGEOM *)lwcollection_construct(
 		outtype, SRID,
@@ -2197,14 +2100,8 @@
 	LWLINE *lwline;
 	LWMPOINT *mpoint;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_line_from_mpoint called.");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_line_from_mpoint called");
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_line_from_mpoint called");
-#endif
-
 	/* Get input PG_LWGEOM and deserialize it */
 	ingeom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 
@@ -2250,14 +2147,8 @@
 	size_t offset;
 	int SRID=-1;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_makeline_garray called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_makeline_garray called.");
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_makeline_garray called");
-#endif
-
 	/* Get input datum */
 	datum = PG_GETARG_DATUM(0);
 
@@ -2271,16 +2162,12 @@
 	/* Get actual ArrayType */
 	array = DatumGetArrayTypeP(datum);
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_makeline_garray: array detoasted");
-#endif
+	POSTGIS_DEBUG(3, "LWGEOM_makeline_garray: array detoasted");
 
 	/* Get number of geometries in array */
 	nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_makeline_garray: array has %d elements", nelems);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_makeline_garray: array has %d elements", nelems);
 
 	/* Return null on 0-elements input array */
 	if ( nelems == 0 )
@@ -2322,10 +2209,8 @@
 			}
 		}
 
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "LWGEOM_makeline_garray: element %d deserialized",
+		POSTGIS_DEBUGF(3, "LWGEOM_makeline_garray: element %d deserialized",
 			i);
-#endif
 	}
 
 	/* Return null on 0-points input array */
@@ -2335,9 +2220,7 @@
 		PG_RETURN_NULL();
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_makeline_garray: point elements: %d", npoints);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_makeline_garray: point elements: %d", npoints);
 
 	outlwg = (LWGEOM *)lwline_from_lwpointarray(SRID, npoints, lwpoints);
 
@@ -2358,14 +2241,8 @@
 	LWPOINT *lwpoints[2];
 	LWLINE *outline;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_makeline called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_makeline called.");
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_makeline called");
-#endif
-
 	/* Get input datum */
 	pglwg1 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	pglwg2 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
@@ -2411,14 +2288,8 @@
 	unsigned int i;
 	size_t offset=0;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_makepoly called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_makepoly called.");
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_makepoly called");
-#endif
-
 	/* Get input shell */
 	pglwg1 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	if ( ! TYPE_GETTYPE(pglwg1->type) == LINETYPE ) {
@@ -2446,10 +2317,9 @@
 	}
 
 	outpoly = lwpoly_from_lwlines(shell, nholes, holes);
-#ifdef PGIS_DEBUG
-	lwnotice("%s", lwgeom_summary((LWGEOM*)outpoly, 0));
-#endif
 
+	POSTGIS_DEBUGF(3, "%s", lwgeom_summary((LWGEOM*)outpoly, 0));
+
 	result = pglwgeom_serialize((LWGEOM *)outpoly);
 
 	PG_FREE_IF_COPY(pglwg1, 0);
@@ -2476,9 +2346,7 @@
 	int SRID;
 	PG_LWGEOM *result;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_expand called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_expand called.");
 
 	/* get geometry box  */
 	if ( ! getbox2d_p(SERIALIZED_FORM(geom), &box) )
@@ -2659,9 +2527,7 @@
 	double dist;
 	LWGEOM *inlwgeom, *outlwgeom;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_segmentize2d called");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_segmentize2d called");
 
 	ingeom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	dist = PG_GETARG_FLOAT8(1);
@@ -2694,9 +2560,7 @@
 	PG_LWGEOM *geom;
 	LWGEOM *lwgeom;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_reverse called");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_reverse called");
 
 	geom = (PG_LWGEOM *)PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0));
 
@@ -2715,9 +2579,7 @@
 	PG_LWGEOM *ingeom, *outgeom;
 	LWGEOM *lwgeom;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_forceRHR_poly called");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_forceRHR_poly called");
 
 	ingeom = (PG_LWGEOM *)PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0));
 
@@ -2739,17 +2601,13 @@
 	PG_LWGEOM *in, *out;
 	LWGEOM *lwgeom;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_noop called");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_noop called");
 
 	in = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 
 	lwgeom = lwgeom_deserialize(SERIALIZED_FORM(in));
 
-#ifdef PGIS_DEBUG
-	lwnotice("Deserialized: %s", lwgeom_summary(lwgeom, 0));
-#endif
+	POSTGIS_DEBUGF(3, "Deserialized: %s", lwgeom_summary(lwgeom, 0));
 
 	out = pglwgeom_serialize(lwgeom);
 
@@ -2853,9 +2711,7 @@
 	LWPOINT *point;
 	PG_LWGEOM *result;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_makepoint called");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_makepoint called");
 
 	x = PG_GETARG_FLOAT8(0);
 	y = PG_GETARG_FLOAT8(1);
@@ -2888,9 +2744,7 @@
 	LWPOINT *point;
 	PG_LWGEOM *result;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_makepoint3dm called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_makepoint3dm called.");
 
 	x = PG_GETARG_FLOAT8(0);
 	y = PG_GETARG_FLOAT8(1);
@@ -2910,9 +2764,7 @@
 	LWLINE *line, *outline;
 	int where = -1;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_addpoint called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_addpoint called.");
 
 	pglwg1 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	pglwg2 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
@@ -2966,9 +2818,7 @@
 	LWLINE *line, *outline;
 	unsigned int which;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_removepoint called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_removepoint called.");
 
 	pglwg1 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	which = PG_GETARG_INT32(1);
@@ -3016,9 +2866,7 @@
 	POINT4D newpoint;
 	unsigned int which;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_setpoint_linestring called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_setpoint_linestring called.");
 
 	/* we copy input as we're going to modify it */
 	pglwg1 = (PG_LWGEOM *)PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0));
@@ -3259,15 +3107,12 @@
 	double x,y,z;
 	POINT4D p4d;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_affine_ptarray start");
-#endif
+	LWDEBUG(2, "lwgeom_affine_ptarray start");
 
 	if ( TYPE_HASZ(pa->dims) )
 	{
-#ifdef PGIS_DEBUG
-		lwnotice(" has z");
-#endif
+		LWDEBUG(3, " has z");
+
 		for (i=0; i<pa->npoints; i++) {
 			getPoint4d_p(pa, i, &p4d);
 			x = p4d.x;
@@ -3277,16 +3122,14 @@
 			p4d.y = dfac * x + efac * y + ffac * z + yoff;
 			p4d.z = gfac * x + hfac * y + ifac * z + zoff;
 			setPoint4d(pa, i, &p4d);
-#ifdef PGIS_DEBUG
-		lwnotice(" POINT %g %g %g => %g %g %g", x, y, x, p4d.x, p4d.y, p4d.z);
-#endif
+
+			LWDEBUGF(3, " POINT %g %g %g => %g %g %g", x, y, x, p4d.x, p4d.y, p4d.z);
 		}
 	}
 	else
 	{
-#ifdef PGIS_DEBUG
-		lwnotice(" doesn't have z");
-#endif
+		LWDEBUG(3, " doesn't have z");
+
 		for (i=0; i<pa->npoints; i++) {
 			getPoint4d_p(pa, i, &p4d);
   			x = p4d.x;
@@ -3294,15 +3137,12 @@
   			p4d.x = afac * x + bfac * y + xoff;
   			p4d.y = dfac * x + efac * y + yoff;
 			setPoint4d(pa, i, &p4d);
-#ifdef PGIS_DEBUG
-		lwnotice(" POINT %g %g %g => %g %g %g", x, y, x, p4d.x, p4d.y, p4d.z);
-#endif
+
+			LWDEBUGF(3, " POINT %g %g %g => %g %g %g", x, y, x, p4d.x, p4d.y, p4d.z);
 		}
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_affine_ptarray end");
-#endif
+	LWDEBUG(3, "lwgeom_affine_ptarray end");
 
 }
 
@@ -3390,10 +3230,6 @@
 	LWGEOM *tmp;
 	uchar *srl = SERIALIZED_FORM(geom);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_affine called.");
-#endif
-
 	double afac =  PG_GETARG_FLOAT8(1);
 	double bfac =  PG_GETARG_FLOAT8(2);
 	double cfac =  PG_GETARG_FLOAT8(3);
@@ -3407,6 +3243,8 @@
 	double yoff =  PG_GETARG_FLOAT8(11);
 	double zoff =  PG_GETARG_FLOAT8(12);
 
+        POSTGIS_DEBUG(2, "LWGEOM_affine called.");
+	
 	lwgeom_affine_recursive(srl,
 		afac, bfac, cfac,
 		dfac, efac, ffac,

Modified: trunk/lwgeom/lwgeom_functions_lrs.c
===================================================================
--- trunk/lwgeom/lwgeom_functions_lrs.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_functions_lrs.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -16,8 +16,6 @@
 #include "lwgeom_pg.h"
 #include "math.h"
 
-#define DEBUG_LRS 0
-#define DEBUG_INTERPOLATION 0
 
 Datum LWGEOM_locate_between_m(PG_FUNCTION_ARGS);
 
@@ -120,12 +118,11 @@
 	dX=p2->x-p1->x;
 	dY=p2->y-p1->y;
 	dZ=p2->z-p1->z;
-#if DEBUG_INTERPOLATION
-	lwnotice("dM0:%g dM1:%g", dM0, dM1);
-	lwnotice("dX:%g dY:%g dZ:%g", dX, dY, dZ);
-#endif
 
+	LWDEBUGF(3, "dM0:%g dM1:%g", dM0, dM1);
+	LWDEBUGF(3, "dX:%g dY:%g dZ:%g", dX, dY, dZ);
 
+
 	/* 
 	 * First point out of range, project 
 	 * it on the range
@@ -201,10 +198,8 @@
 	 */
 	ret.ptarrays=lwalloc(sizeof(POINTARRAY *)*ipa->npoints-1);
 
-#if DEBUG_LRS
-	lwnotice("ptarray_locate...: called for pointarray %x, m0:%g, m1:%g",
+	LWDEBUGF(2, "ptarray_locate...: called for pointarray %x, m0:%g, m1:%g",
 		ipa, m0, m1);
-#endif
 
 
 	for(i=1; i<ipa->npoints; i++)
@@ -215,12 +210,10 @@
 		getPoint4d_p(ipa, i-1, &p1);
 		getPoint4d_p(ipa, i, &p2);
 
-#if DEBUG_LRS
-		lwnotice(" segment %d-%d [ %g %g %g %g -  %g %g %g %g ]",
+		LWDEBUGF(3, " segment %d-%d [ %g %g %g %g -  %g %g %g %g ]",
 			i-1, i,
 			p1.x, p1.y, p1.z, p1.m,
 			p2.x, p2.y, p2.z, p2.m);
-#endif
 
 
 		clipval=clip_seg_by_m_range(&p1, &p2, m0, m1);
@@ -235,29 +228,26 @@
 		 */
 		if ( clipval & 0x0100 || i == ipa->npoints-1 ) 
 		{
-#if DEBUG_LRS
-			lwnotice(" second point clipped");
-#endif
+			LWDEBUG(3, " second point clipped");
+
 			/*
 			 * No output points defined, so
 			 * we have to open a new one and add the first point
 			 */
 			if ( dpa == NULL )
 			{
-#if DEBUG_LRS
-				lwnotice(" 1 creating new POINARRAY with first point %g,%g,%g,%g", p1.x, p1.y, p1.z, p1.m);
-#endif
+				LWDEBUGF(3, " 1 creating new POINARRAY with first point %g,%g,%g,%g", p1.x, p1.y, p1.z, p1.m);
+
 				dpa = dynptarray_create(2, ipa->dims);
 				dynptarray_addPoint4d(dpa, &p1, 1);
 			}
 
-#if DEBUG_LRS
-			lwnotice(" 1 adding new point %g,%g,%g,%g", p2.x, p2.y, p2.z, p2.m);
-#endif
+			LWDEBUGF(3, " 1 adding new point %g,%g,%g,%g", p2.x, p2.y, p2.z, p2.m);
+
 			dynptarray_addPoint4d(dpa, &p2, 0);
-#if DEBUG_LRS
-			lwnotice(" closing pointarray %x with %d points", dpa->pa, dpa->pa->npoints);
-#endif
+
+			LWDEBUGF(3, " closing pointarray %x with %d points", dpa->pa, dpa->pa->npoints);
+
 			ret.ptarrays[ret.nptarrays++] = dpa->pa;
 			lwfree(dpa); dpa=NULL;
 			continue;
@@ -268,9 +258,8 @@
 		 */
 		if ( dpa==NULL )
 		{
-#if DEBUG_LRS
-			lwnotice(" 3 creating new POINARRAY with first point %g,%g,%g,%g", p1.x, p1.y, p1.z, p1.m);
-#endif
+			LWDEBUGF(3, " 3 creating new POINARRAY with first point %g,%g,%g,%g", p1.x, p1.y, p1.z, p1.m);
+
 			dpa = dynptarray_create(ipa->npoints-i, ipa->dims);
 			dynptarray_addPoint4d(dpa, &p1, 1);
 		}
@@ -278,9 +267,8 @@
 		/*
 		 * In any case we add the second point (w/out allowin duplicates)
 		 */
-#if DEBUG_LRS
-		lwnotice(" 2 adding new point %g,%g,%g,%g", p2.x, p2.y, p2.z, p2.m);
-#endif
+		LWDEBUGF(3, " 2 adding new point %g,%g,%g,%g", p2.x, p2.y, p2.z, p2.m);
+
 		dynptarray_addPoint4d(dpa, &p2, 0);
 
 	}
@@ -304,23 +292,19 @@
 {
 	POINT3DM p3dm;
 
-#if DEBUG_LRS
-	lwnotice("lwpoint_locate_between called for lwpoint %x", lwpoint);
-#endif
+	LWDEBUGF(2, "lwpoint_locate_between called for lwpoint %x", lwpoint);
 
 	lwpoint_getPoint3dm_p(lwpoint, &p3dm);
 	if ( p3dm.m >= m0 && p3dm.m <= m1)
 	{
-#if DEBUG_LRS
-		lwnotice(" lwpoint... returning a clone of input");
-#endif
+		LWDEBUG(3, " lwpoint... returning a clone of input");
+
 		return (LWGEOM *)lwpoint_clone(lwpoint);
 	}
 	else
 	{
-#if DEBUG_LRS
-		lwnotice(" lwpoint... returning a clone of input");
-#endif
+		LWDEBUG(3, " lwpoint... returning a clone of input");
+
 		return NULL;
 	}
 }
@@ -347,17 +331,12 @@
 	int typeflag=0; /* see flags below */
 	const int pointflag=0x01;
 	const int lineflag=0x10;
-
-#if DEBUG_LRS
-	lwnotice("lwline_locate_between called for lwline %x", lwline_in);
-#endif
-
 	POINTARRAYSET paset=ptarray_locate_between_m(ipa, m0, m1);
 
-#if DEBUG_LRS
-	lwnotice(" ptarray_locate... returned %d pointarrays",
+	LWDEBUGF(2, "lwline_locate_between called for lwline %x", lwline_in);
+
+	LWDEBUGF(3, " ptarray_locate... returned %d pointarrays",
 		paset.nptarrays);
-#endif
 
 	if ( paset.nptarrays == 0 )
 	{
@@ -443,9 +422,7 @@
 	int ngeoms=0;
 	LWGEOM **geoms;
 
-#if DEBUG_LRS
-	lwnotice("lwcollection_locate_between_m called for lwcoll %x", lwcoll);
-#endif
+	LWDEBUGF(2, "lwcollection_locate_between_m called for lwcoll %x", lwcoll);
 
 	geoms=lwalloc(sizeof(LWGEOM *)*lwcoll->ngeoms);
 	for (i=0; i<lwcoll->ngeoms; i++)
@@ -474,9 +451,8 @@
 static LWGEOM *
 lwgeom_locate_between_m(LWGEOM *lwin, double m0, double m1)
 {
-#if DEBUG_LRS
-	lwnotice("lwgeom_locate_between called for lwgeom %x", lwin);
-#endif
+	LWDEBUGF(2, "lwgeom_locate_between called for lwgeom %x", lwin);
+
 	switch (TYPE_GETTYPE(lwin->type))
 	{
 		case POINTTYPE:

Modified: trunk/lwgeom/lwgeom_geos_c.c
===================================================================
--- trunk/lwgeom/lwgeom_geos_c.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_geos_c.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -22,16 +22,9 @@
 /*
  * Define this to have have many notices printed
  * during postgis->geos and geos->postgis conversions
+ *
  */
-/* #define PGIS_DEBUG_CONVERTER 1 */
-#ifdef PGIS_DEBUG_CONVERTER
-#define PGIS_DEBUG_POSTGIS2GEOS 1
-#define PGIS_DEBUG_GEOS2POSTGIS 1
-#endif /* PGIS_DEBUG_CONVERTER */
 
-/* #define PGIS_DEBUG 1 */
-/* #define WKB_CONVERSION 1 */
-
 /*
  *
  * WARNING: buffer-based GeomUnion has been disabled due to
@@ -78,12 +71,14 @@
 Datum polygonize_garray(PG_FUNCTION_ARGS);
 Datum LWGEOM_buildarea(PG_FUNCTION_ARGS);
 Datum linemerge(PG_FUNCTION_ARGS);
+Datum coveredby(PG_FUNCTION_ARGS);
 
 
 LWGEOM *GEOS2LWGEOM(GEOSGeom geom, char want3d);
 PG_LWGEOM *GEOS2POSTGIS(GEOSGeom geom, char want3d);
 GEOSGeom POSTGIS2GEOS(PG_LWGEOM *g);
 GEOSGeom LWGEOM2GEOS(LWGEOM *g);
+POINTARRAY *ptarray_from_GEOSCoordSeq(GEOSCoordSeq cs, char want3d);
 
 void errorIfGeometryCollection(PG_LWGEOM *g1, PG_LWGEOM *g2);
 
@@ -119,16 +114,15 @@
 	GEOSGeom g1, g2, geos_result=NULL;
 	int SRID=-1;
 	size_t offset;
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL > 0
 	static int call=1;
 #endif
 
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL >= 2 
 	call++;
-	lwnotice("GEOS incremental union (call %d)", call);
+	POSTGIS_DEBUGF(2, "GEOS incremental union (call %d)", call);
 #endif
 
-
 	datum = PG_GETARG_DATUM(0);
 
 	/* Null array, null geometry (should be empty?) */
@@ -138,9 +132,7 @@
 
 	nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "unite_garray: number of elements: %d", nelems);
-#endif
+	POSTGIS_DEBUGF(3, "unite_garray: number of elements: %d", nelems);
 
 	if ( nelems == 0 ) PG_RETURN_NULL();
 
@@ -158,9 +150,7 @@
 
 		pgis_geom = geom;
 
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "geom %d @ %p", i, geom);
-#endif
+		POSTGIS_DEBUGF(3, "geom %d @ %p", i, geom);
 
 		/* Check is3d flag */
 		if ( TYPE_HASZ(geom->type) ) is3d = 1;
@@ -170,9 +160,9 @@
 		{
 			geos_result = POSTGIS2GEOS(geom);
 			SRID = pglwgeom_getSRID(geom);
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "first geom is a %s", lwgeom_typename(TYPE_GETTYPE(geom->type)));
-#endif
+
+			POSTGIS_DEBUGF(3, "first geom is a %s", lwgeom_typename(TYPE_GETTYPE(geom->type)));
+
 			continue;
 		}
 		else
@@ -182,10 +172,8 @@
 		
 		g1 = POSTGIS2GEOS(pgis_geom);
 
-#ifdef PGIS_DEBUG
-		elog(NOTICE, "unite_garray(%d): adding geom %d to union (%s)",
+		POSTGIS_DEBUGF(3, "unite_garray(%d): adding geom %d to union (%s)",
 				call, i, lwgeom_typename(TYPE_GETTYPE(geom->type)));
-#endif
 
 		g2 = GEOSUnion(g1,geos_result);
 		if ( g2 == NULL )
@@ -235,16 +223,15 @@
 	GEOSGeom g1, geos_result=NULL;
 	int SRID=-1;
 	size_t offset;
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL > 0
 	static int call=1;
 #endif
 
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL >= 2 
 	call++;
-	lwnotice("GEOS buffer union (call %d)", call);
+	POSTGIS_DEBUGF(2, "GEOS buffer union (call %d)", call);
 #endif
 
-
 	datum = PG_GETARG_DATUM(0);
 
 	/* Null array, null geometry (should be empty?) */
@@ -254,9 +241,7 @@
 
 	nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "unite_garray: number of elements: %d", nelems);
-#endif
+	POSTGIS_DEBUGF(3, "unite_garray: number of elements: %d", nelems);
 
 	if ( nelems == 0 ) PG_RETURN_NULL();
 
@@ -270,9 +255,9 @@
 
 	offset = 0; i=0;
 	ngeoms = 0; npoints=0;
-#ifdef PGIS_DEBUG
- 	lwnotice("Nelems %d, MAXGEOMSPOINST %d", nelems, MAXGEOMSPOINTS);
-#endif
+
+ 	POSTGIS_DEBUGF(3, "Nelems %d, MAXGEOMSPOINST %d", nelems, MAXGEOMSPOINTS);
+
 	while (!result) 
 	{
 		PG_LWGEOM *geom = (PG_LWGEOM *)(ARR_DATA_PTR(array)+offset);
@@ -292,9 +277,7 @@
 		++ngeoms;
 		++i;
 
-#if PGIS_DEBUG > 1
-		lwnotice("Loop %d, npoints: %d", i, npoints);
-#endif
+		POSTGIS_DEBUGF(4, "Loop %d, npoints: %d", i, npoints);
 
 		/*
 		 * Maximum count of geometry points reached
@@ -302,10 +285,8 @@
 		 */
 		if ( (npoints>=MAXGEOMSPOINTS && ngeoms>1) || i==nelems)
 		{
-#if PGIS_DEBUG > 1
-			lwnotice(" CHUNK (ngeoms:%d, npoints:%d, left:%d)",
+			POSTGIS_DEBUGF(4, " CHUNK (ngeoms:%d, npoints:%d, left:%d)",
 				ngeoms, npoints, nelems-i);
-#endif
 
 			collection = GEOSMakeCollection(GEOS_GEOMETRYCOLLECTION,
 				geoms, ngeoms);
@@ -318,9 +299,7 @@
 			}
 			GEOSGeom_destroy(collection);
 
-#if PGIS_DEBUG > 1
-			lwnotice(" Buffer() executed");
-#endif
+			POSTGIS_DEBUG(4, " Buffer() executed");
 
 			/*
 			 * If there are no other geoms in input
@@ -329,17 +308,14 @@
 			 */
 			if ( i == nelems )
 			{
-#if PGIS_DEBUG > 1
-i				lwnotice("  Final result points: %d",
+				POSTGIS_DEBUGF(4, "  Final result points: %d",
 					GEOSGetNumCoordinate(geos_result));
-#endif
+
 				GEOSSetSRID(geos_result, SRID);
 				result = GEOS2POSTGIS(geos_result, is3d);
 				GEOSGeom_destroy(geos_result);
 
-#if PGIS_DEBUG > 1
-				lwnotice(" Result computed");
-#endif
+				POSTGIS_DEBUG(4, " Result computed");
 
 			}
 			else
@@ -347,9 +323,8 @@
 				geoms[0] = geos_result;
 				ngeoms=1;
 				npoints = GEOSGetNumCoordinate(geoms[0]);
-#if PGIS_DEBUG > 1
-	lwnotice("  Result pushed back on lwgeoms array (npoints:%d)", npoints);
-#endif
+
+				POSTGIS_DEBUGF(4, "  Result pushed back on lwgeoms array (npoints:%d)", npoints);
 			}
 		}
 	}
@@ -381,9 +356,7 @@
 	GEOSGeom g1,g2,g3;
 	PG_LWGEOM *result;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"in geomunion");
-#endif
+	POSTGIS_DEBUG(2, "in geomunion");
 
 #ifdef PROFILE
 	profstart(PROF_QRUN);
@@ -415,10 +388,8 @@
 	profstop(PROF_P2G2);
 #endif
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"g1=%s", GEOSGeomToWKT(g1));
-	elog(NOTICE,"g2=%s", GEOSGeomToWKT(g2));
-#endif
+	POSTGIS_DEBUGF(3, "g1=%s", GEOSGeomToWKT(g1));
+	POSTGIS_DEBUGF(3, "g2=%s", GEOSGeomToWKT(g2));
 
 #ifdef PROFILE
 	profstart(PROF_GRUN);
@@ -428,9 +399,7 @@
 	profstop(PROF_GRUN);
 #endif
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"g3=%s", GEOSGeomToWKT(g3));
-#endif
+	POSTGIS_DEBUGF(3, "g3=%s", GEOSGeomToWKT(g3));
 
 	GEOSGeom_destroy(g1);
 	GEOSGeom_destroy(g2);
@@ -535,9 +504,7 @@
 		PG_RETURN_NULL(); /*never get here */
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3));
-#endif
+	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3));
 
 	GEOSSetSRID(g3, SRID);
 
@@ -617,9 +584,7 @@
 		PG_RETURN_NULL(); /* never get here */
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3));
-#endif
+	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3));
 
 	GEOSSetSRID(g3, SRID);
 
@@ -700,9 +665,7 @@
 	}
 
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3));
-#endif
+	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3));
 
 	GEOSSetSRID(g3, SRID);
 
@@ -796,9 +759,7 @@
 	}
 
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3));
-#endif
+	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3));
 
 	GEOSSetSRID(g3, pglwgeom_getSRID(geom1));
 
@@ -876,9 +837,7 @@
 	}
 
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3));
-#endif
+	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3));
 
 	GEOSSetSRID(g3, pglwgeom_getSRID(geom1));
 
@@ -937,9 +896,7 @@
 
 	initGEOS(lwnotice, lwnotice);
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"intersection() START");
-#endif
+	POSTGIS_DEBUG(3, "intersection() START");
 
 #ifdef PROFILE
 	profstart(PROF_P2G1);
@@ -957,13 +914,11 @@
 	profstop(PROF_P2G2);
 #endif
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE," constructed geometrys - calling geos");
-	elog(NOTICE," g1 = %s", GEOSGeomToWKT(g1));
-	elog(NOTICE," g2 = %s", GEOSGeomToWKT(g2));
-/*elog(NOTICE,"g2 is valid = %i",GEOSisvalid(g2)); */
-/*elog(NOTICE,"g1 is valid = %i",GEOSisvalid(g1)); */
-#endif
+	POSTGIS_DEBUG(3, " constructed geometrys - calling geos");
+	POSTGIS_DEBUGF(3, " g1 = %s", GEOSGeomToWKT(g1));
+	POSTGIS_DEBUGF(3, " g2 = %s", GEOSGeomToWKT(g2));
+	/*POSTGIS_DEBUGF(3, "g2 is valid = %i",GEOSisvalid(g2)); */
+	/*POSTGIS_DEBUGF(3, "g1 is valid = %i",GEOSisvalid(g1)); */
 
 
 
@@ -976,9 +931,7 @@
 	profstop(PROF_GRUN);
 #endif
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE," intersection finished");
-#endif
+	POSTGIS_DEBUG(3, " intersection finished");
 
 	if (g3 == NULL)
 	{
@@ -989,9 +942,7 @@
 	}
 
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3) ) ;
-#endif
+	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3) ) ;
 
 	GEOSSetSRID(g3, SRID);
 
@@ -1092,9 +1043,7 @@
 		PG_RETURN_NULL(); /* never get here */
 	}
 
-#ifdef PGIS_DEBUG
-  	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3) ) ;
-#endif
+  	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3) ) ;
 
 	GEOSSetSRID(g3, SRID);
 
@@ -1171,9 +1120,7 @@
 		PG_RETURN_NULL(); /* never get here */
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3) ) ;
-#endif
+	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3) ) ;
 
 	GEOSSetSRID(g3, pglwgeom_getSRID(geom1));
 #ifdef PROFILE
@@ -1484,16 +1431,13 @@
         type2 = lwgeom_getType((uchar)SERIALIZED_FORM(geom2)[0]);
         if(type1 == POLYGONTYPE && type2 == POINTTYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Point in Polygon test requested...short-circuiting.");
-#endif
+                POSTGIS_DEBUG(3, "Point in Polygon test requested...short-circuiting.");
 
                 poly = lwpoly_deserialize(SERIALIZED_FORM(geom1));
                 point = lwpoint_deserialize(SERIALIZED_FORM(geom2));
-#ifdef PGIS_DEBUG
-                lwnotice("Precall point_in_polygon %p, %p", poly, point);
-#endif
 
+                POSTGIS_DEBUGF(3, "Precall point_in_polygon %p, %p", poly, point);
+
                 /*
                  * Switch the context to the function-scope context,
                  * retrieve the appropriate cache object, cache it for 
@@ -1524,9 +1468,8 @@
         /* Not yet functional 
         else if(type1 == MULTIPOLYGONTYPE && type2 == POINTTYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Point in MultiPolygon test requested...short-circuiting.");
-#endif
+                POSTGIS_DEBUG(3, "Point in MultiPolygon test requested...short-circuiting.");
+
                 mpoly = lwmpoly_deserialize(SERIALIZED_FORM(geom1));
                 point = lwpoint_deserialize(SERIALIZED_FORM(geom2));
                 if(point_in_multipolygon(mpoly, point) == 0)
@@ -1549,9 +1492,7 @@
         */
         else 
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Contains: type1: %d, type2: %d", type1, type2);
-#endif
+                POSTGIS_DEBUGF(3, "Contains: type1: %d, type2: %d", type1, type2);
         }
         
 	initGEOS(lwnotice, lwnotice);
@@ -1651,16 +1592,13 @@
         type2 = lwgeom_getType((uchar)SERIALIZED_FORM(geom2)[0]);
         if(type1 == POLYGONTYPE && type2 == POINTTYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Point in Polygon test requested...short-circuiting.");
-#endif
+                POSTGIS_DEBUG(3, "Point in Polygon test requested...short-circuiting.");
 
                 poly = lwpoly_deserialize(SERIALIZED_FORM(geom1));
                 point = lwpoint_deserialize(SERIALIZED_FORM(geom2));
-#ifdef PGIS_DEBUG
-                lwnotice("Precall point_in_polygon %p, %p", poly, point);
-#endif
 
+                POSTGIS_DEBUGF(3, "Precall point_in_polygon %p, %p", poly, point);
+
                 /*
                  * Switch the context to the function-scope context,
                  * retrieve the appropriate cache object, cache it for 
@@ -1690,9 +1628,7 @@
         } 
         else 
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Covers: type1: %d, type2: %d", type1, type2);
-#endif
+                POSTGIS_DEBUGF(3, "Covers: type1: %d, type2: %d", type1, type2);
         }
         
 	initGEOS(lwnotice, lwnotice);
@@ -1785,9 +1721,7 @@
         type2 = lwgeom_getType((uchar)SERIALIZED_FORM(geom2)[0]);
         if(type1 == POINTTYPE && type2 == POLYGONTYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Point in Polygon test requested...short-circuiting.");
-#endif
+                POSTGIS_DEBUG(3, "Point in Polygon test requested...short-circuiting.");
 
                 point = lwpoint_deserialize(SERIALIZED_FORM(geom1));
                 poly = lwpoly_deserialize(SERIALIZED_FORM(geom2));
@@ -1908,9 +1842,7 @@
 		if ( box1.ymin < box2.ymin ) PG_RETURN_BOOL(FALSE);
 		if ( box1.ymax > box2.ymax ) PG_RETURN_BOOL(FALSE);
 
-#ifdef PGIS_DEBUG
-                lwnotice("bounding box short-circuit missed.");
-#endif
+                POSTGIS_DEBUG(3, "bounding box short-circuit missed.");
 	}
         /*
          * short-circuit 2: if geom1 is a point and geom2 is a polygon
@@ -1920,9 +1852,7 @@
         type2 = lwgeom_getType((uchar)SERIALIZED_FORM(geom2)[0]);
         if(type1 == POINTTYPE && type2 == POLYGONTYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Point in Polygon test requested...short-circuiting.");
-#endif
+                POSTGIS_DEBUG(3, "Point in Polygon test requested...short-circuiting.");
 
                 point = lwpoint_deserialize(SERIALIZED_FORM(geom1));
                 poly = lwpoly_deserialize(SERIALIZED_FORM(geom2));
@@ -2128,9 +2058,8 @@
 	type2 = lwgeom_getType((uchar)SERIALIZED_FORM(geom2)[0]);
 	if(type1 == POINTTYPE && type2 == POLYGONTYPE)
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("Point in Polygon test requested...short-circuiting.");
-#endif
+		POSTGIS_DEBUG(3, "Point in Polygon test requested...short-circuiting.");
+
 		point = lwpoint_deserialize(SERIALIZED_FORM(geom1));
 		poly = lwpoly_deserialize(SERIALIZED_FORM(geom2));
 
@@ -2163,9 +2092,8 @@
 	}
 	else if(type1 == POLYGONTYPE && type2 == POINTTYPE)
 	{
-	#ifdef PGIS_DEBUG
-		lwnotice("Point in Polygon test requested...short-circuiting.");
-#endif
+		POSTGIS_DEBUG(3, "Point in Polygon test requested...short-circuiting.");
+
 		point = lwpoint_deserialize(SERIALIZED_FORM(geom2));
 		poly = lwpoly_deserialize(SERIALIZED_FORM(geom1));
 
@@ -2368,9 +2296,8 @@
 	type2 = lwgeom_getType((uchar)SERIALIZED_FORM(geom2)[0]);
 	if(type1 == POINTTYPE && type2 == POLYGONTYPE)
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("Point outside Polygon test requested...short-circuiting.");
-#endif
+		POSTGIS_DEBUG(3, "Point outside Polygon test requested...short-circuiting.");
+
 		point = lwpoint_deserialize(SERIALIZED_FORM(geom1));
 		poly = lwpoly_deserialize(SERIALIZED_FORM(geom2));
 
@@ -2403,9 +2330,8 @@
 	}
 	else if(type1 == POLYGONTYPE && type2 == POINTTYPE)
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("Point outside Polygon test requested...short-circuiting.");
-#endif
+		POSTGIS_DEBUG(3, "Point outside Polygon test requested...short-circuiting.");
+
 		point = lwpoint_deserialize(SERIALIZED_FORM(geom2));
 		poly = lwpoly_deserialize(SERIALIZED_FORM(geom1));
 
@@ -2565,9 +2491,7 @@
 	profstart(PROF_QRUN);
 #endif
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"in relate_full()");
-#endif
+	POSTGIS_DEBUG(2, "in relate_full()");
 
 	geom1 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	geom2 = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
@@ -2593,22 +2517,18 @@
 	profstop(PROF_P2G2);
 #endif
 
-#ifdef PGIS_DEBUG
- 	elog(NOTICE,"constructed geometries ");
-#endif
+ 	POSTGIS_DEBUG(3, "constructed geometries ");
 
 	if ((g1==NULL) || (g2 == NULL))
 		elog(NOTICE,"g1 or g2 are null");
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,GEOSGeomToWKT(g1));
-	elog(NOTICE,GEOSGeomToWKT(g2));
+	POSTGIS_DEBUGF(3, "%s", GEOSGeomToWKT(g1));
+	POSTGIS_DEBUGF(3, "%s", GEOSGeomToWKT(g2));
 
-	/*elog(NOTICE,"valid g1 = %i", GEOSisvalid(g1));*/
-	/*elog(NOTICE,"valid g2 = %i",GEOSisvalid(g2));*/
+	/*POSTGIS_DEBUGF(3, "valid g1 = %i", GEOSisvalid(g1));*/
+	/*POSTGIS_DEBUGF(3, "valid g2 = %i",GEOSisvalid(g2));*/
 
-	elog(NOTICE,"about to relate()");
-#endif
+	POSTGIS_DEBUG(3, "about to relate()");
 
 
 #ifdef PROFILE
@@ -2619,9 +2539,7 @@
 	profstop(PROF_GRUN);
 #endif
 
-#ifdef PGIS_DEBUG
- 	elog(NOTICE,"finished relate()");
-#endif
+ 	POSTGIS_DEBUG(3, "finished relate()");
 
 	GEOSGeom_destroy(g1);
 	GEOSGeom_destroy(g2);
@@ -2738,9 +2656,7 @@
 	GEOSGeom g1;
 	int result;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"issimple called");
-#endif
+	POSTGIS_DEBUG(2, "issimple called");
 
 #ifdef PROFILE
 	profstart(PROF_QRUN);
@@ -2913,31 +2829,25 @@
 	uchar *points, *ptr;
 	POINTARRAY *ret;
 
-#ifdef PGIS_DEBUG_GEOS2POSTGIS 
-	lwnotice("ptarray_fromGEOSCoordSeq called");
-#endif
+	LWDEBUG(2, "ptarray_fromGEOSCoordSeq called");
 
 	if ( ! GEOSCoordSeq_getSize(cs, &size) )
 			lwerror("Exception thrown");
 
-#ifdef PGIS_DEBUG_GEOS2POSTGIS 
-	lwnotice(" GEOSCoordSeq size: %d", size);
-#endif
+	LWDEBUGF(4, " GEOSCoordSeq size: %d", size);
 
 	if ( want3d )
 	{
 		if ( ! GEOSCoordSeq_getDimensions(cs, &dims) )
 			lwerror("Exception thrown");
-#ifdef PGIS_DEBUG_GEOS2POSTGIS 
-		lwnotice(" GEOSCoordSeq dimensions: %d", dims);
-#endif
+
+		LWDEBUGF(4, " GEOSCoordSeq dimensions: %d", dims);
+
 		/* forget higher dimensions (if any) */
 		if ( dims > 3 ) dims = 3;
 	}
 
-#ifdef PGIS_DEBUG_GEOS2POSTGIS 
-	lwnotice(" output dimensions: %d", dims);
-#endif
+	LWDEBUGF(4, " output dimensions: %d", dims);
 
 	ptsize = sizeof(double)*dims;
 
@@ -2973,9 +2883,8 @@
 	{
 		if ( want3d )
 		{
-#ifdef PGIS_DEBUG
-			elog(NOTICE, "Geometry has no Z, won't provide one");
-#endif
+			LWDEBUG(3, "Geometry has no Z, won't provide one");
+
 			want3d = 0;
 		}
 	}
@@ -2989,26 +2898,23 @@
 		unsigned int i, ngeoms;
 
 		case GEOS_POINT:
-#ifdef PGIS_DEBUG_GEOS2POSTGIS
-	lwnotice("lwgeom_from_geometry: it's a Point");
-#endif
+			LWDEBUG(4, "lwgeom_from_geometry: it's a Point");
+
 			cs = GEOSGeom_getCoordSeq(geom);
 			pa = ptarray_from_GEOSCoordSeq(cs, want3d);
 			return (LWGEOM *)lwpoint_construct(SRID, NULL, pa);
 			
 		case GEOS_LINESTRING:
 		case GEOS_LINEARRING:
-#ifdef PGIS_DEBUG_GEOS2POSTGIS
-	lwnotice("lwgeom_from_geometry: it's a LineString or LinearRing");
-#endif
+			LWDEBUG(4, "lwgeom_from_geometry: it's a LineString or LinearRing");
+
 			cs = GEOSGeom_getCoordSeq(geom);
 			pa = ptarray_from_GEOSCoordSeq(cs, want3d);
 			return (LWGEOM *)lwline_construct(SRID, NULL, pa);
 
 		case GEOS_POLYGON:
-#ifdef PGIS_DEBUG_GEOS2POSTGIS
-	lwnotice("lwgeom_from_geometry: it's a Polygon");
-#endif
+			LWDEBUG(4, "lwgeom_from_geometry: it's a Polygon");
+
 			ngeoms = GEOSGetNumInteriorRings(geom);
 			ppaa = lwalloc(sizeof(POINTARRAY *)*(ngeoms+1));
 			g = GEOSGetExteriorRing(geom);
@@ -3028,9 +2934,8 @@
 		case GEOS_MULTILINESTRING:
 		case GEOS_MULTIPOLYGON:
 		case GEOS_GEOMETRYCOLLECTION:
-#ifdef PGIS_DEBUG_GEOS2POSTGIS
-	lwnotice("lwgeom_from_geometry: it's a Collection or Multi");
-#endif
+			LWDEBUG(4, "lwgeom_from_geometry: it's a Collection or Multi");
+
 			ngeoms = GEOSGetNumGeometries(geom);
 			geoms = NULL;
 			if ( ngeoms )
@@ -3067,9 +2972,7 @@
 		return NULL;
 	}
 
-#ifdef PGIS_DEBUG_GEOS2POSTGIS
-	lwnotice("GEOS2POSTGIS: GEOS2LWGEOM returned a %s", lwgeom_summary(lwgeom, 0)); 
-#endif
+	LWDEBUGF(4, "GEOS2POSTGIS: GEOS2LWGEOM returned a %s", lwgeom_summary(lwgeom, 0)); 
 
 	if ( is_worth_caching_lwgeom_bbox(lwgeom) )
 	{
@@ -3120,9 +3023,9 @@
 		lwerror("POSTGIS2GEOS conversion failed");
 	}
 
-#ifdef PGIS_DEBUG_CONVERTER
+#if POSTGIS_DEBUG_LEVEL >= 4
 	wkb = GEOSGeomToWKT(geom);
-	lwnotice("GEOS geom: %s", wkb);
+	LWDEBUGF(4, "GEOS geom: %s", wkb);
 #endif
 
 	return geom;
@@ -3150,9 +3053,9 @@
 	for (i=0; i<size; i++)
 	{
 		getPoint3dz_p(pa, i, &p);
-#ifdef PGIS_DEBUG_CONVERTER
-lwnotice("Point: %g,%g,%g", p.x, p.y, p.z);
-#endif
+
+		LWDEBUGF(4, "Point: %g,%g,%g", p.x, p.y, p.z);
+
 		GEOSCoordSeq_setX(sq, i, p.x);
 		GEOSCoordSeq_setY(sq, i, p.y);
 		if ( dims == 3 ) GEOSCoordSeq_setZ(sq, i, p.z);
@@ -3169,28 +3072,23 @@
         LWGEOM *tmp;
 	*/
 	unsigned int ngeoms, i;
-	int type;
+	int type = 0;
 	int geostype;
-#ifdef PGIS_DEBUG_POSTGIS2GEOS 
+#if POSTGIS_DEBUG_LEVEL >= 4 
 	char *wkt;
 #endif
 
-#ifdef PGIS_DEBUG_POSTGIS2GEOS 
-	lwnotice("LWGEOM2GEOS got a %s", lwgeom_typename(type));
-#endif
+	LWDEBUGF(4, "LWGEOM2GEOS got a %s", lwgeom_typename(type));
 
         if(has_arc(lwgeom))
         {
-#ifdef PGIS_DEBUG_CALLS
-                lwnotice("LWGEOM2GEOS_c: arced geometry found.");
-#endif
+                LWDEBUG(3, "LWGEOM2GEOS_c: arced geometry found.");
+
 		lwerror("Exception in LWGEOM2GEOS: curved geometry not supported.");
 		/*
                 tmp = lwgeom;
                 lwgeom = lwgeom_segmentize(tmp, 32);
-#ifdef PGIS_DEBUG_CALLS
-                lwnotice("LWGEOM2GEOM_c: was %p, is %p", tmp, lwgeom);
-#endif
+                LWDEBUGF(3, "LWGEOM2GEOM_c: was %p, is %p", tmp, lwgeom);
 		*/
         }
         type = TYPE_GETTYPE(lwgeom->type);
@@ -3261,19 +3159,16 @@
 			break;
 
 		default:
-#ifdef PGIS_DEBUG
-                        lwerror("LWGEOM2GEOS_c: Unknown geometry type: %d", type);
-#else 
 			lwerror("Unknown geometry type: %d", type);
-#endif
+
 			return NULL;
 	}
 
 	GEOSSetSRID(g, lwgeom->SRID);
 
-#ifdef PGIS_DEBUG_POSTGIS2GEOS 
+#if POSTGIS_DEBUG_LEVEL >= 4 
 	wkt = GEOSGeomToWKT(g);
-	lwnotice("LWGEOM2GEOS: GEOSGeom: %s", wkt);
+	LWDEBUGF(4, "LWGEOM2GEOS: GEOSGeom: %s", wkt);
 	/*
         if(tmp != NULL) lwgeom_release(tmp);
 	*/
@@ -3314,10 +3209,9 @@
 	initGEOS(lwnotice, lwnotice);
 
 	geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
-#ifdef PGIS_DEBUG_CONVERTER
-	elog(NOTICE, "GEOSnoop: IN: %s", unparse_WKT(SERIALIZED_FORM(geom), malloc, free));
-#endif
 
+	POSTGIS_DEBUGF(2, "GEOSnoop: IN: %s", unparse_WKT(SERIALIZED_FORM(geom), malloc, free));
+
 	geosgeom = POSTGIS2GEOS(geom);
 	if ( ! geosgeom ) PG_RETURN_NULL();
 
@@ -3329,9 +3223,7 @@
 	result = GEOS2POSTGIS(geosgeom, TYPE_HASZ(geom->type));
 	GEOSGeom_destroy(geosgeom);
 
-#ifdef PGIS_DEBUG_CONVERTER
-	elog(NOTICE, "GEOSnoop: OUT: %s", unparse_WKT(SERIALIZED_FORM(result), malloc, free));
-#endif
+	POSTGIS_DEBUGF(4, "GEOSnoop: OUT: %s", unparse_WKT(SERIALIZED_FORM(result), malloc, free));
 
 	PG_FREE_IF_COPY(geom, 0);
 
@@ -3350,11 +3242,11 @@
 	GEOSGeom *vgeoms;
 	int SRID=-1;
 	size_t offset;
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL > 0 
 	static int call=1;
 #endif
 
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL >= 3 
 	call++;
 #endif
 
@@ -3367,9 +3259,7 @@
 
 	nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "polygonize_garray: number of elements: %d", nelems);
-#endif
+	POSTGIS_DEBUGF(3, "polygonize_garray: number of elements: %d", nelems);
 
 	if ( nelems == 0 ) PG_RETURN_NULL();
 
@@ -3398,14 +3288,12 @@
 		}
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "polygonize_garray: invoking GEOSpolygonize");
-#endif
+	POSTGIS_DEBUG(3, "polygonize_garray: invoking GEOSpolygonize");
 
 	geos_result = GEOSPolygonize(vgeoms, nelems);
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "polygonize_garray: GEOSpolygonize returned");
-#endif
+
+	POSTGIS_DEBUG(3, "polygonize_garray: GEOSpolygonize returned");
+
 	for (i=0; i<nelems; ++i) GEOSGeom_destroy(vgeoms[i]);
 	pfree(vgeoms);
 
@@ -3465,9 +3353,7 @@
 	}
 
 
-#ifdef PGIS_DEBUG
-  	elog(NOTICE,"result: %s", GEOSGeomToWKT(g3) ) ;
-#endif
+  	POSTGIS_DEBUGF(3, "result: %s", GEOSGeomToWKT(g3) ) ;
 
 	GEOSSetSRID(g3, pglwgeom_getSRID(geom1));
 
@@ -3532,22 +3418,21 @@
 	GEOSGeom geos_result, shp;
 	GEOSGeom vgeoms[1];
 	int SRID=-1;
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL > 0
 	static int call=1;
 #endif
 
-#ifdef PGIS_DEBUG
+	PG_LWGEOM *geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
+
+#if POSTGIS_DEBUG_LEVEL >= 3
 	call++;
 	lwnotice("buildarea called (call %d)", call);
 #endif
 
-	PG_LWGEOM *geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	SRID = pglwgeom_getSRID(geom);
 	is3d = TYPE_HASZ(geom->type);
 
-#ifdef PGIS_DEBUG
-	lwnotice("LWGEOM_buildarea got geom @ %x", geom);
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_buildarea got geom @ %p", geom);
 
 	initGEOS(lwnotice, lwnotice);
 
@@ -3555,9 +3440,7 @@
 	geos_result = GEOSPolygonize(vgeoms, 1);
 	GEOSGeom_destroy(vgeoms[0]);
 
-#ifdef PGIS_DEBUG
-	lwnotice("GEOSpolygonize returned @ %x", geos_result);
-#endif
+	POSTGIS_DEBUGF(3, "GEOSpolygonize returned @ %p", geos_result);
 
 	/* Null return from GEOSpolygonize */
 	if ( ! geos_result ) PG_RETURN_NULL();
@@ -3576,9 +3459,7 @@
 
 	ngeoms = GEOSGetNumGeometries(geos_result);
 
-#ifdef PGIS_DEBUG
-	lwnotice("GEOSpolygonize: ngeoms in polygonize output: %d", ngeoms);
-#endif
+	POSTGIS_DEBUGF(3, "GEOSpolygonize: ngeoms in polygonize output: %d", ngeoms);
 
 	/*
 	 * No geometries in collection, return NULL
@@ -3720,9 +3601,7 @@
 
 	if ( !cache )
 	{
-		#ifdef PGIS_DEBUG
-		lwnotice( "get_prepared_geometry_cache: creating cache: %x", cache);
-		#endif
+		LWDEBUGF(3, "get_prepared_geometry_cache: creating cache: %x", cache);
 		
 		cache = lwalloc( sizeof( PREPARED_GEOM_CACHE ));
 		
@@ -3733,25 +3612,19 @@
 	{
 		if ( !cache->prepared_geom )
 		{
-			#ifdef PGIS_DEBUG
-			lwnotice("get_prepared_geometry_cache: preparing obj");
-			#endif
+			LWDEBUGF(3, "get_prepared_geometry_cache: preparing obj");
 			
 			g = POSTGIS2GEOS( serialized_geom);
 			cache->prepared_geom = GEOSPrepare( g);
 		}
 		else
 		{
-			#ifdef PGIS_DEBUG
-			lwnotice("get_prepared_geometry_cache: prepared obj in cache");
-			#endif
+			LWDEBUGF(3, "get_prepared_geometry_cache: prepared obj in cache");
 		}
 	}
 	else
 	{
-		#ifdef PGIS_DEBUG
-		lwnotice("get_prepared_geometry_cache: obj NOT in cache");
-		#endif
+		LWDEBUG(3, "get_prepared_geometry_cache: obj NOT in cache");
 
 		GEOSPreparedGeom_destroy( cache->prepared_geom);
 

Modified: trunk/lwgeom/lwgeom_gist.c
===================================================================
--- trunk/lwgeom/lwgeom_gist.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_gist.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -20,19 +20,16 @@
 #include "lwgeom_pg.h"
 #include "stringBuffer.h"
 
+#if POSTGIS_DEBUG_LEVEL > 0
+#include "wktparse.h"
+#endif
+
+
 /*
  * implementation GiST support and basic LWGEOM operations (like &&)
  */
 
 
-/* #define PGIS_DEBUG */
-/* #define PGIS_DEBUG_CALLS */
-/* #define PGIS_DEBUG_GIST */
-/* #define PGIS_DEBUG_GIST2 */
-/* #define PGIS_DEBUG_GIST3 */
-/* #define PGIS_DEBUG_GIST4 */
-/* #define PGIS_DEBUG_GIST5 */
-/* #define PGIS_DEBUG_GIST6 */
 
 Datum LWGEOM_overlap(PG_FUNCTION_ARGS);
 Datum LWGEOM_overleft(PG_FUNCTION_ARGS);
@@ -102,9 +99,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_overlap --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_overlap --entry");
 
 	if ( pglwgeom_getSRID(lwgeom1) != pglwgeom_getSRID(lwgeom2) )
 	{
@@ -130,17 +125,11 @@
 	PG_FREE_IF_COPY(lwgeom1, 0);
         PG_FREE_IF_COPY(lwgeom2, 1);
 
-#ifdef PGIS_DEBUG
-#ifdef PGIS_DEBUG_GIST2
-	elog(NOTICE,"GIST: lwgeom_overlap:\n(%f %f, %f %f) (%f %f %f %f) = %i",
+	POSTGIS_DEBUGF(3, "GIST: lwgeom_overlap:\n(%f %f, %f %f) (%f %f %f %f) = %i",
 		box1.xmin, box1.ymax, box1.xmax, box1.ymax,
 		box2.xmin, box2.ymax, box2.xmax, box2.ymax,
 		result
 		);
-#else
-	elog(NOTICE,"GIST: lwgeom_overlap: call");
-#endif
-#endif
 
         PG_RETURN_BOOL(result);
 }
@@ -155,9 +144,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_overleft --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_overleft --entry");
 
 	if ( pglwgeom_getSRID(lwgeom1) != pglwgeom_getSRID(lwgeom2) )
 	{
@@ -193,9 +180,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_left --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_left --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -225,9 +210,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_right --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_right --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -257,9 +240,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_overright --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_overright --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -289,9 +270,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_overbelow --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_overbelow --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -321,9 +300,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_below --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_below --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -353,9 +330,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_above --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_above --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -385,9 +360,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_overabove --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_overabove --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -417,9 +390,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_contained --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_contained --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -449,9 +420,7 @@
 	BOX2DFLOAT4 box1;
 	BOX2DFLOAT4 box2;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_contain --entry");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_contain --entry");
 
 	errorIfSRIDMismatch(pglwgeom_getSRID(lwgeom1), pglwgeom_getSRID(lwgeom2));
 
@@ -484,31 +453,24 @@
 	GISTENTRY *entry=(GISTENTRY*)PG_GETARG_POINTER(0);
 	GISTENTRY *retval;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_gist_compress called");
-#endif
+	PG_LWGEOM *in; /* lwgeom serialized */
+	BOX2DFLOAT4 *rr;
 
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_gist_compress called");
+
 	if (entry->leafkey)
 	{
-#ifdef PGIS_DEBUG_GIST4
-		elog(NOTICE,"GIST: LWGEOM_gist_compress got a leafkey");
-#endif
+		POSTGIS_DEBUG(4, "GIST: LWGEOM_gist_compress got a leafkey");
+
 		retval = palloc(sizeof(GISTENTRY));
 		if ( DatumGetPointer(entry->key) != NULL )
 		{
-#ifdef PGIS_DEBUG_GIST4
-		elog(NOTICE,"GIST: LWGEOM_gist_compress got a non-NULL key");
-#endif
+			POSTGIS_DEBUG(4, "GIST: LWGEOM_gist_compress got a non-NULL key");
 
-			PG_LWGEOM *in; /* lwgeom serialized */
-			BOX2DFLOAT4 *rr;
-
 			/* lwgeom serialized form */
 			in = (PG_LWGEOM*)PG_DETOAST_DATUM(entry->key);
 
-#ifdef PGIS_DEBUG_GIST4
-		elog(NOTICE,"GIST: LWGEOM_gist_compress detoasted entry->key: %s", unparse_WKT(in+4, malloc, free));
-#endif
+			POSTGIS_DEBUGF(4, "GIST: LWGEOM_gist_compress detoasted entry->key: %s", unparse_WKT(in+VARHDRSZ, malloc, free));
 
 			if (in == NULL)
 			{
@@ -524,24 +486,19 @@
 				! finite(rr->xmax) ||
 				! finite(rr->ymax) )
 			{
-#ifdef PGIS_DEBUG_GIST4
-			elog(NOTICE, "found empty or infinite geometry");
-#endif
+
+				POSTGIS_DEBUG(4, "found empty or infinite geometry");
+
 				pfree(rr);
 				if (in!=(PG_LWGEOM*)DatumGetPointer(entry->key))
 					pfree(in);  /* PG_FREE_IF_COPY */
 				PG_RETURN_POINTER(entry);
 			}
 
-#ifdef PGIS_DEBUG_GIST4
-			elog(NOTICE,"GIST: LWGEOM_gist_compress got box2d");
-#endif
+			POSTGIS_DEBUG(4, "GIST: LWGEOM_gist_compress got box2d");
 
+			POSTGIS_DEBUGF(3, "GIST: LWGEOM_gist_compress -- got box2d BOX(%.15g %.15g,%.15g %.15g)", rr->xmin, rr->ymin, rr->xmax, rr->ymax);
 
-#ifdef PGIS_DEBUG_GIST2
-	elog(NOTICE,"GIST: LWGEOM_gist_compress -- got box2d BOX(%.15g %.15g,%.15g %.15g)", rr->xmin, rr->ymin, rr->xmax, rr->ymax);
-#endif
-
 			if (in != (PG_LWGEOM*)DatumGetPointer(entry->key))
 				pfree(in);  /* PG_FREE_IF_COPY */
 
@@ -561,9 +518,7 @@
 		}
 		else
 		{
-#ifdef PGIS_DEBUG_GIST4
-		elog(NOTICE,"GIST: LWGEOM_gist_compress got a NULL key");
-#endif
+			POSTGIS_DEBUG(4, "GIST: LWGEOM_gist_compress got a NULL key");
 
 #if POSTGIS_PGSQL_VERSION >= 82
 			gistentryinit(*retval, (Datum) 0, entry->rel,
@@ -578,9 +533,8 @@
 	}
 	else
 	{
-#ifdef PGIS_DEBUG_GIST4
-		elog(NOTICE,"GIST: LWGEOM_gist_compress got a non-leafkey");
-#endif
+		POSTGIS_DEBUG(4, "GIST: LWGEOM_gist_compress got a non-leafkey");
+
 		retval = entry;
 	}
 
@@ -597,9 +551,7 @@
 	bool result;
 	BOX2DFLOAT4  box;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_gist_consistent called");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_gist_consistent called");
 
 	if ( ((Pointer *) PG_GETARG_DATUM(1)) == NULL )
 	{
@@ -641,9 +593,7 @@
 {
 	bool retval;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: lwgeom_rtree_internal_consistent called with strategy=%i", strategy);
-#endif
+	POSTGIS_DEBUGF(2, "GIST: lwgeom_rtree_internal_consistent called with strategy=%i", strategy);
 
 	switch(strategy) {
 		case RTLeftStrategyNumber:
@@ -654,31 +604,30 @@
 			break;
 		case RTOverlapStrategyNumber:  /*optimized for speed */
 
-        retval = (((key->xmax>= query->xmax) &&
-			 (key->xmin <= query->xmax)) ||
-			((query->xmax>= key->xmax) &&
-			 (query->xmin<= key->xmax)))
-		&&
-		(((key->ymax>= query->ymax) &&
-		  (key->ymin<= query->ymax)) ||
-		 ((query->ymax>= key->ymax) &&
-		  (query->ymin<= key->ymax)));
+		        retval = (((key->xmax>= query->xmax) &&
+				 (key->xmin <= query->xmax)) ||
+				((query->xmax>= key->xmax) &&
+				 (query->xmin<= key->xmax)))
+				&&
+				(((key->ymax>= query->ymax) &&
+		  		(key->ymin<= query->ymax)) ||
+		 		((query->ymax>= key->ymax) &&
+		  		(query->ymin<= key->ymax)));
 
 
+#if POSTGIS_DEBUG_LEVEL >=4
+			/*keep track and report info about how many times this is called */
+			if (counter_intern == 0)
+			{
+				POSTGIS_DEBUGF(4, "search bounding box is: <%.16g %.16g,%.16g %.16g> - size box2d= %ld",
+				 	query->xmin,query->ymin,query->xmax,query->ymax,sizeof(BOX2DFLOAT4));
 
-#ifdef PGIS_DEBUG_GIST5
-/*keep track and report info about how many times this is called */
-					if (counter_intern == 0)
-					{
-									 elog(NOTICE,"search bounding box is: <%.16g %.16g,%.16g %.16g> - size box2d= %i",
-									 	query->xmin,query->ymin,query->xmax,query->ymax,sizeof(BOX2DFLOAT4));
+			}
 
-					}
 
-
-
-elog(NOTICE,"%i:(int)<%.8g %.8g,%.8g %.8g>&&<%.8g %.8g,%.8g %.8g> %i",counter_intern,key->xmin,key->ymin,key->xmax,key->ymax,
-		  						query->xmin,query->ymin,query->xmax,query->ymax,   (int) retval);
+			POSTGIS_DEBUGF(4, "%i:(int)<%.8g %.8g,%.8g %.8g>&&<%.8g %.8g,%.8g %.8g> %i",counter_intern,key->xmin,key->ymin,key->xmax,key->ymax,
+		  			query->xmin,query->ymin,query->xmax,query->ymax,   (int) retval);
+		
 			counter_intern++;
 #endif
 
@@ -721,11 +670,9 @@
 lwgeom_rtree_leaf_consistent(BOX2DFLOAT4 *key,
 	BOX2DFLOAT4 *query, StrategyNumber strategy)
 {
-    bool retval;
+	bool retval;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: rtree_leaf_consist called with strategy=%i",strategy);
-#endif
+	POSTGIS_DEBUGF(2, "GIST: rtree_leaf_consist called with strategy=%d",strategy);
 
 	switch (strategy)
 	{
@@ -736,23 +683,25 @@
 			retval = DatumGetBool(DirectFunctionCall2(BOX2D_overleft, PointerGetDatum(key), PointerGetDatum(query)));
 			break;
 		case RTOverlapStrategyNumber: /*optimized for speed */
-			           retval = (((key->xmax>= query->xmax) &&
-			   			 (key->xmin <= query->xmax)) ||
-			   			((query->xmax>= key->xmax) &&
-			   			 (query->xmin<= key->xmax)))
-			   		&&
-			   		(((key->ymax>= query->ymax) &&
-			   		  (key->ymin<= query->ymax)) ||
-			   		 ((query->ymax>= key->ymax) &&
-			   		  (query->ymin<= key->ymax)));
-#ifdef PGIS_DEBUG_GIST5
-/*keep track and report info about how many times this is called */
+			retval = (((key->xmax>= query->xmax) &&
+				 (key->xmin <= query->xmax)) ||
+				 ((query->xmax>= key->xmax) &&
+	   			 (query->xmin<= key->xmax)))
+			   	 &&
+				 (((key->ymax>= query->ymax) &&
+				 (key->ymin<= query->ymax)) ||
+				 ((query->ymax>= key->ymax) &&
+				 (query->ymin<= key->ymax)));
 
-			   elog(NOTICE,"%i:gist test (leaf) <%.6g %.6g,%.6g %.6g> &&  <%.6g %.6g,%.6g %.6g> --> %i",counter_leaf,key->xmin,key->ymin,key->xmax,key->ymax,
-			   		  						query->xmin,query->ymin,query->xmax,query->ymax,   (int) retval);
+#if POSTGIS_DEBUG_LEVEL >= 4
+			/*keep track and report info about how many times this is called */
+			POSTGIS_DEBUGF(4, "%i:gist test (leaf) <%.6g %.6g,%.6g %.6g> &&  <%.6g %.6g,%.6g %.6g> --> %i",
+				counter_leaf,key->xmin,key->ymin,key->xmax,key->ymax,
+				query->xmin,query->ymin,query->xmax,query->ymax,   (int) retval);
+			counter_leaf++;
 #endif
-			   counter_leaf++;
-		  return(retval);
+			return(retval);
+
 			break;
 		case RTOverRightStrategyNumber:
 			retval = DatumGetBool(DirectFunctionCall2(BOX2D_overright, PointerGetDatum(key), PointerGetDatum(query)));
@@ -792,11 +741,11 @@
 PG_FUNCTION_INFO_V1(LWGEOM_gist_decompress);
 Datum LWGEOM_gist_decompress(PG_FUNCTION_ARGS)
 {
-#ifdef PGIS_DEBUG_CALLS
+#if POSTGIS_DEBUG_LEVEL >= 4
 	static unsigned int counter2 = 0;
-	elog(NOTICE,"GIST: LWGEOM_gist_decompress called %i",counter2);
 	counter2++;
 #endif
+	POSTGIS_DEBUGF(2, "GIST: LWGEOM_gist_decompress called %i",counter2);
 
 	PG_RETURN_POINTER(PG_GETARG_POINTER(0));
 }
@@ -821,9 +770,7 @@
 	BOX2DFLOAT4 *cur,
 			   *pageunion;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_gist_union called\n");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_gist_union called\n");
 
 #if POSTGIS_PGSQL_VERSION < 80
 	numranges = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
@@ -858,11 +805,8 @@
 
 	*sizep = sizeof(BOX2DFLOAT4);
 
-#ifdef PGIS_DEBUG_GIST
-	elog(NOTICE,"GIST: gbox_union called with numranges=%i pageunion is: <%.16g %.16g,%.16g %.16g>", numranges,pageunion->xmin, pageunion->ymin, pageunion->xmax, pageunion->ymax);
-#endif
+	POSTGIS_DEBUGF(3, "GIST: gbox_union called with numranges=%i pageunion is: <%.16g %.16g,%.16g %.16g>", numranges,pageunion->xmin, pageunion->ymin, pageunion->xmax, pageunion->ymax);
 
-
 	PG_RETURN_POINTER(pageunion);
 }
 
@@ -877,11 +821,8 @@
 {
 	float result;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: size_box2d called");
-#endif
+	POSTGIS_DEBUG(2, "GIST: size_box2d called");
 
-
 	if (DatumGetPointer(box2d) != NULL)
 	{
 		BOX2DFLOAT4 *a = (BOX2DFLOAT4*) DatumGetPointer(box2d);
@@ -897,9 +838,8 @@
 	}
 	else result = (float) 0.0;
 
-#ifdef PGIS_DEBUG_GIST
-	elog(NOTICE,"GIST: size_box2d called - returning %.15g",result);
-#endif
+	POSTGIS_DEBUGF(3, "GIST: size_box2d called - returning %.15g",result);
+
 	return result;
 }
 
@@ -914,9 +854,7 @@
 {
 	double result;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: size_box2d_double called");
-#endif
+	POSTGIS_DEBUG(2, "GIST: size_box2d_double called");
 
 	if (DatumGetPointer(box2d) != NULL)
 	{
@@ -936,9 +874,8 @@
 		result = (double) 0.0;
 	}
 
-#ifdef PGIS_DEBUG_GIST
-	elog(NOTICE,"GIST: size_box2d_double called - returning %.15g",result);
-#endif
+	POSTGIS_DEBUGF(3, "GIST: size_box2d_double called - returning %.15g",result);
+
 	return result;
 }
 
@@ -957,15 +894,12 @@
 	Datum		ud;
 	double		tmp1;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_gist_penalty called");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_gist_penalty called");
 
 	if (DatumGetPointer(origentry->key) == NULL && DatumGetPointer(newentry->key) == NULL)
 	{
-#ifdef PGIS_DEBUG_GIST6
-		elog(NOTICE,"GIST: LWGEOM_gist_penalty called with both inputs NULL");
-#endif
+		POSTGIS_DEBUG(4, "GIST: LWGEOM_gist_penalty called with both inputs NULL");
+
 		*result = 0;
 	}
 	else
@@ -979,9 +913,7 @@
 	}
 
 
-#ifdef PGIS_DEBUG_GIST6
-	elog(NOTICE,"GIST: LWGEOM_gist_penalty called and returning %.15g", *result);
-#endif
+	POSTGIS_DEBUGF(4, "GIST: LWGEOM_gist_penalty called and returning %.15g", *result);
 
 	PG_RETURN_POINTER(result);
 }
@@ -1012,9 +944,7 @@
 	BOX2DFLOAT4 *b2 = (BOX2DFLOAT4 *) PG_GETARG_POINTER(1);
 	bool *result = (bool *)PG_GETARG_POINTER(2);
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_gist_same called");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_gist_same called");
 
 	if (b1 && b2)
 		*result = DatumGetBool(DirectFunctionCall2(BOX2D_same, PointerGetDatum(b1), PointerGetDatum(b2)));
@@ -1050,9 +980,7 @@
 	OffsetNumber maxoff;
 	int nbytes;
 
-#ifdef PGIS_DEBUG_CALLS
-	elog(NOTICE,"GIST: LWGEOM_gist_picksplit called");
-#endif
+	POSTGIS_DEBUG(2, "GIST: LWGEOM_gist_picksplit called");
 
 	posL = posR = posB = posT = 0;
 
@@ -1066,9 +994,7 @@
 
 	memcpy((void *) &pageunion, (void *) cur, sizeof(BOX2DFLOAT4));
 
-#ifdef PGIS_DEBUG_GIST6
-elog(NOTICE,"   cur is: <%.16g %.16g,%.16g %.16g>", cur->xmin, cur->ymin, cur->xmax, cur->ymax);
-#endif
+	POSTGIS_DEBUGF(4, "   cur is: <%.16g %.16g,%.16g %.16g>", cur->xmin, cur->ymin, cur->xmax, cur->ymax);
 
 
 	/* find MBR */
@@ -1098,11 +1024,8 @@
 			pageunion.ymin = cur->ymin;
 	}
 
-#ifdef PGIS_DEBUG_GIST6
-elog(NOTICE,"   pageunion is: <%.16g %.16g,%.16g %.16g>", pageunion.xmin, pageunion.ymin, pageunion.xmax, pageunion.ymax);
-#endif
+	POSTGIS_DEBUGF(4, "   pageunion is: <%.16g %.16g,%.16g %.16g>", pageunion.xmin, pageunion.ymin, pageunion.xmax, pageunion.ymax);
 
-
 	nbytes = (maxoff + 2) * sizeof(OffsetNumber);
 	listL = (OffsetNumber *) palloc(nbytes);
 	listR = (OffsetNumber *) palloc(nbytes);
@@ -1111,9 +1034,8 @@
 
 	if (allisequal)
 	{
-#ifdef PGIS_DEBUG_GIST6
-elog(NOTICE," AllIsEqual!");
-#endif
+		POSTGIS_DEBUG(4, " AllIsEqual!");
+
 #if POSTGIS_PGSQL_VERSION < 80
 		cur = (BOX2DFLOAT4*) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[OffsetNumberNext(FirstOffsetNumber)].key);
 #else
@@ -1185,12 +1107,10 @@
 			ADDLIST(listT, unionT, posT,i);
 	}
 
-#ifdef PGIS_DEBUG_GIST6
-elog(NOTICE,"   unionL is: <%.16g %.16g,%.16g %.16g>", unionL->xmin, unionL->ymin, unionL->xmax, unionL->ymax);
-elog(NOTICE,"   unionR is: <%.16g %.16g,%.16g %.16g>", unionR->xmin, unionR->ymin, unionR->xmax, unionR->ymax);
-elog(NOTICE,"   unionT is: <%.16g %.16g,%.16g %.16g>", unionT->xmin, unionT->ymin, unionT->xmax, unionT->ymax);
-elog(NOTICE,"   unionB is: <%.16g %.16g,%.16g %.16g>", unionB->xmin, unionB->ymin, unionB->xmax, unionB->ymax);
-#endif
+	POSTGIS_DEBUGF(4, "   unionL is: <%.16g %.16g,%.16g %.16g>", unionL->xmin, unionL->ymin, unionL->xmax, unionL->ymax);
+	POSTGIS_DEBUGF(4, "   unionR is: <%.16g %.16g,%.16g %.16g>", unionR->xmin, unionR->ymin, unionR->xmax, unionR->ymax);
+	POSTGIS_DEBUGF(4, "   unionT is: <%.16g %.16g,%.16g %.16g>", unionT->xmin, unionT->ymin, unionT->xmax, unionT->ymax);
+	POSTGIS_DEBUGF(4, "   unionB is: <%.16g %.16g,%.16g %.16g>", unionB->xmin, unionB->ymin, unionB->xmax, unionB->ymax);
 
 
 
@@ -1245,7 +1165,7 @@
 			PointerGetDatum(unionB), PointerGetDatum(unionT));
 		float sizeLR, sizeBT;
 
-/*elog(NOTICE,"direction is abigeous"); */
+		/*elog(NOTICE,"direction is abigeous"); */
 
 		sizeLR = size_box2d(interLR);
 		sizeBT = size_box2d(interBT);
@@ -1275,29 +1195,29 @@
 		v->spl_ldatum = PointerGetDatum(unionL);
 		v->spl_rdatum = PointerGetDatum(unionR);
 
-#ifdef PGIS_DEBUG_GIST6
+#if POSTGIS_DEBUG_LEVEL >= 4
 	{
 		char aaa[5000],bbb[100];
 		aaa[0] = 0;
 
-		elog(NOTICE,"   split direction was '%c'", direction);
-		elog(NOTICE,"   posL = %i, posR=%i", posL,posR);
-		elog(NOTICE,"   posL's (nleft) offset numbers:");
+		POSTGIS_DEBUGF(4, "   split direction was '%c'", direction);
+		POSTGIS_DEBUGF(4, "   posL = %i, posR=%i", posL,posR);
+		POSTGIS_DEBUG(4, "   posL's (nleft) offset numbers:");
 
 		for (i=0;i<posL;i++)
 		{
 			sprintf(bbb," %i", listL[i]);
 			strcat(aaa,bbb);
 		}
-		elog(NOTICE,aaa);
+		POSTGIS_DEBUGF(4, "%s", aaa);
 		aaa[0]=0;
-		elog(NOTICE,"   posR's (nright) offset numbers:");
+		POSTGIS_DEBUG(4, "   posR's (nright) offset numbers:");
 		for (i=0;i<posR;i++)
 		{
 			sprintf(bbb," %i", listR[i]);
 			strcat(aaa,bbb);
 		}
-		elog(NOTICE,aaa);
+		POSTGIS_DEBUGF(4, "%s", aaa);
 	}
 #endif
 
@@ -1317,29 +1237,29 @@
 		v->spl_ldatum = PointerGetDatum(unionB);
 		v->spl_rdatum = PointerGetDatum(unionT);
 
-#ifdef PGIS_DEBUG_GIST6
+#if POSTGIS_DEBUG_LEVEL >= 4 
 	{
 		char aaa[5000],bbb[100];
 		aaa[0]=0;
 
-		elog(NOTICE,"   split direction was '%c'", direction);
-		elog(NOTICE,"   posB = %i, posT=%i", posB,posT);
-		elog(NOTICE,"   posB's (nleft) offset numbers:");
+		POSTGIS_DEBUGF(4, "   split direction was '%c'", direction);
+		POSTGIS_DEBUGF(4, "   posB = %i, posT=%i", posB,posT);
+		POSTGIS_DEBUG(4, "   posB's (nleft) offset numbers:");
 
 		for (i=0;i<posB;i++)
 		{
 			sprintf(bbb," %i", listB[i]);
 			strcat(aaa,bbb);
 		}
-		elog(NOTICE,aaa);
+		POSTGIS_DEBUGF(4, "%s", aaa);
 		aaa[0]=0;
-		elog(NOTICE,"   posT's (nright) offset numbers:");
+		POSTGIS_DEBUG(4, "   posT's (nright) offset numbers:");
 		for (i=0;i<posT;i++)
 		{
 			sprintf(bbb," %i", listT[i]);
 			strcat(aaa,bbb);
 		}
-		elog(NOTICE,aaa);
+		POSTGIS_DEBUGF(4, "%s", aaa);
 	}
 #endif
 

Modified: trunk/lwgeom/lwgeom_gml.c
===================================================================
--- trunk/lwgeom/lwgeom_gml.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_gml.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -842,10 +842,9 @@
 	/* write query */
 	sprintf(query, "SELECT textcat(auth_name, textcat(':', auth_srid::text)) \
 		FROM spatial_ref_sys WHERE srid = '%d'", SRID);
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "Query: %s", query);
-#endif
 
+	POSTGIS_DEBUGF(3, "Query: %s", query);
+
 	/* execute query */
 	err = SPI_exec(query, 1);
 	if ( err < 0 ) {

Modified: trunk/lwgeom/lwgeom_inout.c
===================================================================
--- trunk/lwgeom/lwgeom_inout.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_inout.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -24,7 +24,6 @@
 #include "stringBuffer.h"
 
 
-/* #define PGIS_DEBUG 1 */
 
 #include "lwgeom_pg.h"
 #include "wktparse.h"
@@ -283,9 +282,7 @@
 	hexized_wkb_srid = unparse_WKB(SERIALIZED_FORM(lwgeom_input),
 		lwalloc, lwfree, byteorder, &size, 1);
 
-#ifdef PGIS_DEBUG
-  elog(NOTICE, "in WKBFromLWGEOM with WKB = '%s'", hexized_wkb_srid);
-#endif
+	LWDEBUGF(3, "in WKBFromLWGEOM with WKB = '%s'", hexized_wkb_srid);
 
 	hexized_wkb = hexized_wkb_srid;
 
@@ -295,14 +292,12 @@
 		hexized_wkb = (semicolonLoc+1);
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "in WKBFromLWGEOM with WKB (with no 'SRID=#;' = '%s'",
+	LWDEBUGF(3, "in WKBFromLWGEOM with WKB (with no 'SRID=#;' = '%s'",
 		hexized_wkb);
-#endif
 
 	size_result = size/2 + VARHDRSZ;
 	result = palloc(size_result);
-    SET_VARSIZE(result, size_result);
+	SET_VARSIZE(result, size_result);
 
 	/* have a hexized string, want to make it binary */
 	for (t=0; t< (size/2); t++)
@@ -330,12 +325,9 @@
 	lwnotice("unparse_WKB: prof: %lu", proftime[PROF_QRUN]);
 #endif
 
-#ifdef PGIS_DEBUG
-	lwnotice("Output size is %lu (comp: %lu)",
+	LWDEBUGF(3, "Output size is %lu (comp: %lu)",
 		VARSIZE(result), (unsigned long)size);
-#endif /* def PGIS_DEBUG */
 
-
 	PG_RETURN_POINTER(result);
 }
 
@@ -349,32 +341,27 @@
 	uchar	old_type;
 	int		size;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"in LWGEOM_addBBOX");
-#endif
+	POSTGIS_DEBUG(2, "in LWGEOM_addBBOX");
 
 	if (lwgeom_hasBBOX( lwgeom->type ) )
 	{
-#ifdef PGIS_DEBUG
-		elog(NOTICE,"LWGEOM_addBBOX  -- already has bbox");
-#endif
+		POSTGIS_DEBUG(3, "LWGEOM_addBBOX  -- already has bbox");
+
 		/* easy - already has one.  Just copy! */
 		result = palloc (VARSIZE(lwgeom));
-        SET_VARSIZE(result, VARSIZE(lwgeom));
+		SET_VARSIZE(result, VARSIZE(lwgeom));
 		memcpy(VARDATA(result), VARDATA(lwgeom), VARSIZE(lwgeom)-VARHDRSZ);
 		PG_RETURN_POINTER(result);
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"LWGEOM_addBBOX  -- giving it a bbox");
-#endif
+	POSTGIS_DEBUG(3, "LWGEOM_addBBOX  -- giving it a bbox");
 
 	/* construct new one */
 	if ( ! getbox2d_p(SERIALIZED_FORM(lwgeom), &box) )
 	{
 		/* Empty geom, no bbox to add */
 		result = palloc (VARSIZE(lwgeom));
-        SET_VARSIZE(result, VARSIZE(lwgeom));
+		SET_VARSIZE(result, VARSIZE(lwgeom));
 		memcpy(VARDATA(result), VARDATA(lwgeom), VARSIZE(lwgeom)-VARHDRSZ);
 		PG_RETURN_POINTER(result);
 	}
@@ -393,10 +380,8 @@
 	/* copy in bbox */
 	memcpy(result->data, &box, sizeof(BOX2DFLOAT4));
 
-#ifdef PGIS_DEBUG
-	lwnotice("result->type hasbbox: %d", TYPE_HASBBOX(result->type));
-	lwnotice("LWGEOM_addBBOX  -- about to copy serialized form");
-#endif
+	POSTGIS_DEBUGF(3, "result->type hasbbox: %d", TYPE_HASBBOX(result->type));
+	POSTGIS_DEBUG(3, "LWGEOM_addBBOX  -- about to copy serialized form");
 
 	/* everything but the type and length */
 	memcpy((char *)VARDATA(result)+sizeof(BOX2DFLOAT4)+1, (char *)VARDATA(lwgeom)+1, VARSIZE(lwgeom)-VARHDRSZ-1);
@@ -443,24 +428,19 @@
 	uchar old_type;
 	int size;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"in LWGEOM_dropBBOX");
-#endif
+	POSTGIS_DEBUG(2, "in LWGEOM_dropBBOX");
 
 	if (!lwgeom_hasBBOX( lwgeom->type ) )
 	{
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"LWGEOM_dropBBOX  -- doesnt have a bbox already");
-#endif
+		POSTGIS_DEBUG(3, "LWGEOM_dropBBOX  -- doesnt have a bbox already");
+
 		result = palloc (VARSIZE(lwgeom));
-        SET_VARSIZE(result, VARSIZE(lwgeom));
+		SET_VARSIZE(result, VARSIZE(lwgeom));
 		memcpy(VARDATA(result), VARDATA(lwgeom), VARSIZE(lwgeom)-VARHDRSZ);
 		PG_RETURN_POINTER(result);
 	}
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"LWGEOM_dropBBOX  -- dropping the bbox");
-#endif
+	POSTGIS_DEBUG(3, "LWGEOM_dropBBOX  -- dropping the bbox");
 
 	/* construct new one */
 	old_type = lwgeom->type;
@@ -468,7 +448,7 @@
 	size = VARSIZE(lwgeom)-sizeof(BOX2DFLOAT4);
 
 	result = palloc(size); /* 16 for bbox2d */
-    SET_VARSIZE(result, size);
+	SET_VARSIZE(result, size);
 
 	result->type = lwgeom_makeType_full(
 		TYPE_HASZ(old_type),
@@ -498,9 +478,9 @@
 	/* text */
 	text *wkt_input = PG_GETARG_TEXT_P(0);
 	PG_LWGEOM *ret;  /*with length */
-    SERIALIZED_LWGEOM *serialized_lwgeom;
-    LWGEOM *lwgeom;	
-    char *wkt;
+	SERIALIZED_LWGEOM *serialized_lwgeom;
+	LWGEOM *lwgeom;	
+	char *wkt;
 	int wkt_size ;
 
 	init_pg_func();
@@ -512,19 +492,15 @@
 	wkt[wkt_size] = 0; /* null term */
 
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"in parse_WKT_lwgeom with input: '%s'",wkt);
-#endif
+	POSTGIS_DEBUGF(3, "in parse_WKT_lwgeom with input: '%s'",wkt);
 
-    serialized_lwgeom = parse_lwg((const char *)wkt, (allocator)lwalloc, (report_error)elog_ERROR);
-    lwgeom = lwgeom_deserialize(serialized_lwgeom->lwgeom);
+	serialized_lwgeom = parse_lwg((const char *)wkt, (allocator)lwalloc, (report_error)elog_ERROR);
+	lwgeom = lwgeom_deserialize(serialized_lwgeom->lwgeom);
     
-    ret = pglwgeom_serialize(lwgeom);
+	ret = pglwgeom_serialize(lwgeom);
 	lwgeom_release(lwgeom);
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE,"parse_WKT_lwgeom:: finished parse");
-#endif
+	POSTGIS_DEBUG(3, "parse_WKT_lwgeom:: finished parse");
 
 	pfree (wkt);
 
@@ -555,38 +531,27 @@
         bytea *wkb;
 	PG_LWGEOM *result;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_recv start");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_recv start");
 
 	/* Add VARLENA size info to make it a valid varlena object */
 	wkb = (bytea *)palloc(buf->len+VARHDRSZ);
 	SET_VARSIZE(wkb, buf->len+VARHDRSZ);
 	memcpy(VARDATA(wkb), buf->data, buf->len);
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_recv calling LWGEOMFromWKB");
-#endif
+	POSTGIS_DEBUG(3, "LWGEOM_recv calling LWGEOMFromWKB");
 
 	/* Call LWGEOM_from_bytea function... */
 	result = (PG_LWGEOM *)DatumGetPointer(DirectFunctionCall1(
 		LWGEOMFromWKB, PointerGetDatum(wkb)));
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_recv advancing StringInfo buffer");
-#endif
+	POSTGIS_DEBUG(3, "LWGEOM_recv advancing StringInfo buffer");
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_from_bytea returned %s", unparse_WKB(SERIALIZED_FORM(result),pg_alloc,pg_free,-1,NULL,1));
-#endif
+	POSTGIS_DEBUGF(3, "LWGEOM_from_bytea returned %s", unparse_WKB(SERIALIZED_FORM(result),pg_alloc,pg_free,-1,NULL,1));
 
-
 	/* Set cursor to the end of buffer (so the backend is happy) */
 	buf->cursor = buf->len;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_recv returning");
-#endif
+	POSTGIS_DEBUG(3, "LWGEOM_recv returning");
 
         PG_RETURN_POINTER(result);
 }
@@ -596,9 +561,7 @@
 {
 	bytea *result;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_send called");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_send called");
 
 	result = (bytea *)DatumGetPointer(DirectFunctionCall1(
 		WKBFromLWGEOM, PG_GETARG_DATUM(0)));
@@ -614,9 +577,7 @@
 {
 	bytea *result;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_to_bytea called");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_to_bytea called");
 
 	result = (bytea *)DatumGetPointer(DirectFunctionCall1(
 		WKBFromLWGEOM, PG_GETARG_DATUM(0)));
@@ -629,9 +590,7 @@
 {
 	PG_LWGEOM *result;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "LWGEOM_from_bytea start");
-#endif
+	POSTGIS_DEBUG(2, "LWGEOM_from_bytea start");
 
 	result = (PG_LWGEOM *)DatumGetPointer(DirectFunctionCall1(
 		LWGEOMFromWKB, PG_GETARG_DATUM(0)));

Modified: trunk/lwgeom/lwgeom_ogc.c
===================================================================
--- trunk/lwgeom/lwgeom_ogc.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_ogc.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -28,7 +28,6 @@
 #include "lwgeom_pg.h"
 
 
-/*#define PGIS_DEBUG */
 
 #include "wktparse.h"
 
@@ -181,9 +180,7 @@
 	LWGEOM_INSPECTED *inspected = lwgeom_inspect(serialized);
 	int i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwgeom_numpoints_linestring_recursive called.");
-#endif
+        LWDEBUG(2, "lwgeom_numpoints_linestring_recursive called.");
 
 	for (i=0; i<inspected->ngeometries; i++)
 	{
@@ -194,9 +191,7 @@
 
                 geom = lwgeom_getgeom_inspected(inspected, i);
 
-#ifdef PGIS_DEBUG
-                lwnotice("numpoints_recursive: type=%d", lwgeom_getType(geom->type));
-#endif
+                LWDEBUGF(3, "numpoints_recursive: type=%d", lwgeom_getType(geom->type));
 
                 if(lwgeom_getType(geom->type) == LINETYPE)
                 {
@@ -206,7 +201,7 @@
 		subgeom = lwgeom_getsubgeometry_inspected(inspected, i);
 		if ( subgeom == NULL )
 		{
-	elog(ERROR, "What ? lwgeom_getsubgeometry_inspected returned NULL??");
+			elog(ERROR, "What ? lwgeom_getsubgeometry_inspected returned NULL??");
 		}
 
 		type = lwgeom_getType(subgeom[0]);
@@ -238,9 +233,7 @@
 	PG_LWGEOM *geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	int32 ret;
 
-#ifdef PGIS_DEBUG
-        lwnotice("LWGEOM_numpoints_linestring called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_numpoints_linestring called.");
 
 	ret = lwgeom_numpoints_linestring_recursive(SERIALIZED_FORM(geom));
 	if ( ret == -1 )
@@ -284,9 +277,7 @@
 	LWCOLLECTION *coll;
 	LWGEOM *subgeom;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_geometryn_collection called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_geometryn_collection called.");
 
 	/* elog(NOTICE, "GeometryN called"); */
 
@@ -349,11 +340,10 @@
 		uchar *subgeom;
 		char typeflags = lwgeom_getsubtype_inspected(inspected, i);
 		int type = lwgeom_getType(typeflags);
-#ifdef PGIS_DEBUG
-                lwnotice("lwgeom_dimension_recursive: type %d", type);
-#endif
 		int dims=-1;
 
+                LWDEBUGF(3, "lwgeom_dimension_recursive: type %d", type);
+
 		if ( type == POINTTYPE ) dims = 0;
 		else if ( type == MULTIPOINTTYPE ) dims=0;
 		else if ( type == LINETYPE ) dims=1;
@@ -398,10 +388,9 @@
 {
 	PG_LWGEOM *geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	int dimension;
-#ifdef PGIS_DEBUG_CALLS
-        elog(NOTICE, "LWGEOM_dimension called");
-#endif
 
+        POSTGIS_DEBUG(2, "LWGEOM_dimension called");
+
 	dimension = lwgeom_dimension_recursive(SERIALIZED_FORM(geom));
 	if ( dimension == -1 )
 	{
@@ -432,9 +421,7 @@
 	PG_LWGEOM *result;
 	BOX2DFLOAT4 *bbox=NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_exteriorring_polygon called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_exteriorring_polygon called.");
 
 	if ( TYPE_GETTYPE(geom->type) != POLYGONTYPE && 
                 TYPE_GETTYPE(geom->type) != CURVEPOLYTYPE)
@@ -492,9 +479,7 @@
 	int32 result;
 	int i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_numinteriorrings called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_numinteriorrings called.");
 
         if(lwgeom_getType((uchar)SERIALIZED_FORM(geom)[0]) == CURVEPOLYTYPE)
         {
@@ -516,10 +501,9 @@
 		pfree_inspected(inspected);
 		PG_RETURN_NULL();
 	}
-#ifdef PGIS_DEBUG
-        lwnotice("Geometry of type %d found.", lwgeom_getType(tmp->type));
-#endif
 
+        POSTGIS_DEBUGF(3, "Geometry of type %d found.", lwgeom_getType(tmp->type));
+
         if(lwgeom_getType(tmp->type) == POLYGONTYPE)
         {
                 poly = (LWPOLY *)tmp;
@@ -529,9 +513,7 @@
         }
         else if(lwgeom_getType(tmp->type) == CURVEPOLYTYPE)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("CurvePolygon found.");
-#endif
+                POSTGIS_DEBUG(3, "CurvePolygon found.");
                
                 curvepoly = (LWCURVEPOLY *)tmp;
                 result = curvepoly->nrings-1;
@@ -567,9 +549,7 @@
 	PG_LWGEOM *result;
 	BOX2DFLOAT4 *bbox = NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_interierringn_polygon called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_interierringn_polygon called.");
 
 	wanted_index = PG_GETARG_INT32(1);
 	if ( wanted_index < 1 )
@@ -870,9 +850,7 @@
 	PG_LWGEOM *result;
 	int i, type;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_startpoint_linestring called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_startpoint_linestring called.");
 
 	geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 
@@ -935,9 +913,7 @@
 	PG_LWGEOM *result;
 	int i, type;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_endpoint_linestring called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_endpoint_linestring called.");
 
 	geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
 	type = lwgeom_getType((uchar)SERIALIZED_FORM(geom)[0]);
@@ -995,18 +971,15 @@
 	text *wkttext = PG_GETARG_TEXT_P(0);
 	char *wkt, fc;
 	size_t size;
-    SERIALIZED_LWGEOM *serialized_lwgeom;
+	SERIALIZED_LWGEOM *serialized_lwgeom;
 	PG_LWGEOM *result = NULL;
 	LWGEOM *lwgeom;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_from_text");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_from_text");
+
 	size = VARSIZE(wkttext)-VARHDRSZ;
 
-#ifdef PGIS_DEBUG
-	lwnotice("size: %d", size); 
-#endif
+	POSTGIS_DEBUGF(3, "size: %d", (int)size); 
 
 	if ( size < 10 )
 	{
@@ -1032,12 +1005,10 @@
 	memcpy(wkt, VARDATA(wkttext), size);
 	wkt[size]='\0';
 
-#ifdef PGIS_DEBUG
-	lwnotice("wkt: [%s]", wkt);
-#endif
+	POSTGIS_DEBUGF(3, "wkt: [%s]", wkt);
 
-    serialized_lwgeom = parse_lwgeom_wkt(wkt);
-    lwgeom = lwgeom_deserialize(serialized_lwgeom->lwgeom);
+	serialized_lwgeom = parse_lwgeom_wkt(wkt);
+	lwgeom = lwgeom_deserialize(serialized_lwgeom->lwgeom);
 
 	if ( lwgeom->SRID != -1 || TYPE_GETZM(lwgeom->type) != 0 )
 	{
@@ -1097,17 +1068,14 @@
 PG_FUNCTION_INFO_V1(LWGEOM_asText);
 Datum LWGEOM_asText(PG_FUNCTION_ARGS)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_asText called.");
-#endif
-
 	PG_LWGEOM *lwgeom;
 	PG_LWGEOM *ogclwgeom;
 	char *result_cstring;
 	int len;
-    char *result,*loc_wkt;
+	char *result,*loc_wkt;
 	char *semicolonLoc;
+        
+	POSTGIS_DEBUG(2, "LWGEOM_asText called.");
 
 	init_pg_func();
 
@@ -1175,9 +1143,7 @@
 {
 	POINT3DZ sp, ep;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("line_is_closed called.");
-#endif
+        LWDEBUG(2, "line_is_closed called.");
 
 	getPoint3dz_p(line->points, 0, &sp);
 	getPoint3dz_p(line->points, line->points->npoints-1, &ep);
@@ -1196,9 +1162,7 @@
 {
         POINT3DZ sp, ep;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("curve_is_closed called.");
-#endif
+        LWDEBUG(2, "curve_is_closed called.");
 
         getPoint3dz_p(curve->points, 0, &sp);
         getPoint3dz_p(curve->points, curve->points->npoints-1, &ep);
@@ -1217,9 +1181,7 @@
         POINT3DZ sp, ep;
         LWGEOM *tmp;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("compound_is_closed called.");
-#endif
+        LWDEBUG(2, "compound_is_closed called.");
 
         tmp = compound->geoms[0];
         if(lwgeom_getType(tmp->type) == LINETYPE)
@@ -1266,9 +1228,7 @@
 	int linesfound=0;
 	int i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_isclosed_linestring called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_isclosed_linestring called.");
 
 	geom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
         if(lwgeom_getType((uchar)SERIALIZED_FORM(geom)[0]) == COMPOUNDTYPE) {

Modified: trunk/lwgeom/lwgeom_pg.c
===================================================================
--- trunk/lwgeom/lwgeom_pg.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_pg.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -11,7 +11,6 @@
 #include "wktparse.h"
 
 
-/* #undef PGIS_DEBUG */
 
 #define PARANOIA_LEVEL 1
 
@@ -27,16 +26,16 @@
 pg_alloc(size_t size)
 {
 	void * result;
-#ifdef PGIS_DEBUG_ALLOCS
-	lwnotice("  pg_alloc(%d) called", size);
-#endif
+
+	POSTGIS_DEBUGF(5, "  pg_alloc(%d) called", (int)size);
+
 	result = palloc(size);
-#ifdef PGIS_DEBUG_ALLOCS
-	lwnotice("  pg_alloc(%d) returning %p", size, result);
-#endif
+
+	POSTGIS_DEBUGF(5, "  pg_alloc(%d) returning %p", (int)size, result);
+
 	if ( ! result )
 	{
-		elog(ERROR, "Out of virtual memory");
+		ereport(ERROR, (errmsg_internal("Out of virtual memory")));
 		return NULL;
 	}
 	return result;
@@ -46,13 +45,13 @@
 pg_realloc(void *mem, size_t size)
 {
 	void * result;
-#ifdef PGIS_DEBUG_ALLOCS
-	lwnotice("  pg_realloc(%p, %d) called", mem, size);
-#endif
+
+	POSTGIS_DEBUGF(5, "  pg_realloc(%p, %d) called", mem, (int)size);
+
 	result = repalloc(mem, size);
-#ifdef PGIS_DEBUG_ALLOCS
-	lwnotice("  pg_realloc(%p, %d) returning %p", mem, size, result);
-#endif
+
+	POSTGIS_DEBUGF(5, "  pg_realloc(%p, %d) returning %p", mem, (int)size, result);
+
 	return result;
 }
 
@@ -75,7 +74,7 @@
 	va_end (ap);
 
 	errmsg[ERRMSG_MAXLEN]='\0';
-	elog(ERROR, "%s", errmsg);
+	ereport(ERROR, (errmsg_internal("%s", errmsg)));
 }
 
 void
@@ -95,7 +94,7 @@
 		va_end (ap);
 		return;
 	}
-	elog(NOTICE, "%s", msg);
+	ereport(NOTICE, (errmsg_internal("%s", msg)));
 	va_end(ap);
 	free(msg);
 }
@@ -125,22 +124,18 @@
 
 	size = lwgeom_serialize_size(in) + VARHDRSZ;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwgeom_serialize_size returned %d", size-VARHDRSZ);
-#endif
+	POSTGIS_DEBUGF(3, "lwgeom_serialize_size returned %d", (int)size-VARHDRSZ);
 
 	result = palloc(size);
-    SET_VARSIZE(result, size);
+	SET_VARSIZE(result, size);
 	lwgeom_serialize_buf(in, SERIALIZED_FORM(result), &size);
 
-#ifdef PGIS_DEBUG
-        lwnotice("pglwgeom_serialize: serialized size: %d, computed size: %d", size, VARSIZE(result)-VARHDRSZ);
-#endif
+        POSTGIS_DEBUGF(3, "pglwgeom_serialize: serialized size: %d, computed size: %d", (int)size, VARSIZE(result)-VARHDRSZ);
 
 #if PARANOIA_LEVEL > 0
 	if ( size != VARSIZE(result)-VARHDRSZ )
 	{
-		lwerror("pglwgeom_serialize: serialized size:%d, computed size:%d", size, VARSIZE(result)-VARHDRSZ);
+		lwerror("pglwgeom_serialize: serialized size:%d, computed size:%d", (int)size, VARSIZE(result)-VARHDRSZ);
 		return NULL;
 	}
 #endif
@@ -231,7 +226,7 @@
 	size+=4; /* size header */
 
 	result = lwalloc(size);
-    SET_VARSIZE(result, size);
+	SET_VARSIZE(result, size);
 
 	result->type = lwgeom_makeType_full(
 		TYPE_HASZ(ser[0]), TYPE_HASM(ser[0]),

Modified: trunk/lwgeom/lwgeom_pg.h
===================================================================
--- trunk/lwgeom/lwgeom_pg.h	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_pg.h	2008-05-31 09:56:44 UTC (rev 2797)
@@ -22,6 +22,37 @@
 void pg_error(const char *msg, ...);
 void pg_notice(const char *msg, ...);
 
+
+/* Debugging macros */
+#if POSTGIS_DEBUG_LEVEL > 0
+
+/* Display a simple message at NOTICE level */
+#define POSTGIS_DEBUG(level, msg) \
+        do { \
+                if (POSTGIS_DEBUG_LEVEL >= level) \
+                        ereport(NOTICE, (errmsg_internal("[%s:%s:%d] " msg, __FILE__, __func__, __LINE__))); \
+        } while (0);
+
+/* Display a formatted message at NOTICE level (like printf, with variadic arguments) */
+#define POSTGIS_DEBUGF(level, msg, ...) \
+        do { \
+                if (POSTGIS_DEBUG_LEVEL >= level) \
+                        ereport(NOTICE, (errmsg_internal("[%s:%s:%d] " msg, __FILE__, __func__, __LINE__, __VA_ARGS__))); \
+        } while (0);
+
+#else
+
+/* Empty prototype that can be optimised away by the compiler for non-debug builds */
+#define POSTGIS_DEBUG(level, msg) \
+        ((void) 0)
+
+/* Empty prototype that can be optimised away by the compiler for non-debug builds */
+#define POSTGIS_DEBUGF(level, msg, ...) \
+        ((void) 0)
+
+#endif
+
+
 /* Serialize/deserialize a PG_LWGEOM (postgis datatype) */
 extern PG_LWGEOM *pglwgeom_serialize(LWGEOM *lwgeom);
 extern LWGEOM *pglwgeom_deserialize(PG_LWGEOM *pglwgeom);

Modified: trunk/lwgeom/lwgeom_rtree.c
===================================================================
--- trunk/lwgeom/lwgeom_rtree.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_rtree.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -30,15 +30,11 @@
 	int i, nodeCount;
         int childNodes, parentNodes;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("createTree called with pointarray %p", pointArray);
-#endif
+        LWDEBUGF(2, "createTree called with pointarray %p", pointArray);
 
         nodeCount = pointArray->npoints - 1;
 
-#ifdef PGIS_DEBUG
-        lwnotice("Total leaf nodes: %d", nodeCount);
-#endif
+        LWDEBUGF(3, "Total leaf nodes: %d", nodeCount);
 
         /*
          * Create a leaf node for every line segment.
@@ -57,9 +53,8 @@
         parentNodes = nodeCount / 2;
         while(parentNodes > 0)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Merging %d children into %d parents.", childNodes, parentNodes);
-#endif
+                LWDEBUGF(3, "Merging %d children into %d parents.", childNodes, parentNodes);
+
                 i = 0;
                 while(i < parentNodes) 
                 {
@@ -71,9 +66,8 @@
                  */
                 if(parentNodes * 2 < childNodes)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("Shuffling child %d to parent %d", childNodes - 1, i);
-#endif
+                        LWDEBUGF(3, "Shuffling child %d to parent %d", childNodes - 1, i);
+
                         nodes[i] = nodes[childNodes - 1];
                         parentNodes++;
                 }
@@ -83,9 +77,8 @@
 
         root = nodes[0];
 
-#ifdef PGIS_DEBUG
-        lwnotice("createTree returning %p", root);
-#endif
+        LWDEBUGF(3, "createTree returning %p", root);
+
         return root;
 }
 
@@ -95,17 +88,16 @@
 RTREE_NODE *createInteriorNode(RTREE_NODE *left, RTREE_NODE *right){
         RTREE_NODE *parent;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("createInteriorNode called for children %p, %p", left, right);
-#endif
+        LWDEBUGF(2, "createInteriorNode called for children %p, %p", left, right);
+
         parent = lwalloc(sizeof(RTREE_NODE));
         parent->leftNode = left;
         parent->rightNode = right;
         parent->interval = mergeIntervals(left->interval, right->interval);
         parent->segment = NULL;
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("createInteriorNode returning %p", parent);
-#endif
+
+        LWDEBUGF(3, "createInteriorNode returning %p", parent);
+
         return parent;
 }
 
@@ -121,9 +113,8 @@
         POINT4D tmp;
         POINTARRAY *npa;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("createLeafNode called for point %d of %p", startPoint, pa);
-#endif
+        LWDEBUGF(2, "createLeafNode called for point %d of %p", startPoint, pa);
+
         if(pa->npoints < startPoint + 2)
         {
                 lwerror("createLeafNode: npoints = %d, startPoint = %d", pa->npoints, startPoint);
@@ -158,9 +149,8 @@
         parent->leftNode = NULL;
         parent->rightNode = NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("createLeafNode returning %p", parent);
-#endif
+        LWDEBUGF(3, "createLeafNode returning %p", parent);
+
         return parent;
 }
 
@@ -171,15 +161,14 @@
 {
         INTERVAL *interval;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("mergeIntervals called with %p, %p", inter1, inter2);
-#endif
+        LWDEBUGF(2, "mergeIntervals called with %p, %p", inter1, inter2);
+
         interval = lwalloc(sizeof(INTERVAL));
         interval->max = FP_MAX(inter1->max, inter2->max);
         interval->min = FP_MIN(inter1->min, inter2->min);
-#ifdef PGIS_DEBUG
-        lwnotice("interval min = %8.3f, max = %8.3f", interval->min, interval->max);
-#endif
+
+        LWDEBUGF(3, "interval min = %8.3f, max = %8.3f", interval->min, interval->max);
+
         return interval;
 }
 
@@ -190,15 +179,14 @@
 {
         INTERVAL *interval;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("createInterval called with %8.3f, %8.3f", value1, value2);
-#endif
+        LWDEBUGF(2, "createInterval called with %8.3f, %8.3f", value1, value2);
+
         interval = lwalloc(sizeof(INTERVAL));
         interval->max = FP_MAX(value1, value2);
         interval->min = FP_MIN(value1, value2);
-#ifdef PGIS_DEBUG
-        lwnotice("interval min = %8.3f, max = %8.3f", interval->min, interval->max);
-#endif
+
+        LWDEBUGF(3, "interval min = %8.3f, max = %8.3f", interval->min, interval->max);
+
         return interval;
 }
 
@@ -208,10 +196,8 @@
  */
 void freeTree(RTREE_NODE *root)
 {
+        LWDEBUGF(2, "freeTree called for %p", root);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("freeTree called for %p", root);
-#endif
         if(root->leftNode)
                 freeTree(root->leftNode);
         if(root->rightNode)
@@ -233,46 +219,40 @@
         LWMLINE *tmp, *result;
         LWGEOM **lwgeoms;
         
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("findLineSegments called for tree %p and value %8.3f", root, value);
-#endif
+        LWDEBUGF(2, "findLineSegments called for tree %p and value %8.3f", root, value);
+
         result = NULL;
 
         if(!isContained(root->interval, value))
         {
-#ifdef PGIS_DEBUG
-                lwnotice("findLineSegments %p: not contained.", root);
-#endif
+                LWDEBUGF(3, "findLineSegments %p: not contained.", root);
+
                 return NULL;
         }
 
         /* If there is a segment defined for this node, include it. */
         if(root->segment)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("findLineSegments %p: adding segment %p %d.", root, root->segment, TYPE_GETTYPE(root->segment->type));
-#endif
+                LWDEBUGF(3, "findLineSegments %p: adding segment %p %d.", root, root->segment, TYPE_GETTYPE(root->segment->type));
+
                 lwgeoms = lwalloc(sizeof(LWGEOM *));
                 lwgeoms[0] = (LWGEOM *)root->segment;
 
-#ifdef PGIS_DEBUG
-                lwnotice("Found geom %p, type %d, dim %d", root->segment, TYPE_GETTYPE(root->segment->type), TYPE_GETZM(root->segment->type));
-#endif
+                LWDEBUGF(3, "Found geom %p, type %d, dim %d", root->segment, TYPE_GETTYPE(root->segment->type), TYPE_GETZM(root->segment->type));
+
                 result = (LWMLINE *)lwcollection_construct(lwgeom_makeType_full(0, 0, 0, MULTILINETYPE, 0), -1, NULL, 1, lwgeoms);
         }
 
         /* If there is a left child node, recursively include its results. */
         if(root->leftNode)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("findLineSegments %p: recursing left.", root);
-#endif
+                LWDEBUGF(3, "findLineSegments %p: recursing left.", root);
+
                 tmp = findLineSegments(root->leftNode, value);
                 if(tmp)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("Found geom %p, type %d, dim %d", tmp, TYPE_GETTYPE(tmp->type), TYPE_GETZM(tmp->type));
-#endif
+                        LWDEBUGF(3, "Found geom %p, type %d, dim %d", tmp, TYPE_GETTYPE(tmp->type), TYPE_GETZM(tmp->type));
+
                         if(result)
                                 result = mergeMultiLines(result, tmp);
                         else
@@ -283,15 +263,13 @@
         /* Same for any right child. */
         if(root->rightNode)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("findLineSegments %p: recursing right.", root);
-#endif
+                LWDEBUGF(3, "findLineSegments %p: recursing right.", root);
+
                 tmp = findLineSegments(root->rightNode, value);
                 if(tmp)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("Found geom %p, type %d, dim %d", tmp, TYPE_GETTYPE(tmp->type), TYPE_GETZM(tmp->type));
-#endif
+                        LWDEBUGF(3, "Found geom %p, type %d, dim %d", tmp, TYPE_GETTYPE(tmp->type), TYPE_GETZM(tmp->type));
+
                         if(result)
                                 result = mergeMultiLines(result, tmp);
                         else
@@ -309,9 +287,8 @@
         LWCOLLECTION *col;
         int i, j, ngeoms;
         
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("mergeMultiLines called on %p, %d, %d; %p, %d, %d", line1, line1->ngeoms, TYPE_GETTYPE(line1->type), line2, line2->ngeoms, TYPE_GETTYPE(line2->type));
-#endif
+        LWDEBUGF(2, "mergeMultiLines called on %p, %d, %d; %p, %d, %d", line1, line1->ngeoms, TYPE_GETTYPE(line1->type), line2, line2->ngeoms, TYPE_GETTYPE(line2->type));
+
         ngeoms = line1->ngeoms + line2->ngeoms;
         geoms = lwalloc(sizeof(LWGEOM *) * ngeoms);
 
@@ -326,9 +303,7 @@
         }
         col = lwcollection_construct(MULTILINETYPE, -1, NULL, ngeoms, geoms);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("mergeMultiLines returning %p, %d, %d", col, col->ngeoms, TYPE_GETTYPE(col->type));
-#endif
+        LWDEBUGF(3, "mergeMultiLines returning %p, %d, %d", col, col->ngeoms, TYPE_GETTYPE(col->type));
 
         return (LWMLINE *)col;
 }
@@ -349,11 +324,12 @@
         LWMLINE *mline;
         RTREE_NODE *root;
         double yval;
-        
-#ifdef PGIS_DEBUG_CALLS
-        int i;
-        lwnotice("polygon_index called.");
-#endif
+#if POSTGIS_DEBUG_LEVEL > 0
+	int i = 0;
+#endif       
+ 
+        POSTGIS_DEBUG(2, "polygon_index called.");
+
         result = NULL;
         igeom = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
         yval = PG_GETARG_FLOAT8(1);
@@ -369,20 +345,19 @@
 
         mline = findLineSegments(root, yval);
 
-#ifdef PGIS_DEBUG
-        lwnotice("mline returned %p %d", mline, TYPE_GETTYPE(mline->type));
+#if POSTGIS_DEBUG_LEVEL >= 3
+        POSTGIS_DEBUGF(3, "mline returned %p %d", mline, TYPE_GETTYPE(mline->type));
         for(i = 0; i < mline->ngeoms; i++)
         {
-                lwnotice("geom[%d] %p %d", i, mline->geoms[i], TYPE_GETTYPE(mline->geoms[i]->type));
+                POSTGIS_DEBUGF(3, "geom[%d] %p %d", i, mline->geoms[i], TYPE_GETTYPE(mline->geoms[i]->type));
         }
 #endif
 
         if(mline)
                 result = pglwgeom_serialize((LWGEOM *)mline);
 
-#ifdef PGIS_DEBUG
-        lwnotice("returning result %p", result);
-#endif
+        POSTGIS_DEBUGF(3, "returning result %p", result);
+
 	lwfree(root);
 
 	PG_FREE_IF_COPY(igeom, 0);
@@ -397,9 +372,8 @@
         RTREE_POLY_CACHE *result;
         int i, length;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("createNewCache called with %p", poly);
-#endif
+        LWDEBUGF(2, "createNewCache called with %p", poly);
+
         result = lwalloc(sizeof(RTREE_POLY_CACHE));
         result->ringIndices = lwalloc(sizeof(RTREE_NODE *) * poly->nrings);
         result->ringCount = poly->nrings;
@@ -410,9 +384,9 @@
         {
                 result->ringIndices[i] = createTree(poly->rings[i]);
         }
-#ifdef PGIS_DEBUG
-        lwnotice("createNewCache returning %p", result);
-#endif
+
+        LWDEBUGF(3, "createNewCache returning %p", result);
+
         return result;
 }
 
@@ -428,21 +402,18 @@
 {
         int i, length;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("retrieveCache called with %p %p %p", poly, serializedPoly, currentCache);
-#endif
+        LWDEBUGF(2, "retrieveCache called with %p %p %p", poly, serializedPoly, currentCache);
+
         if(!currentCache)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("No existing cache, create one.");
-#endif
+                LWDEBUG(3, "No existing cache, create one.");
+
                 return createNewCache(poly, serializedPoly);
         }
         if(!(currentCache->poly))
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Cache contains no polygon, creating new cache.");
-#endif
+                LWDEBUG(3, "Cache contains no polygon, creating new cache.");
+
                 return createNewCache(poly, serializedPoly);
         }
 
@@ -450,9 +421,8 @@
 
         if(lwgeom_size_poly(currentCache->poly) != length)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Polygon size mismatch, creating new cache.");
-#endif
+                LWDEBUG(3, "Polygon size mismatch, creating new cache.");
+
                 lwfree(currentCache->poly);
                 lwfree(currentCache);
                 return createNewCache(poly, serializedPoly);
@@ -463,18 +433,16 @@
                 uchar b = currentCache->poly[i];
                 if(a != b) 
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("Polygon mismatch, creating new cache. %c, %c", a, b);
-#endif
+                        LWDEBUGF(3, "Polygon mismatch, creating new cache. %c, %c", a, b);
+
                         lwfree(currentCache->poly);
                         lwfree(currentCache);
                         return createNewCache(poly, serializedPoly);
                 }
         }
 
-#ifdef PGIS_DEBUG
-        lwnotice("Polygon match, retaining current cache, %p.", currentCache);
-#endif
+        LWDEBUGF(3, "Polygon match, retaining current cache, %p.", currentCache);
+
         return currentCache;
 }
 

Modified: trunk/lwgeom/lwgeom_spheroid.c
===================================================================
--- trunk/lwgeom/lwgeom_spheroid.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_spheroid.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -194,7 +194,10 @@
 distance_ellipse(double lat1, double long1,
 	double lat2, double long2, SPHEROID *sphere)
 {
-	double result;
+	double result = 0;
+#if POSTGIS_DEBUG_LEVEL > 0
+	double result2 = 0;
+#endif
 
 	if ( (lat1==lat2) && (long1 == long2) )
 	{
@@ -202,12 +205,13 @@
 	}
 
 	result = distance_ellipse_calculation(lat1,long1,lat2,long2,sphere);
-	/*result2 =  distance_sphere_method(lat1, long1,lat2,long2, sphere);*/
 
-#ifdef PGIS_DEBUG
-	/*elog(NOTICE, "delta = %lf, skae says: %.15lf,2 circle says: %.15lf",
+#if POSTGIS_DEBUG_LEVEL >= 4
+	result2 =  distance_sphere_method(lat1, long1,lat2,long2, sphere);
+
+	LWDEBUGF(4, "delta = %lf, skae says: %.15lf,2 circle says: %.15lf",
 		(result2-result),result,result2);
-	elog(NOTICE,"2 circle says: %.15lf",result2);*/
+	LWDEBUGF(4, "2 circle says: %.15lf",result2);
 #endif
 
 	if (result != result)  /* NaN check
@@ -313,9 +317,7 @@
 	double dist = 0.0;
 	int i;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_pointarray_length_ellipse called");
-#endif
+	LWDEBUG(2, "lwgeom_pointarray_length_ellipse called");
 
 	if ( pts->npoints < 2 ) return 0.0;
 
@@ -354,9 +356,7 @@
 	POINT2D frm;
 	POINT2D to;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "lwgeom_pointarray_length2d_ellipse called");
-#endif
+	LWDEBUG(2, "lwgeom_pointarray_length2d_ellipse called");
 
 	if ( pts->npoints < 2 ) return 0.0;
 	for (i=0; i<pts->npoints-1;i++)
@@ -389,9 +389,7 @@
 	double dist = 0.0;
 	int i;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "in LWGEOM_length2d_ellipsoid_linestring");
-#endif
+	POSTGIS_DEBUG(2, "in LWGEOM_length2d_ellipsoid_linestring");
 
 	for (i=0; i<inspected->ngeometries; i++)
 	{
@@ -399,10 +397,9 @@
 		if ( line == NULL ) continue;
 		dist += lwgeom_pointarray_length2d_ellipse(line->points,
 			sphere);
-#if PGIS_DEBUG > 1
- 	elog(NOTICE, " LWGEOM_length2d_ellipsoid_linestring found a line (%f)",
-		dist);
-#endif
+
+	 	POSTGIS_DEBUGF(3, " LWGEOM_length2d_ellipsoid_linestring found a line (%f)",
+			dist);
 	}
 
 	pfree_inspected(inspected);
@@ -430,9 +427,7 @@
 	double dist = 0.0;
 	int i;
 
-#ifdef PGIS_DEBUG
-	elog(NOTICE, "in LWGEOM_length_ellipsoid_linestring");
-#endif
+	POSTGIS_DEBUG(2, "in LWGEOM_length_ellipsoid_linestring");
 
 	for (i=0; i<inspected->ngeometries; i++)
 	{
@@ -440,10 +435,9 @@
 		if ( line == NULL ) continue;
 		dist += lwgeom_pointarray_length_ellipse(line->points,
 			sphere);
-#ifdef PGIS_DEBUG
-	elog(NOTICE, " LWGEOM_length_ellipsoid_linestring found a line (%f)",
-		dist);
-#endif
+
+		POSTGIS_DEBUGF(3, " LWGEOM_length_ellipsoid_linestring found a line (%f)",
+			dist);
 	}
 
 	pfree_inspected(inspected);

Modified: trunk/lwgeom/lwgeom_sqlmm.c
===================================================================
--- trunk/lwgeom/lwgeom_sqlmm.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_sqlmm.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -58,9 +58,7 @@
         LWCOLLECTION *col;
         int i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("has_arc called.");
-#endif
+        LWDEBUG(2, "has_arc called.");
 
         switch(lwgeom_getType(geom->type)) 
         {
@@ -98,9 +96,7 @@
         double cx, cy, cr;
         double temp, bc, cd, det;
         
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcircle_center called (%.16f, %.16f), (%.16f, %.16f), (%.16f, %.16f).", p1->x, p1->y, p2->x, p2->y, p3->x, p3->y);
-#endif
+        LWDEBUGF(2, "lwcircle_center called (%.16f, %.16f), (%.16f, %.16f), (%.16f, %.16f).", p1->x, p1->y, p2->x, p2->y, p3->x, p3->y);
 
         /* Closed circle */
         if(fabs(p1->x - p3->x) < EPSILON_SQLMM
@@ -142,18 +138,13 @@
 double
 interpolate_arc(double angle, double zm1, double a1, double zm2, double a2)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("interpolate_arc called.");
-#endif
-
         double frac = fabs((angle - a1) / (a2 - a1));
         double result = frac * (zm2 - zm1) + zm1;
 
-#ifdef PGIS_DEBUG
-        lwnotice("interpolate_arc: angle=%.16f, a1=%.16f, a2=%.16f, z1=%.16f, z2=%.16f, frac=%.16f, result=%.16f", angle, a1, a2, zm1, zm2, frac, result);
-#endif
+        LWDEBUG(2, "interpolate_arc called.");
 
+        LWDEBUGF(3, "interpolate_arc: angle=%.16f, a1=%.16f, a2=%.16f, z1=%.16f, z2=%.16f, frac=%.16f, result=%.16f", angle, a1, a2, zm1, zm2, frac, result);
+
         return result;
 }
 
@@ -177,14 +168,12 @@
                increment = 0.0;
         double a1, a2, a3, i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcircle_segmentize called. ");
-#endif
+        LWDEBUG(2, "lwcircle_segmentize called. ");
 
         radius = lwcircle_center(p1, p2, p3, &center);
-#ifdef PGIS_DEBUG
-        lwnotice("lwcircle_segmentize, (%.16f, %.16f) radius=%.16f", center->x, center->y, radius);
-#endif
+
+        LWDEBUGF(3, "lwcircle_segmentize, (%.16f, %.16f) radius=%.16f", center->x, center->y, radius);
+
         if(radius < 0)
         {
                 return NULL;
@@ -194,9 +183,7 @@
         a2 = atan2(p2->y - center->y, p2->x - center->x);
         a3 = atan2(p3->y - center->y, p3->x - center->x);
 
-#ifdef PGIS_DEBUG
-        lwnotice("a1 = %.16f, a2 = %.16f, a3 = %.16f", a1, a2, a3);
-#endif
+        LWDEBUGF(3, "a1 = %.16f, a2 = %.16f, a3 = %.16f", a1, a2, a3);
 
         if(fabs(p1->x - p3->x) < EPSILON_SQLMM
                         && fabs(p1->y - p3->y) < EPSILON_SQLMM)
@@ -236,9 +223,7 @@
         if(sweep < 0) increment *= -1.0;
         angle = a1;
 
-#ifdef PGIS_DEBUG
-        lwnotice("ptcount: %d, perQuad: %d, sweep: %.16f, increment: %.16f", ptcount, perQuad, sweep, increment);
-#endif
+        LWDEBUGF(3, "ptcount: %d, perQuad: %d, sweep: %.16f, increment: %.16f", ptcount, perQuad, sweep, increment);
 
         for(i = 0; i < ptcount - 1; i++)
         {
@@ -314,9 +299,7 @@
         POINT4D *p4 = lwalloc(sizeof(POINT4D));
 
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwcurve_segmentize called., dim = %d", icurve->points->dims);
-#endif
+        LWDEBUGF(2, "lwcurve_segmentize called., dim = %d", icurve->points->dims);
 
         ptarray = dynptarray_create(icurve->points->npoints, icurve->points->dims);
         if(!getPoint4d_p(icurve->points, 0, p4))
@@ -327,19 +310,14 @@
 
         for(i = 2; i < icurve->points->npoints; i+=2) 
         {
+                LWDEBUGF(3, "lwcurve_segmentize: arc ending at point %d", i);
 
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_segmentize: arc ending at point %d", i);
-#endif
-
                 getPoint4d_p(icurve->points, i - 2, p1);
                 getPoint4d_p(icurve->points, i - 1, p2);
                 getPoint4d_p(icurve->points, i, p3);
                 tmp = lwcircle_segmentize(p1, p2, p3, perQuad);
 
-#ifdef PGIS_DEBUG
-                lwnotice("lwcurve_segmentize: generated %d points", tmp->npoints);
-#endif
+                LWDEBUGF(3, "lwcurve_segmentize: generated %d points", tmp->npoints);
 
                 for(j = 0; j < tmp->npoints; j++)
                 {
@@ -368,9 +346,8 @@
         uint32 i, j;
         POINT4D *p = NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcompound_segmentize called.");
-#endif 
+        LWDEBUG(2, "lwcompound_segmentize called.");
+
         p = lwalloc(sizeof(POINT4D));
 
         ptarray = dynptarray_create(2, ((POINTARRAY *)icompound->geoms[0]->data)->dims);
@@ -418,9 +395,7 @@
         POINTARRAY **ptarray;
         int i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcurvepoly_segmentize called.");
-#endif
+        LWDEBUG(2, "lwcurvepoly_segmentize called.");
 
         ptarray = lwalloc(sizeof(POINTARRAY *)*curvepoly->nrings);
 
@@ -457,9 +432,7 @@
         LWGEOM **lines;
         int i;
         
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwmcurve_segmentize called, geoms=%d, dim=%d.", mcurve->ngeoms, TYPE_NDIMS(mcurve->type));
-#endif
+        LWDEBUGF(2, "lwmcurve_segmentize called, geoms=%d, dim=%d.", mcurve->ngeoms, TYPE_NDIMS(mcurve->type));
 
         lines = lwalloc(sizeof(LWGEOM *)*mcurve->ngeoms);
 
@@ -495,9 +468,7 @@
         POINTARRAY **ptarray;
         int i, j;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwmsurface_segmentize called.");
-#endif
+        LWDEBUG(2, "lwmsurface_segmentize called.");
 
         polys = lwalloc(sizeof(LWGEOM *)*msurface->ngeoms);
 
@@ -531,9 +502,7 @@
         LWGEOM **geoms;
         int i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwcollection_segmentize called.");
-#endif
+        LWDEBUG(2, "lwcollection_segmentize called.");
 
         if(has_arc((LWGEOM *)collection) == 0)
         {
@@ -602,28 +571,27 @@
         LWGEOM *result; 
         int currentType, i;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("append_segment called %p, %p, %d, %d", geom, pts, type, SRID);
-#endif
+        LWDEBUGF(2, "append_segment called %p, %p, %d, %d", geom, pts, type, SRID);
 
         if(geom == NULL)
         {
                 if(type == LINETYPE)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("append_segment: line to NULL");
-#endif
+                        LWDEBUG(3, "append_segment: line to NULL");
+
                         return (LWGEOM *)lwline_construct(SRID, NULL, pts);
                 }
                 else if(type == CURVETYPE)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("append_segment: curve to NULL %d", pts->npoints);
+#if POSTGIS_DEBUG_LEVEL >= 4
                         POINT4D tmp;
+                        
+			LWDEBUGF(4, "append_segment: curve to NULL %d", pts->npoints);
+ 
                         for(i=0; i<pts->npoints; i++)
                         {
                                 getPoint4d_p(pts, i, &tmp);
-                                lwnotice("new point: (%.16f,%.16f)",tmp.x,tmp.y);
+                                LWDEBUGF(4, "new point: (%.16f,%.16f)",tmp.x,tmp.y);
                         }
 #endif
                         return (LWGEOM *)lwcurve_construct(SRID, NULL, pts);
@@ -640,9 +608,9 @@
                 POINTARRAY *newPoints;
                 POINT4D pt;
                 LWLINE *line = (LWLINE *)geom;
-#ifdef PGIS_DEBUG
-                lwnotice("append_segment: line to line");
-#endif
+
+                LWDEBUG(3, "append_segment: line to line");
+
                 newPoints = ptarray_construct(TYPE_HASZ(pts->dims), TYPE_HASM(pts->dims), pts->npoints + line->points->npoints - 1);
                 for(i=0; i<line->points->npoints; i++)
                 {
@@ -663,27 +631,27 @@
                 POINTARRAY *newPoints;
                 POINT4D pt;
                 LWCURVE *curve = (LWCURVE *)geom;
-#ifdef PGIS_DEBUG
-                lwnotice("append_segment: curve to curve");
-#endif
+
+                LWDEBUG(3, "append_segment: curve to curve");
+
                 newPoints = ptarray_construct(TYPE_HASZ(pts->dims), TYPE_HASM(pts->dims), pts->npoints + curve->points->npoints - 1);
-#ifdef PGIS_DEBUG
-                lwnotice("New array length: %d", pts->npoints + curve->points->npoints - 1);
-#endif
+
+                LWDEBUGF(3, "New array length: %d", pts->npoints + curve->points->npoints - 1);
+
                 for(i=0; i<curve->points->npoints; i++)
                 {
                         getPoint4d_p(curve->points, i, &pt);
-#ifdef PGIS_DEBUG
-                        lwnotice("orig point %d: (%.16f,%.16f)", i, pt.x, pt.y);
-#endif
+
+                        LWDEBUGF(3, "orig point %d: (%.16f,%.16f)", i, pt.x, pt.y);
+
                         setPoint4d(newPoints, i, &pt);
                 }
                 for(i=1; i<pts->npoints;i++)
                 {
                         getPoint4d_p(pts, i, &pt);
-#ifdef PGIS_DEBUG
-                        lwnotice("new point %d: (%.16f,%.16f)", i + curve->points->npoints - 1, pt.x, pt.y);
-#endif
+
+                        LWDEBUGF(3, "new point %d: (%.16f,%.16f)", i + curve->points->npoints - 1, pt.x, pt.y);
+
                         setPoint4d(newPoints, i + curve->points->npoints - 1, &pt);
                 }
                 result = (LWGEOM *)lwcurve_construct(SRID, NULL, newPoints);
@@ -694,9 +662,9 @@
         {
                 LWLINE *line;
                 LWGEOM **geomArray;
-#ifdef PGIS_DEBUG
-                lwnotice("append_segment: line to curve");
-#endif
+
+                LWDEBUG(3, "append_segment: line to curve");
+
                 geomArray = lwalloc(sizeof(LWGEOM *)*2);
                 geomArray[0] = lwgeom_clone(geom);
                 
@@ -712,9 +680,9 @@
         {
                 LWCURVE *curve;
                 LWGEOM **geomArray;
-#ifdef PGIS_DEBUG
-                lwnotice("append_segment: curve to line");
-#endif
+
+                LWDEBUG(3, "append_segment: curve to line");
+
                 geomArray = lwalloc(sizeof(LWGEOM *)*2);
                 geomArray[0] = lwgeom_clone(geom);
 
@@ -742,16 +710,14 @@
                 }
                 if(type == LINETYPE)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("append_segment: line to compound");
-#endif
+                        LWDEBUG(3, "append_segment: line to compound");
+
                         newGeom = (LWGEOM *)lwline_construct(SRID, NULL, pts);
                 }
                 else if(type == CURVETYPE)
                 {
-#ifdef PGIS_DEBUG
-                        lwnotice("append_segment: curve to compound");
-#endif
+                        LWDEBUG(3, "append_segment: curve to compound");
+
                         newGeom = (LWGEOM *)lwcurve_construct(SRID, NULL, pts);
                 }
                 else
@@ -780,9 +746,7 @@
         POINTARRAY *pts;
         LWGEOM *geom = NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("pta_desegmentize called.");
-#endif
+        LWDEBUG(2, "pta_desegmentize called.");
 
         getPoint4d_p(points, 0, &a);
         getPoint4d_p(points, 1, &b);
@@ -800,16 +764,12 @@
         if((last_length - length) < EPSILON_SQLMM) 
         {
                 isline = -1;
-#ifdef PGIS_DEBUG
-                lwnotice("Starting as unknown.");
-#endif
+                LWDEBUG(3, "Starting as unknown.");
         }
         else 
         {
                 isline = 1;        
-#ifdef PGIS_DEBUG
-                lwnotice("Starting as line.");
-#endif
+                LWDEBUG(3, "Starting as line.");
         }
 
         commit = 0;
@@ -824,16 +784,14 @@
                 dxbc = c.x - b.x;
                 dybc = c.y - b.y;
 
-#ifdef PGIS_DEBUG
-                lwnotice("(dxab, dyab, dxbc, dybc) (%.16f, %.16f, %.16f, %.16f)", dxab, dyab, dxbc, dybc);
-#endif
+                LWDEBUGF(3, "(dxab, dyab, dxbc, dybc) (%.16f, %.16f, %.16f, %.16f)", dxab, dyab, dxbc, dybc);
 
                 theta = atan2(dyab, dxab);
                 theta = theta - atan2(dybc, dxbc);
                 length = sqrt(dxbc*dxbc+dybc*dybc);
-#ifdef PGIS_DEBUG
-                lwnotice("Last/current length and angle %.16f/%.16f, %.16f/%.16f", last_angle, theta, last_length, length);
-#endif
+
+                LWDEBUGF(3, "Last/current length and angle %.16f/%.16f, %.16f/%.16f", last_angle, theta, last_length, length);
+
                 /* Found a line segment */
                 if(fabs(length - last_length) > EPSILON_SQLMM || 
                         fabs(theta - last_angle) > EPSILON_SQLMM)
@@ -847,9 +805,8 @@
                         /* We were tracking a curve, commit it and start line*/
                         else if(isline == 0)
                         {
-#ifdef PGIS_DEBUG
-                                lwnotice("Building curve, %d - %d", commit, i);
-#endif
+                                LWDEBUGF(3, "Building curve, %d - %d", commit, i);
+
                                 count = i - commit;
                                 pts = ptarray_construct(
                                         TYPE_HASZ(type),
@@ -889,16 +846,12 @@
         if((last_length - length) < EPSILON_SQLMM) 
         {
                 isline = -1;
-#ifdef PGIS_DEBUG
-                lwnotice("Restarting as unknown.");
-#endif
+                LWDEBUG(3, "Restarting as unknown.");
         }
         else 
         {
                 isline = 1;        
-#ifdef PGIS_DEBUG
-                lwnotice("Restarting as line.");
-#endif
+                LWDEBUG(3, "Restarting as line.");
         }
 
 
@@ -906,9 +859,7 @@
                         /* We didn't know what we were tracking, now we do. */
                         else
                         {
-#ifdef PGIS_DEBUG
-                                lwnotice("It's a line");
-#endif
+                                LWDEBUG(3, "It's a line");
                                 isline = 1;
                         }
                 }
@@ -918,9 +869,8 @@
                         /* We were tracking a curve, commit it and start line */
                         if(isline > 0)
                         {
-#ifdef PGIS_DEBUG
-                                lwnotice("Building line, %d - %d", commit, i-2);
-#endif
+                                LWDEBUGF(3, "Building line, %d - %d", commit, i-2);
+
                                 count = i - commit - 2;
 
                                 pts = ptarray_construct(
@@ -945,9 +895,7 @@
                         /* We didn't know what we were tracking, now we do */
                         else
                         {
-#ifdef PGIS_DEBUG
-                                lwnotice("It's a curve");
-#endif                          
+                                LWDEBUG(3, "It's a curve");
                                 isline = 0;
                         }
                 }
@@ -955,9 +903,8 @@
         count = i - commit;
         if(isline == 0 && count > 2)
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Finishing curve %d,%d.", commit, i);
-#endif
+                LWDEBUGF(3, "Finishing curve %d,%d.", commit, i);
+
                 pts = ptarray_construct(
                         TYPE_HASZ(type),
                         TYPE_HASM(type),
@@ -973,9 +920,8 @@
         }
         else 
         {
-#ifdef PGIS_DEBUG
-                lwnotice("Finishing line %d,%d.", commit, i);
-#endif
+                LWDEBUGF(3, "Finishing line %d,%d.", commit, i);
+
                 pts = ptarray_construct(
                         TYPE_HASZ(type),
                         TYPE_HASM(type),
@@ -993,9 +939,7 @@
 LWGEOM *
 lwline_desegmentize(LWLINE *line)
 {
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwline_desegmentize called.");
-#endif 
+        LWDEBUG(2, "lwline_desegmentize called.");
 
         return pta_desegmentize(line->points, line->type, line->SRID);
 }
@@ -1006,9 +950,7 @@
         LWGEOM **geoms;
         int i, hascurve = 0;
         
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwpolygon_desegmentize called.");
-#endif
+        LWDEBUG(2, "lwpolygon_desegmentize called.");
 
         geoms = lwalloc(sizeof(LWGEOM *)*poly->nrings);
         for(i=0; i<poly->nrings; i++)
@@ -1038,9 +980,7 @@
         LWGEOM **geoms;
         int i, hascurve = 0;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwmline_desegmentize called.");
-#endif
+        LWDEBUG(2, "lwmline_desegmentize called.");
 
         geoms = lwalloc(sizeof(LWGEOM *)*mline->ngeoms);
         for(i=0; i<mline->ngeoms; i++)
@@ -1069,9 +1009,7 @@
         LWGEOM **geoms;
         int i, hascurve = 0;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwmpoly_desegmentize called.");
-#endif
+        LWDEBUG(2, "lwmpoly_desegmentize called.");
 
         geoms = lwalloc(sizeof(LWGEOM *)*mpoly->ngeoms);
         for(i=0; i<mpoly->ngeoms; i++)
@@ -1098,9 +1036,7 @@
 {
         int type = lwgeom_getType(geom->type);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwgeom_desegmentize called.");
-#endif
+        LWDEBUG(2, "lwgeom_desegmentize called.");
 
         switch(type) {
         case LINETYPE:
@@ -1142,19 +1078,17 @@
         PG_LWGEOM *ret;
         LWGEOM *igeom = NULL, *ogeom = NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_curve_segmentize called.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_curve_segmentize called.");
 
         if(perQuad < 0) 
         {
                 elog(ERROR, "2nd argument must be positive.");
                 PG_RETURN_NULL();
         }
-#ifdef PGIS_DEBUG
+#if POSTGIS_DEBUG_LEVEL > 0
         else
         {
-                lwnotice("perQuad = %d", perQuad);
+                POSTGIS_DEBUGF(3, "perQuad = %d", perQuad);
         }
 #endif
         igeom = lwgeom_deserialize(SERIALIZED_FORM(geom));
@@ -1174,9 +1108,7 @@
         PG_LWGEOM *ret;
         LWGEOM *igeom = NULL, *ogeom = NULL;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("LWGEOM_line_desegmentize.");
-#endif
+        POSTGIS_DEBUG(2, "LWGEOM_line_desegmentize.");
 
         igeom = lwgeom_deserialize(SERIALIZED_FORM(geom));
         ogeom = lwgeom_desegmentize(igeom);

Modified: trunk/lwgeom/lwgeom_transform.c
===================================================================
--- trunk/lwgeom/lwgeom_transform.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgeom_transform.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -70,8 +70,6 @@
 static int lwgeom_transform_recursive(uchar *geom, PJ *inpj, PJ *outpj);
 
 
-/* PROJ4 SRS Cache debugging (uncomment to debug) */
-/* #define PROJ4_CACHE_DEBUG 1 */
 
 /* PROJ 4 lookup transaction cache methods */
 #define PROJ4_CACHE_ITEMS	8
@@ -229,9 +227,7 @@
 	if (!projection)
 		elog(ERROR, "PROJ4SRSCacheDelete: Trying to delete non-existant projection object with MemoryContext key (%p)", (void *)context);
 
-#if PROJ4_CACHE_DEBUG
-	elog(NOTICE, "PROJ4SRSCacheDelete: deleting projection object (%p) with MemoryContext key (%p)", projection, context);
-#endif
+	LWDEBUGF(3, "deleting projection object (%p) with MemoryContext key (%p)", projection, context);
 
 	/* Free it */
 	pj_free(projection);	
@@ -482,9 +478,8 @@
 			{
 				if (PROJ4Cache->PROJ4SRSCache[i].srid != other_srid && found == false)
 				{
-#if PROJ4_CACHE_DEBUG
-					elog(NOTICE, "AddToPROJ4SRSCache: choosing to remove item from query cache with SRID %d and index %d", PROJ4Cache->PROJ4SRSCache[i].srid, i);
-#endif
+					LWDEBUGF(3, "choosing to remove item from query cache with SRID %d and index %d", PROJ4Cache->PROJ4SRSCache[i].srid, i);
+		
 					DeleteFromPROJ4SRSCache(PROJ4Cache, PROJ4Cache->PROJ4SRSCache[i].srid);
 					PROJ4Cache->PROJ4SRSCacheCount = i;
 
@@ -497,9 +492,8 @@
 		 * Now create a memory context for this projection and
 		 * store it in the backend hash
 		 */
-#if PROJ4_CACHE_DEBUG
-		elog(NOTICE, "AddToPROJ4SRSCache: adding SRID %d with proj4text \"%s\" to query cache at index %d", srid, proj_str, PROJ4Cache->PROJ4SRSCacheCount);
-#endif
+		LWDEBUGF(3, "adding SRID %d with proj4text \"%s\" to query cache at index %d", srid, proj_str, PROJ4Cache->PROJ4SRSCacheCount);
+
 		PJMemoryContext = MemoryContextCreate(T_AllocSetContext, 8192,
 					&PROJ4SRSCacheContextMethods,
 					PROJ4Cache->PROJ4SRSCacheContext,
@@ -513,9 +507,8 @@
 		 * Add the MemoryContext to the backend hash so we can
 		 * clean up upon portal shutdown
 		 */
-#if PROJ4_CACHE_DEBUG
-		elog(NOTICE, "AddToPROJ4SRSCache: adding projection object (%p) to hash table with MemoryContext key (%p)", projection, PJMemoryContext);
-#endif
+		LWDEBUGF(3, "adding projection object (%p) to hash table with MemoryContext key (%p)", projection, PJMemoryContext);
+
 		AddPJHashEntry(PJMemoryContext, projection);
 		
 		PROJ4Cache->PROJ4SRSCache[PROJ4Cache->PROJ4SRSCacheCount].srid = srid;
@@ -553,9 +546,8 @@
 	{
 		if (PROJ4Cache->PROJ4SRSCache[i].srid == srid)
 		{
-#if PROJ4_CACHE_DEBUG
-			elog(NOTICE, "DeleteFromPROJ4SRSCache: removing query cache entry with SRID %d at index %d", srid, i);
-#endif
+			LWDEBUGF(3, "removing query cache entry with SRID %d at index %d", srid, i);
+
 			/*
 			 * Zero out the entries and free the PROJ4 handle
 			 * by deleting the memory context
@@ -885,9 +877,7 @@
 		{
 			int i;
 
-#if PROJ4_CACHE_DEBUG
-			elog(NOTICE, "Allocating PROJ4Cache for portal with transform() MemoryContext %p", fcinfo->flinfo->fn_mcxt);
-#endif
+			POSTGIS_DEBUGF(3, "Allocating PROJ4Cache for portal with transform() MemoryContext %p", fcinfo->flinfo->fn_mcxt);
 			/* Put in any required defaults */
 			for (i = 0; i < PROJ4_CACHE_ITEMS; i++)
 			{

Modified: trunk/lwgeom/lwgparse.c
===================================================================
--- trunk/lwgeom/lwgparse.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwgparse.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -247,14 +247,11 @@
 void
 alloc_stack_tuple(int type,output_func of,size_t size)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_stack_tuple %d, %d", type, size);
-#endif
-
 	tuple*	p;
 	inc_num();
 
+        LWDEBUGF(2, "alloc_stack_tuple %d, %d", type, size);
+	
 	p = alloc_tuple(of,size);
 	p->uu.nn.stack_next = the_geom.stack;
 	p->uu.nn.type = type;
@@ -294,19 +291,14 @@
 void
 check_dims(int num)
 {
+        LWDEBUGF(2, "check_dims the_geom.ndims = %d, num = %d", the_geom.ndims, num);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("check_dims the_geom.ndims = %d, num = %d", the_geom.ndims, num);
-#endif
-
 	if( the_geom.ndims != num){
 		if (the_geom.ndims) {
 			error("Can not mix dimensionality in a geometry");
 		} else {
 
-#ifdef PGIS_DEBUG
-                        lwnotice("check_dims: setting dim %d", num);
-#endif
+                        LWDEBUGF(3, "check_dims: setting dim %d", num);
 
 			the_geom.ndims = num;
 			if ( num > 2 ) the_geom.hasZ = 1;
@@ -381,11 +373,8 @@
 void
 alloc_lwgeom(int srid)
 {
+        LWDEBUGF(2, "alloc_lwgeom %d", srid);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_lwgeom %d", srid);
-#endif
-
 	the_geom.srid=srid;
 	the_geom.alloc_size=0;
 	the_geom.stack=NULL;
@@ -446,15 +435,12 @@
 void
 alloc_point_2d(double x,double y)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_point_2d %f,%f", x, y);
-#endif
-
 	tuple* p = alloc_tuple(write_point_2,the_geom.lwgi?8:16);
 	p->uu.points[0] = x;
 	p->uu.points[1] = y;
 
+        LWDEBUGF(2, "alloc_point_2d %f,%f", x, y);
+	
 	/* keep track of point */
 	if ( checkclosed ) {
 		if ( ! the_geom.stack->uu.nn.num )
@@ -469,16 +455,13 @@
 void
 alloc_point_3d(double x,double y,double z)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_point_3d %f, %f, %f", x, y, z);
-#endif
-
 	tuple* p = alloc_tuple(write_point_3,the_geom.lwgi?12:24);
 	p->uu.points[0] = x;
 	p->uu.points[1] = y;
 	p->uu.points[2] = z;
 
+        LWDEBUGF(2, "alloc_point_3d %f, %f, %f", x, y, z);
+	
 	/* keep track of point */
 	if ( checkclosed ) {
 		if ( ! the_geom.stack->uu.nn.num )
@@ -493,17 +476,14 @@
 void
 alloc_point_4d(double x,double y,double z,double m)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_point_4d %f, %f, %f, %f", x, y, z, m);
-#endif
-
 	tuple* p = alloc_tuple(write_point_4,the_geom.lwgi?16:32);
 	p->uu.points[0] = x;
 	p->uu.points[1] = y;
 	p->uu.points[2] = z;
 	p->uu.points[3] = m;
 
+        LWDEBUGF(2, "alloc_point_4d %f, %f, %f, %f", x, y, z, m);
+
 	/* keep track of point */
 	if ( checkclosed ) {
 		if ( ! the_geom.stack->uu.nn.num )
@@ -562,11 +542,8 @@
 void
 alloc_point(void)
 {
+        LWDEBUG(2, "alloc_point");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_point");
-#endif
-
 	if( the_geom.lwgi)
 		alloc_stack_tuple(POINTTYPEI,write_type,1);
 	else
@@ -580,11 +557,8 @@
 void
 alloc_linestring(void)
 {
+        LWDEBUG(2, "alloc_linestring");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_linestring");
-#endif
-
 	if( the_geom.lwgi)
 		alloc_stack_tuple(LINETYPEI,write_type,1);
 	else
@@ -597,11 +571,8 @@
 
 void alloc_linestring_closed(void)
 {
+        LWDEBUG(2, "alloc_linestring_closed called.");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_linestring_closed called.");
-#endif
-
         alloc_linestring();
         checkclosed=1;
 }
@@ -609,11 +580,8 @@
 void
 alloc_circularstring(void)
 {
+        LWDEBUG(2, "alloc_circularstring");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_circularstring");
-#endif
-
         alloc_stack_tuple(CURVETYPE,write_type,1);
         minpoints=3;
         checkclosed=0;
@@ -622,10 +590,7 @@
 
 void alloc_circularstring_closed(void)
 {
-      
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_circularstring_closed");
-#endif
+        LWDEBUG(2, "alloc_circularstring_closed");
 
         alloc_circularstring();
         checkclosed=1;
@@ -634,11 +599,8 @@
 void
 alloc_polygon(void)
 {
+        LWDEBUG(2, "alloc_polygon");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_polygon");
-#endif
-
 	if( the_geom.lwgi)
 		alloc_stack_tuple(POLYGONTYPEI, write_type,1);
 	else
@@ -653,11 +615,8 @@
 void
 alloc_curvepolygon(void)
 {
+        LWDEBUG(2, "alloc_curvepolygon called.");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_curvepolygon called.");
-#endif
-
         alloc_stack_tuple(CURVEPOLYTYPE, write_type, 1);
         minpoints=3;
         checkclosed=1;
@@ -667,43 +626,31 @@
 void
 alloc_compoundcurve(void)
 {
+        LWDEBUG(2, "alloc_compoundcurve called.");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_compoundcurve called.");
-#endif
-
         alloc_stack_tuple(COMPOUNDTYPE, write_type, 1);
 }
 
 void
 alloc_multipoint(void)
 {
+        LWDEBUG(2, "alloc_multipoint");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_multipoint");
-#endif 
-
 	alloc_stack_tuple(MULTIPOINTTYPE,write_type,1);
 }
 
 void
 alloc_multilinestring(void)
 {
+        LWDEBUG(2, "alloc_multilinestring");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_multilinestring");
-#endif
-
 	alloc_stack_tuple(MULTILINETYPE,write_type,1);
 }
 
 void
 alloc_multicurve(void)
 {
-       
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_multicurve");
-#endif
+        LWDEBUG(2, "alloc_multicurve");
 
         alloc_stack_tuple(MULTICURVETYPE,write_type,1);
 }
@@ -711,56 +658,42 @@
 void
 alloc_multipolygon(void)
 {
+        LWDEBUG(2, "alloc_multipolygon");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_multipolygon");
-#endif
-
 	alloc_stack_tuple(MULTIPOLYGONTYPE,write_type,1);
 }
 
 void
 alloc_multisurface(void)
 {
+        LWDEBUG(2, "alloc_multisurface called");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_multisurface called");
-#endif
-
         alloc_stack_tuple(MULTISURFACETYPE,write_type,1);
 }
 
 void
 alloc_geomertycollection(void)
 {
+        LWDEBUG(2, "alloc_geometrycollection");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_geometrycollection");
-#endif
-
 	alloc_stack_tuple(COLLECTIONTYPE,write_type,1);
 }
 
 void
 alloc_counter(void)
 {
+        LWDEBUG(2, "alloc_counter");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_counter");
-#endif
-
 	alloc_stack_tuple(0,write_count,4);
 }
 
 void
 alloc_empty(void)
 {
+	tuple* st = the_geom.stack;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_empty");
-#endif
+	LWDEBUG(2, "alloc_empty");
 
-	tuple* st = the_geom.stack;
 	/* Find the last geometry */
 	while(st->uu.nn.type == 0){
 		st =st->uu.nn.stack_next;
@@ -788,20 +721,17 @@
 SERIALIZED_LWGEOM *
 make_serialized_lwgeom(void)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("make_serialized_lwgeom");
-#endif
-
-    SERIALIZED_LWGEOM *out_serialized_lwgeom;
+	SERIALIZED_LWGEOM *out_serialized_lwgeom;
 	uchar* out_c;
 	output_state out;
 	tuple* cur;
+	
+	LWDEBUG(2, "make_serialized_lwgeom");
 
-    /* Allocate the SERIALIZED_LWGEOM structure */
-    out_serialized_lwgeom = (SERIALIZED_LWGEOM *)local_malloc(sizeof(SERIALIZED_LWGEOM));
+	/* Allocate the SERIALIZED_LWGEOM structure */
+	out_serialized_lwgeom = (SERIALIZED_LWGEOM *)local_malloc(sizeof(SERIALIZED_LWGEOM));
 
-    /* Allocate the LWGEOM itself */
+	/* Allocate the LWGEOM itself */
 	out_c = (uchar*)local_malloc(the_geom.alloc_size);
 	out.pos = out_c;
 	cur = the_geom.first ;
@@ -812,8 +742,8 @@
 	}
 
 	/* Setup the SERIALIZED_LWGEOM structure */
-    out_serialized_lwgeom->lwgeom = out_c;
-    out_serialized_lwgeom->size = the_geom.alloc_size;
+	out_serialized_lwgeom->lwgeom = out_c;
+	out_serialized_lwgeom->size = the_geom.alloc_size;
 
 	return out_serialized_lwgeom;
 }
@@ -1044,15 +974,12 @@
 void
 parse_wkb(const char **b)
 {
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("parse_wkb");
-#endif
-
 	int4 type;
 	uchar xdr = read_wkb_byte(b);
 	int4 localsrid;
 
+        LWDEBUG(2, "parse_wkb");
+
 	swap_order=0;
 
 	if ( xdr != getMachineEndian() )
@@ -1170,11 +1097,8 @@
 void
 alloc_wkb(const char *parser)
 {
+        LWDEBUG(2, "alloc_wkb");
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("alloc_wkb");
-#endif
-
 	parse_wkb(&parser);
 }
 
@@ -1184,11 +1108,8 @@
 SERIALIZED_LWGEOM *
 parse_it(const char *geometry, allocator allocfunc, report_error errfunc)
 {
+        LWDEBUGF(2, "parse_it: %s", geometry);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("parse_it: %s", geometry);
-#endif
-
 	local_malloc = allocfunc;
 	error_func=errfunc;
 
@@ -1223,11 +1144,8 @@
 void
 set_zm(char z, char m)
 {
+        LWDEBUGF(2, "set_zm %d, %d", z, m);
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("set_zm %d, %d", z, m);
-#endif
-
 	the_geom.hasZ = z;
 	the_geom.hasM = m;
 	the_geom.ndims = 2+z+m;

Modified: trunk/lwgeom/lwline.c
===================================================================
--- trunk/lwgeom/lwline.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwline.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -17,8 +17,6 @@
 #include <string.h>
 #include "liblwgeom.h"
 
-/*#define PGIS_DEBUG_CALLS 1 */
-/*#define PGIS_DEBUG 1 */
 
 
 /*
@@ -31,9 +29,7 @@
 	LWLINE *result;
 	result = (LWLINE*) lwalloc(sizeof(LWLINE));
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwline_construct called.");
-#endif
+        LWDEBUG(2, "lwline_construct called.");
 
 	result->type = lwgeom_makeType_full(
 		TYPE_HASZ(points->dims),
@@ -41,9 +37,7 @@
 		(SRID!=-1), LINETYPE,
 		0);
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwline_construct type=%d", result->type);
-#endif
+        LWDEBUGF(3, "lwline_construct type=%d", result->type);
 
 	result->SRID = SRID;
 	result->points = points;
@@ -82,9 +76,8 @@
 
 	if (lwgeom_hasBBOX(type))
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwline_deserialize: input has bbox");
-#endif
+		LWDEBUG(3, "lwline_deserialize: input has bbox");
+
 		result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
 		memcpy(result->bbox, loc, sizeof(BOX2DFLOAT4));
 		loc += sizeof(BOX2DFLOAT4);
@@ -156,10 +149,8 @@
 	int ptsize;
 	size_t size;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwline_serialize_buf(%p, %p, %p) called",
+	LWDEBUGF(2, "lwline_serialize_buf(%p, %p, %p) called",
 		line, buf, retsize);
-#endif
 
 	if (line == NULL)
 		lwerror("lwline_serialize:: given null line");
@@ -176,55 +167,44 @@
 		hasSRID, LINETYPE, line->bbox ? 1 : 0);
 	loc = buf+1;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwline_serialize_buf added type (%d)", line->type);
-#endif
+	LWDEBUGF(3, "lwline_serialize_buf added type (%d)", line->type);
 
 	if (line->bbox)
 	{
 		memcpy(loc, line->bbox, sizeof(BOX2DFLOAT4));
 		loc += sizeof(BOX2DFLOAT4);
-#ifdef PGIS_DEBUG
-		lwnotice("lwline_serialize_buf added BBOX");
-#endif
+
+		LWDEBUG(3, "lwline_serialize_buf added BBOX");
 	}
 
 	if (hasSRID)
 	{
 		memcpy(loc, &line->SRID, sizeof(int32));
 		loc += sizeof(int32);
-#ifdef PGIS_DEBUG
-		lwnotice("lwline_serialize_buf added SRID");
-#endif
+
+		LWDEBUG(3, "lwline_serialize_buf added SRID");
 	}
 
 	memcpy(loc, &line->points->npoints, sizeof(uint32));
 	loc += sizeof(uint32);
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwline_serialize_buf added npoints (%d)",
+	LWDEBUGF(3, "lwline_serialize_buf added npoints (%d)",
 		line->points->npoints);
-#endif
 
 	/*copy in points */
 	size = line->points->npoints*ptsize;
 	memcpy(loc, getPoint_internal(line->points, 0), size);
 	loc += size;
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwline_serialize_buf copied serialized_pointlist (%d bytes)",
+	LWDEBUGF(3, "lwline_serialize_buf copied serialized_pointlist (%d bytes)",
 		ptsize * line->points->npoints);
-#endif
 
 	if (retsize) *retsize = loc-buf;
 
 	/*printBYTES((uchar *)result, loc-buf); */
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwline_serialize_buf returning (loc: %p, size: %d)",
+	LWDEBUGF(3, "lwline_serialize_buf returning (loc: %p, size: %d)",
 		loc, loc-buf);
-#endif
-
 }
 
 /*
@@ -248,9 +228,7 @@
 {
 	size_t size = 1;  /* type */
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwline_serialize_size called");
-#endif
+	LWDEBUG(2, "lwline_serialize_size called");
 
 	if ( line->SRID != -1 ) size += 4; /* SRID */
 	if ( line->bbox ) size += sizeof(BOX2DFLOAT4);
@@ -258,9 +236,7 @@
 	size += 4; /* npoints */
 	size += pointArray_ptsize(line->points)*line->points->npoints;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwline_serialize_size returning %d", size);
-#endif
+	LWDEBUGF(3, "lwline_serialize_size returning %d", size);
 
 	return size;
 }
@@ -280,9 +256,7 @@
 	const uchar *loc;
 	uint32 npoints;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwgeom_size_line called");
-#endif
+	LWDEBUG(2, "lwgeom_size_line called");
 
 	if ( lwgeom_getType(type) != LINETYPE)
 		lwerror("lwgeom_size_line::attempt to find the length of a non-line");
@@ -308,9 +282,7 @@
 
 	result += TYPE_NDIMS(type) * sizeof(double) * npoints;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwgeom_size_line returning %d", result);
-#endif
+	LWDEBUGF(3, "lwgeom_size_line returning %d", result);
 
 	return result;
 }
@@ -334,10 +306,10 @@
 LWLINE *
 lwline_clone(const LWLINE *g)
 {
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwline_clone called with %p", g);
-#endif
 	LWLINE *ret = lwalloc(sizeof(LWLINE));
+       
+	LWDEBUGF(2, "lwline_clone called with %p", g);
+
 	memcpy(ret, g, sizeof(LWLINE));
 	if ( g->bbox ) ret->bbox = box2d_clone(g->bbox);
 	return ret;
@@ -501,9 +473,7 @@
 	pa = pointArray_construct(newpoints, zmflag&2, zmflag&1,
 		mpoint->ngeoms);
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwline_from_lwmpoint: constructed pointarray for %d points, %d zmflag", mpoint->ngeoms, zmflag);
-#endif
+	LWDEBUGF(3, "lwline_from_lwmpoint: constructed pointarray for %d points, %d zmflag", mpoint->ngeoms, zmflag);
 
 	return lwline_construct(SRID, NULL, pa);
 }

Modified: trunk/lwgeom/lwmpoly.c
===================================================================
--- trunk/lwgeom/lwmpoly.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwmpoly.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -15,7 +15,6 @@
 #include <string.h>
 #include "liblwgeom.h"
 
-/*#define PGIS_DEBUG_CALLS 1 */
 
 LWMPOLY *
 lwmpoly_deserialize(uchar *srl)
@@ -25,9 +24,7 @@
 	int type = lwgeom_getType(srl[0]);
 	int i;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwmpoly_deserialize called");
-#endif
+	LWDEBUG(2, "lwmpoly_deserialize called");
 
 	if ( type != MULTIPOLYGONTYPE ) 
 	{

Modified: trunk/lwgeom/lwmsurface.c
===================================================================
--- trunk/lwgeom/lwmsurface.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwmsurface.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -1,132 +1,129 @@
-/**********************************************************************
- * $Id$
- *
- * PostGIS - Spatial Types for PostgreSQL
- * http://postgis.refractions.net
- * Copyright 2001-2006 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.
- * 
- **********************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "liblwgeom.h"
-
-/*#define PGIS_DEBUG_CALLS 1 */
-
-LWMSURFACE *
-lwmsurface_deserialize(uchar *srl)
-{
-        LWMSURFACE *result;
-        LWGEOM_INSPECTED *insp;
-        int stype;
-        int type = lwgeom_getType(srl[0]);
-        int i;
-
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("lwmsurface_deserialize called");
-#endif
-
-        if(type != MULTISURFACETYPE)
-        {
-                lwerror("lwmsurface_deserialize called on a non-multisurface: %d", type);
-                return NULL;
-        }
-
-        insp = lwgeom_inspect(srl);
-
-        result = lwalloc(sizeof(LWMSURFACE));
-        result->type = insp->type;
-        result->SRID = insp->SRID;
-        result->ngeoms = insp->ngeometries;
-        result->geoms = lwalloc(sizeof(LWPOLY *)*insp->ngeometries);
-
-        if(lwgeom_hasBBOX(srl[0]))
-        {
-                result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
-                memcpy(result->bbox, srl + 1, sizeof(BOX2DFLOAT4));
-        }
-        else result->bbox = NULL;
-
-        for(i = 0; i < insp->ngeometries; i++)
-        {
-                stype = lwgeom_getType(insp->sub_geoms[i][0]);
-                if(stype == POLYGONTYPE) 
-                {
-                        result->geoms[i] = (LWGEOM *)lwpoly_deserialize(insp->sub_geoms[i]);
-                }
-                else if(stype == CURVEPOLYTYPE)
-                {
-                        result->geoms[i] = (LWGEOM *)lwcurvepoly_deserialize(insp->sub_geoms[i]);
-                }
-                else
-                {
-                        lwerror("Only Polygons and Curved Polygons are supported in a MultiSurface.");
-                        lwfree(result);
-                        lwfree(insp);
-                        return NULL;
-                }
-
-                if(TYPE_NDIMS(result->geoms[i]->type) != TYPE_NDIMS(result->type))
-                {
-                        lwerror("Mixed dimensions (multisurface: %d, surface %d:%d", 
-                                TYPE_NDIMS(result->type), i, 
-                                TYPE_NDIMS(result->geoms[i]->type));
-                        lwfree(result);
-                        lwfree(insp);
-                        return NULL;
-                }
-        }
-        return result;
-}
-
-/*
- * Add 'what' to this multisurface at position 'where'
- * where=0 == prepend
- * where=-1 == append
- * Returns a MULTISURFACE or a COLLECTION
- */
-LWGEOM *
-lwmsurface_add(const LWMSURFACE *to, uint32 where, const LWGEOM *what)
-{
-        LWCOLLECTION *col;
-        LWGEOM **geoms;
-        int newtype;
-        uint32 i;
-        
-        if(where == -1) where = to->ngeoms;
-        else if(where < -1 || where > to->ngeoms)
-        {
-                lwerror("lwmsurface_add: add position out of range %d..%d",
-                        -1, to->ngeoms);
-                return NULL;
-        }
-
-        /* dimensions compatibility are checked by caller */
-
-        /* Construct geoms array */
-        geoms = lwalloc(sizeof(LWGEOM *)*(to->ngeoms+1));
-        for(i = 0; i < where; i++)
-        {
-                geoms[i] = lwgeom_clone((LWGEOM *)to->geoms[i]);
-        }
-        geoms[where] = lwgeom_clone(what);
-        for(i = where; i < to->ngeoms; i++)
-        {
-                geoms[i+1] = lwgeom_clone((LWGEOM *)to->geoms[i]);
-        }
-
-        if(TYPE_GETTYPE(what->type) == POLYGONTYPE 
-                || TYPE_GETTYPE(what->type) == CURVEPOLYTYPE) 
-            newtype = MULTISURFACETYPE;
-        else newtype = COLLECTIONTYPE;
-
-        col = lwcollection_construct(newtype,
-            to->SRID, NULL, to->ngeoms + 1, geoms);
-
-        return (LWGEOM *)col;
-}
-
+/**********************************************************************
+ * $Id$
+ *
+ * PostGIS - Spatial Types for PostgreSQL
+ * http://postgis.refractions.net
+ * Copyright 2001-2006 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.
+ * 
+ **********************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "liblwgeom.h"
+
+
+LWMSURFACE *
+lwmsurface_deserialize(uchar *srl)
+{
+        LWMSURFACE *result;
+        LWGEOM_INSPECTED *insp;
+        int stype;
+        int type = lwgeom_getType(srl[0]);
+        int i;
+
+        LWDEBUG(2, "lwmsurface_deserialize called");
+
+        if(type != MULTISURFACETYPE)
+        {
+                lwerror("lwmsurface_deserialize called on a non-multisurface: %d", type);
+                return NULL;
+        }
+
+        insp = lwgeom_inspect(srl);
+
+        result = lwalloc(sizeof(LWMSURFACE));
+        result->type = insp->type;
+        result->SRID = insp->SRID;
+        result->ngeoms = insp->ngeometries;
+        result->geoms = lwalloc(sizeof(LWPOLY *)*insp->ngeometries);
+
+        if(lwgeom_hasBBOX(srl[0]))
+        {
+                result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
+                memcpy(result->bbox, srl + 1, sizeof(BOX2DFLOAT4));
+        }
+        else result->bbox = NULL;
+
+        for(i = 0; i < insp->ngeometries; i++)
+        {
+                stype = lwgeom_getType(insp->sub_geoms[i][0]);
+                if(stype == POLYGONTYPE) 
+                {
+                        result->geoms[i] = (LWGEOM *)lwpoly_deserialize(insp->sub_geoms[i]);
+                }
+                else if(stype == CURVEPOLYTYPE)
+                {
+                        result->geoms[i] = (LWGEOM *)lwcurvepoly_deserialize(insp->sub_geoms[i]);
+                }
+                else
+                {
+                        lwerror("Only Polygons and Curved Polygons are supported in a MultiSurface.");
+                        lwfree(result);
+                        lwfree(insp);
+                        return NULL;
+                }
+
+                if(TYPE_NDIMS(result->geoms[i]->type) != TYPE_NDIMS(result->type))
+                {
+                        lwerror("Mixed dimensions (multisurface: %d, surface %d:%d", 
+                                TYPE_NDIMS(result->type), i, 
+                                TYPE_NDIMS(result->geoms[i]->type));
+                        lwfree(result);
+                        lwfree(insp);
+                        return NULL;
+                }
+        }
+        return result;
+}
+
+/*
+ * Add 'what' to this multisurface at position 'where'
+ * where=0 == prepend
+ * where=-1 == append
+ * Returns a MULTISURFACE or a COLLECTION
+ */
+LWGEOM *
+lwmsurface_add(const LWMSURFACE *to, uint32 where, const LWGEOM *what)
+{
+        LWCOLLECTION *col;
+        LWGEOM **geoms;
+        int newtype;
+        uint32 i;
+        
+        if(where == -1) where = to->ngeoms;
+        else if(where < -1 || where > to->ngeoms)
+        {
+                lwerror("lwmsurface_add: add position out of range %d..%d",
+                        -1, to->ngeoms);
+                return NULL;
+        }
+
+        /* dimensions compatibility are checked by caller */
+
+        /* Construct geoms array */
+        geoms = lwalloc(sizeof(LWGEOM *)*(to->ngeoms+1));
+        for(i = 0; i < where; i++)
+        {
+                geoms[i] = lwgeom_clone((LWGEOM *)to->geoms[i]);
+        }
+        geoms[where] = lwgeom_clone(what);
+        for(i = where; i < to->ngeoms; i++)
+        {
+                geoms[i+1] = lwgeom_clone((LWGEOM *)to->geoms[i]);
+        }
+
+        if(TYPE_GETTYPE(what->type) == POLYGONTYPE 
+                || TYPE_GETTYPE(what->type) == CURVEPOLYTYPE) 
+            newtype = MULTISURFACETYPE;
+        else newtype = COLLECTIONTYPE;
+
+        col = lwcollection_construct(newtype,
+            to->SRID, NULL, to->ngeoms + 1, geoms);
+
+        return (LWGEOM *)col;
+}
+

Modified: trunk/lwgeom/lwpoint.c
===================================================================
--- trunk/lwgeom/lwpoint.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwpoint.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -15,7 +15,6 @@
 #include <string.h>
 #include "liblwgeom.h"
 
-/*#define PGIS_DEBUG_CALLS 1 */
 
 /*
  * Convert this point into its serialize form
@@ -56,10 +55,8 @@
 	if ( TYPE_GETZM(point->type) != TYPE_GETZM(point->point->dims) )
 		lwerror("Dimensions mismatch in lwpoint");
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoint_serialize_buf(%p, %p) called", point, buf);
+	LWDEBUGF(2, "lwpoint_serialize_buf(%p, %p) called", point, buf);
 	/*printLWPOINT(point); */
-#endif
 
 	hasSRID = (point->SRID != -1);
 
@@ -98,20 +95,16 @@
 BOX3D *
 lwpoint_compute_box3d(LWPOINT *point)
 {
-#ifdef PGIS_DEBUG
-	lwnotice("lwpoint_compute_box3d called with point %p", point);
-#endif
+	LWDEBUGF(2, "lwpoint_compute_box3d called with point %p", point);
+
 	if (point == NULL)
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwpoint_compute_box3d returning NULL");
-#endif
+		LWDEBUG(3, "lwpoint_compute_box3d returning NULL");
+
 		return NULL;
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("lwpoint_compute_box3d returning ptarray_compute_box3d return");
-#endif
+	LWDEBUG(3, "lwpoint_compute_box3d returning ptarray_compute_box3d return");
 
 	return ptarray_compute_box3d(point->point);
 }
@@ -149,18 +142,14 @@
 {
 	size_t size = 1; /* type */
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoint_serialize_size called");
-#endif
+	LWDEBUG(2, "lwpoint_serialize_size called");
 
 	if ( point->SRID != -1 ) size += 4; /* SRID */
 	if ( point->bbox ) size += sizeof(BOX2DFLOAT4);
 
 	size += TYPE_NDIMS(point->type) * sizeof(double); /* point */
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoint_serialize_size returning %d", size);
-#endif
+	LWDEBUGF(3, "lwpoint_serialize_size returning %d", size);
 
 	return size; 
 }
@@ -261,9 +250,7 @@
 	uchar *loc = NULL;
 	POINTARRAY *pa;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoint_deserialize called");
-#endif
+	LWDEBUG(2, "lwpoint_deserialize called");
 
 	result = (LWPOINT*) lwalloc(sizeof(LWPOINT)) ;
 
@@ -281,9 +268,8 @@
 
 	if (lwgeom_hasBBOX(type))
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwpoint_deserialize: input has bbox");
-#endif
+		LWDEBUG(3, "lwpoint_deserialize: input has bbox");
+
 		result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
 		memcpy(result->bbox, loc, sizeof(BOX2DFLOAT4));
 		loc += sizeof(BOX2DFLOAT4);
@@ -295,9 +281,8 @@
 
 	if ( lwgeom_hasSRID(type))
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwpoint_deserialize: input has SRID");
-#endif
+		LWDEBUG(3, "lwpoint_deserialize: input has SRID");
+
 		result->SRID = lw_get_int32(loc);
 		loc += 4; /* type + SRID */
 	}
@@ -342,9 +327,9 @@
 lwpoint_clone(const LWPOINT *g)
 {
 	LWPOINT *ret = lwalloc(sizeof(LWPOINT));
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoint_clone called");
-#endif
+
+	LWDEBUG(2, "lwpoint_clone called");
+
 	memcpy(ret, g, sizeof(LWPOINT));
 	if ( g->bbox ) ret->bbox = box2d_clone(g->bbox);
 	return ret;
@@ -413,9 +398,7 @@
 
 	if ( lwgeom_getType(type) != POINTTYPE) return 0;
 
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_size_point called (%d)", result);
-#endif
+	LWDEBUGF(2, "lwgeom_size_point called (%d)", result);
 
 	loc = serialized_point+1;
 
@@ -423,16 +406,14 @@
 	{
 		loc += sizeof(BOX2DFLOAT4);
 		result +=sizeof(BOX2DFLOAT4);
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_size_point: has bbox (%d)", result);
-#endif
+
+		LWDEBUGF(3, "lwgeom_size_point: has bbox (%d)", result);
 	}
 
 	if ( lwgeom_hasSRID(type))
 	{
-#ifdef PGIS_DEBUG
-lwnotice("lwgeom_size_point: has srid (%d)", result);
-#endif
+		LWDEBUGF(3, "lwgeom_size_point: has srid (%d)", result);
+
 		loc +=4; /* type + SRID */
 		result +=4;
 	}

Modified: trunk/lwgeom/lwpoly.c
===================================================================
--- trunk/lwgeom/lwpoly.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwpoly.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -17,7 +17,6 @@
 #include <string.h>
 #include "liblwgeom.h"
 
-/*#define PGIS_DEBUG_CALLS 1 */
 
 #define CHECK_POLY_RINGS_ZM 1
 
@@ -104,9 +103,8 @@
 	loc = serialized_form+1;
 
 	if (lwgeom_hasBBOX(type)) {
-#ifdef PGIS_DEBUG
-		lwnotice("lwpoly_deserialize: input has bbox");
-#endif
+		LWDEBUG(3, "lwpoly_deserialize: input has bbox");
+
 		result->bbox = lwalloc(sizeof(BOX2DFLOAT4));
 		memcpy(result->bbox, loc, sizeof(BOX2DFLOAT4));
 		loc += sizeof(BOX2DFLOAT4);
@@ -181,9 +179,7 @@
 	uchar *loc;
 	int ptsize;
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoly_serialize_buf called");
-#endif
+	LWDEBUG(2, "lwpoly_serialize_buf called");
 
 	ptsize = sizeof(double)*TYPE_NDIMS(poly->type);
 
@@ -281,9 +277,8 @@
 
 	if (lwgeom_hasBBOX(type))
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_size_poly: has bbox");
-#endif
+		LWDEBUG(3, "lwgeom_size_poly: has bbox");
+
 		loc += sizeof(BOX2DFLOAT4);
 		result +=sizeof(BOX2DFLOAT4);
 	}
@@ -291,9 +286,8 @@
 
 	if ( lwgeom_hasSRID(type))
 	{
-#ifdef PGIS_DEBUG
-		lwnotice("lwgeom_size_poly: has srid");
-#endif
+		LWDEBUG(3, "lwgeom_size_poly: has srid");
+
 		loc +=4; /* type + SRID */
 		result += 4;
 	}
@@ -303,9 +297,8 @@
 	loc +=4;
 	result +=4;
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwgeom_size_poly contains %d rings", nrings);
-#endif
+        LWDEBUGF(3, "lwgeom_size_poly contains %d rings", nrings);
+
 	for (t =0;t<nrings;t++)
 	{
 		/* read in a single ring and make a PA */
@@ -330,9 +323,8 @@
 		}
 	}
 
-#ifdef PGIS_DEBUG
-        lwnotice("lwgeom_size_poly returning %d", result);
-#endif
+        LWDEBUGF(3, "lwgeom_size_poly returning %d", result);
+
 	return result;
 }
 
@@ -346,10 +338,8 @@
 	if ( poly->SRID != -1 ) size += 4; /* SRID */
 	if ( poly->bbox ) size += sizeof(BOX2DFLOAT4);
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoly_serialize_size called with poly[%p] (%d rings)",
+	LWDEBUGF(2, "lwpoly_serialize_size called with poly[%p] (%d rings)",
 			poly, poly->nrings);
-#endif
 
 	size += 4; /* nrings */
 
@@ -359,9 +349,7 @@
 		size += poly->rings[i]->npoints*TYPE_NDIMS(poly->type)*sizeof(double);
 	}
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("lwpoly_serialize_size returning %d", size);
-#endif
+	LWDEBUGF(3, "lwpoly_serialize_size returning %d", size);
 
 	return size;
 }

Modified: trunk/lwgeom/lwpostgis.sql.in.c
===================================================================
--- trunk/lwgeom/lwpostgis.sql.in.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/lwpostgis.sql.in.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -4433,7 +4433,7 @@
 -- Availability: 1.3.4
 CREATEFUNCTION _ST_DWithin(geometry,geometry,float8)
     RETURNS boolean
-    AS '@MODULE_FILENAME@', 'LWGEOM_dwithin'
+    AS 'MODULE_PATHNAME', 'LWGEOM_dwithin'
     LANGUAGE 'C' _IMMUTABLE_STRICT; -- WITH (isstrict,iscachable);
 
 -- Availability: 1.2.2

Modified: trunk/lwgeom/measures.c
===================================================================
--- trunk/lwgeom/measures.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/measures.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -15,7 +15,6 @@
 
 #include "liblwgeom.h"
 
-/*#define PGIS_DEBUG 1*/
 
 /*
  * pt_in_ring_2d(): crossing number test for a point in a polygon
@@ -45,10 +44,8 @@
 	}
 #endif
 
-#ifdef PGIS_DEBUG
-	lwnotice("pt_in_ring_2d called with point: %g %g", p->x, p->y);
+	LWDEBUGF(2, "pt_in_ring_2d called with point: %g %g", p->x, p->y);
 	/* printPA(ring); */
-#endif
 
 	/* loop through all edges of the polygon */
 	getPoint2d_p(ring, 0, &v1);
@@ -78,9 +75,9 @@
 		}
 		v1 = v2;
 	}
-#ifdef PGIS_DEBUG
-	lwnotice("pt_in_ring_2d returning %d", cn&1);
-#endif
+
+	LWDEBUGF(3, "pt_in_ring_2d returning %d", cn&1);
+
 	return (cn&1);    /* 0 if even (out), and 1 if odd (in) */
 }
 
@@ -152,10 +149,8 @@
 	double	s_top, s_bot,s;
 	double	r_top, r_bot,r;
 
-#ifdef PGIS_DEBUG
-	lwnotice("distance2d_seg_seg [%g,%g]->[%g,%g] by [%g,%g]->[%g,%g]",
+	LWDEBUGF(2, "distance2d_seg_seg [%g,%g]->[%g,%g] by [%g,%g]->[%g,%g]",
 		A->x,A->y,B->x,B->y, C->x,C->y, D->x, D->y);
-#endif
 
 
 	/*A and B are the same point */
@@ -264,10 +259,8 @@
 	POINT2D	start, end;
 	POINT2D	start2, end2;
 
-#ifdef PGIS_DEBUG
-	lwnotice("distance2d_ptarray_ptarray called (points: %d-%d)",
+	LWDEBUGF(2, "distance2d_ptarray_ptarray called (points: %d-%d)",
 			l1->npoints, l2->npoints);
-#endif
 
 	getPoint2d_p(l1, 0, &start);
 	for (t=1; t<l1->npoints; t++) /*for each segment in L1 */
@@ -282,10 +275,9 @@
 			getPoint2d_p(l2, u, &end2);
 
 			dist = distance2d_seg_seg(&start, &end, &start2, &end2);
-#if PGIS_DEBUG > 1
-printf("line_line; seg %i * seg %i, dist = %g\n",t,u,dist_this);
-#endif
 
+			LWDEBUGF(4, "line_line; seg %i * seg %i, dist = %g\n",t,u,dist);
+
 			if (result_okay)
 				result = LW_MIN(result,dist);
 			else
@@ -294,10 +286,8 @@
 				result = dist;
 			}
 
-#ifdef PGIS_DEBUG
-			lwnotice(" seg%d-seg%d dist: %f, mindist: %f",
+			LWDEBUGF(3, " seg%d-seg%d dist: %f, mindist: %f",
 				t, u, dist, result);
-#endif
 
 			if (result <= 0) return 0; /*intersection */
 
@@ -343,19 +333,16 @@
 	int i;
 	double mindist = 0;
 
-#ifdef PGIS_DEBUG
-	lwnotice("distance2d_ptarray_poly called (%d rings)", poly->nrings);
-#endif
+	LWDEBUGF(2, "distance2d_ptarray_poly called (%d rings)", poly->nrings);
 
 	for (i=0; i<poly->nrings; i++)
 	{
 		double dist = distance2d_ptarray_ptarray(pa, poly->rings[i]);
 		if (i) mindist = LW_MIN(mindist, dist);
 		else mindist = dist;
-#ifdef PGIS_DEBUG
-	lwnotice(" distance from ring %d: %f, mindist: %f",
+
+		LWDEBUGF(3, " distance from ring %d: %f, mindist: %f",
 			i, dist, mindist);
-#endif
 
 		if ( mindist <= 0 ) return 0.0; /* intersection */
 	}
@@ -430,16 +417,13 @@
 
 	getPoint2d_p(point->point, 0, &p);
 
-#ifdef PGIS_DEBUG
-	lwnotice("distance2d_point_poly called");
-#endif
+	LWDEBUG(2, "distance2d_point_poly called");
 
 	/* Return distance to outer ring if not inside it */
 	if ( ! pt_in_ring_2d(&p, poly->rings[0]) )
 	{
-#ifdef PGIS_DEBUG
-	lwnotice(" not inside outer-ring");
-#endif
+		LWDEBUG(3, " not inside outer-ring");
+
 		return distance2d_pt_ptarray(&p, poly->rings[0]);
 	}
 
@@ -454,16 +438,14 @@
 		/* Inside a hole. Distance = pt -> ring */
 		if ( pt_in_ring_2d(&p, poly->rings[i]) )
 		{
-#ifdef PGIS_DEBUG
-			lwnotice(" inside an hole");
-#endif
+			LWDEBUG(3, " inside an hole");
+
 			return distance2d_pt_ptarray(&p, poly->rings[i]);
 		}
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice(" inside the polygon");
-#endif
+	LWDEBUG(3, " inside the polygon");
+
 	return 0.0; /* Is inside the polygon */
 }
 
@@ -480,9 +462,7 @@
 	double mindist = -1;
 	int i;
 
-#ifdef PGIS_DEBUG
-	lwnotice("distance2d_poly_poly called");
-#endif
+	LWDEBUG(2, "distance2d_poly_poly called");
 
 	/* if poly1 inside poly2 return 0 */
 	getPoint2d_p(poly1->rings[0], 0, &pt);
@@ -492,9 +472,7 @@
 	getPoint2d_p(poly2->rings[0], 0, &pt);
 	if ( pt_in_poly_2d(&pt, poly1) ) return 0.0;  
 
-#ifdef PGIS_DEBUG
-	lwnotice("  polys not inside each other");
-#endif
+	LWDEBUG(3, "  polys not inside each other");
 
 	/*
 	 * foreach ring in Poly1
@@ -513,10 +491,8 @@
 			/* mindist is -1 when not yet set */
 			if (mindist > -1) mindist = LW_MIN(mindist, d);
 			else mindist = d;
-#ifdef PGIS_DEBUG
-		lwnotice("  ring%i-%i dist: %f, mindist: %f", i, j, d, mindist);
-#endif
 
+			LWDEBUGF(3, "  ring%i-%i dist: %f, mindist: %f", i, j, d, mindist);
 		}
 
 	}
@@ -602,9 +578,7 @@
 	POINT2D p1;
 	POINT2D p2;
 
-#ifdef PGIS_DEBUG
-	lwnotice("in lwgeom_polygon_area (%d rings)", poly->nrings);
-#endif
+	LWDEBUGF(2, "in lwgeom_polygon_area (%d rings)", poly->nrings);
 
 	for (i=0; i<poly->nrings; i++)
 	{
@@ -612,9 +586,8 @@
 		POINTARRAY *ring = poly->rings[i];
 		double ringarea = 0.0;
 
-#if PGIS_DEBUG > 1
-lwnotice(" rings %d has %d points", i, ring->npoints);
-#endif
+		LWDEBUGF(4, " rings %d has %d points", i, ring->npoints);
+
 		for (j=0; j<ring->npoints-1; j++)
     		{
 			getPoint2d_p(ring, j, &p1);
@@ -623,9 +596,9 @@
 		}
 
 		ringarea  /= 2.0;
-#if PGIS_DEBUG > 1
-lwnotice(" ring 1 has area %lf",ringarea);
-#endif
+
+		LWDEBUGF(4, " ring 1 has area %lf",ringarea);
+
 		ringarea  = fabs(ringarea);
 		if (i != 0)	/*outer */
 			ringarea  = -1.0*ringarea ; /* its a hole */
@@ -645,9 +618,7 @@
 	double result=0.0;
 	int i;
 
-#ifdef PGIS_DEBUG
-lwnotice("in lwgeom_polygon_perimeter (%d rings)", poly->nrings);
-#endif
+	LWDEBUGF(2, "in lwgeom_polygon_perimeter (%d rings)", poly->nrings);
 
 	for (i=0; i<poly->nrings; i++)
 		result += lwgeom_pointarray_length(poly->rings[i]);
@@ -664,9 +635,7 @@
 	double result=0.0;
 	int i;
 
-#ifdef PGIS_DEBUG
-lwnotice("in lwgeom_polygon_perimeter (%d rings)", poly->nrings);
-#endif
+	LWDEBUGF(2, "in lwgeom_polygon_perimeter (%d rings)", poly->nrings);
 
 	for (i=0; i<poly->nrings; i++)
 		result += lwgeom_pointarray_length2d(poly->rings[i]);
@@ -791,10 +760,8 @@
 			if (mindist == -1 ) mindist = dist;
 			else mindist = LW_MIN(dist, mindist);
 
-#ifdef PGIS_DEBUG
-		lwnotice("dist %d-%d: %f - mindist: %f",
+			LWDEBUGF(3, "dist %d-%d: %f - mindist: %f",
 				i, j, dist, mindist);
-#endif
 
 
 			if (mindist <= tolerance) return tolerance; /* can't be closer */

Modified: trunk/lwgeom/ptarray.c
===================================================================
--- trunk/lwgeom/ptarray.c	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/lwgeom/ptarray.c	2008-05-31 09:56:44 UTC (rev 2797)
@@ -15,8 +15,6 @@
 
 #include "liblwgeom.h"
 
-/*#define PGIS_DEBUG_CALLS 1*/
-/*#define PGIS_DEBUG 1*/
 
 POINTARRAY *
 ptarray_construct(char hasz, char hasm, unsigned int npoints)
@@ -243,10 +241,8 @@
 	POINT4D pbuf;
 	size_t ptsize = pointArray_ptsize(pa);
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("ptarray_addPoint: pa %x p %x size %d where %d",
+	LWDEBUGF(3, "pa %x p %x size %d where %d",
 		pa, p, pdims, where);
-#endif
 
 	if ( pdims < 2 || pdims > 4 )
 	{
@@ -262,16 +258,12 @@
 		return NULL;
 	}
 
-#if PGIS_DEBUG
-	lwnotice("ptarray_addPoint: called with a %dD point");
-#endif
+	LWDEBUG(3, "called with a %dD point");
 	
 	pbuf.x = pbuf.y = pbuf.z = pbuf.m = 0.0;
 	memcpy((uchar *)&pbuf, p, pdims*sizeof(double));
 
-#if PGIS_DEBUG
-	lwnotice("ptarray_addPoint: initialized point buffer");
-#endif
+	LWDEBUG(3, "initialized point buffer");
 
 	ret = ptarray_construct(TYPE_HASZ(pa->dims),
 		TYPE_HASM(pa->dims), pa->npoints+1);
@@ -306,10 +298,7 @@
 	POINTARRAY *ret;
 	size_t ptsize = pointArray_ptsize(pa);
 
-#ifdef PGIS_DEBUG_CALLS
-	lwnotice("ptarray_removePoint: pa %x which %d",
-		pa, which);
-#endif
+	LWDEBUGF(3, "pa %x which %d", pa, which);
 
 #if PARANOIA_LEVEL > 0
 	if ( which > pa->npoints-1 )
@@ -353,9 +342,7 @@
 	POINTARRAY *out = lwalloc(sizeof(POINTARRAY));
 	size_t size;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("ptarray_clone called.");
-#endif
+        LWDEBUG(3, "ptarray_clone called.");
 
 	out->dims = in->dims;
 	out->npoints = in->npoints;
@@ -405,16 +392,13 @@
 	int t;
 	POINT3DZ pt;
 
-#ifdef PGIS_DEBUG
-	lwnotice("ptarray_compute_box3d call (array has %d points)", pa->npoints);
-#endif
+	LWDEBUGF(3, "ptarray_compute_box3d call (array has %d points)", pa->npoints);
+	
 	if (pa->npoints == 0) return 0;
 
 	getPoint3dz_p(pa, 0, &pt);
 
-#ifdef PGIS_DEBUG
-	lwnotice("ptarray_compute_box3d: got point 0");
-#endif
+	LWDEBUG(3, "got point 0");
 
 	result->xmin = pt.x;
 	result->xmax = pt.x;
@@ -429,9 +413,8 @@
 		result->zmax = NO_Z_VALUE;
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("ptarray_compute_box3d: scanning other %d points", pa->npoints);
-#endif
+	LWDEBUGF(3, "scanning other %d points", pa->npoints);
+
 	for (t=1; t<pa->npoints; t++)
 	{
 		getPoint3dz_p(pa,t,&pt);
@@ -446,9 +429,7 @@
 		}
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("ptarray_compute_box3d returning box");
-#endif
+	LWDEBUG(3, "returning box");
 
 	return 1;
 }
@@ -478,18 +459,18 @@
 	/* Compute total line length */
 	length = lwgeom_pointarray_length2d(ipa);
 
-#ifdef PGIS_DEBUG
-	lwnotice("Total length: %g", length);
-#endif
 
+	LWDEBUGF(3, "Total length: %g", length);
+
+
 	/* Get 'from' and 'to' lengths */
 	from = length*from;
 	to = length*to;
 
-#ifdef PGIS_DEBUG
-	lwnotice("From/To: %g/%g", from, to);
-#endif
 
+	LWDEBUGF(3, "From/To: %g/%g", from, to);
+
+
 	tlength = 0;
 	getPoint4d_p(ipa, 0, &p1);
 	nsegs = ipa->npoints - 1;
@@ -499,11 +480,11 @@
 
 		getPoint4d_p(ipa, i+1, &p2);
 
-#ifdef PGIS_DEBUG
-	lwnotice("Segment %d: (%g,%g,%g,%g)-(%g,%g,%g,%g)",
-		i, p1.x, p1.y, p1.z, p1.m, p2.x, p2.y, p2.z, p2.m);
-#endif
 
+		LWDEBUGF(3 ,"Segment %d: (%g,%g,%g,%g)-(%g,%g,%g,%g)",
+			i, p1.x, p1.y, p1.z, p1.m, p2.x, p2.y, p2.z, p2.m);
+
+
 		/* Find the length of this segment */
 		slength = distance2d_pt_pt((POINT2D *)p1ptr, (POINT2D *)p2ptr);
 
@@ -513,9 +494,8 @@
 		if ( state == 0 ) /* before */
 		{
 
-#ifdef PGIS_DEBUG
-			lwnotice(" Before start");
-#endif
+			LWDEBUG(3, " Before start");
+
 			/*
 			 * Didn't reach the 'from' point,
 			 * nothing to do
@@ -524,9 +504,9 @@
 
 			else if ( from == tlength + slength )
 			{
-#ifdef PGIS_DEBUG
-				lwnotice("  Second point is our start");
-#endif
+
+				LWDEBUG(3, "  Second point is our start");
+
 				/*
 				 * Second point is our start
 				 */
@@ -537,9 +517,9 @@
 
 			else if ( from == tlength )
 			{
-#ifdef PGIS_DEBUG
-				lwnotice("  First point is our start");
-#endif
+
+				LWDEBUG(3, "  First point is our start");
+
 				/*
 				 * First point is our start
 				 */
@@ -554,9 +534,9 @@
 
 			else  /* tlength < from < tlength+slength */
 			{
-#ifdef PGIS_DEBUG
-				lwnotice("  Seg contains first point");
-#endif
+
+				LWDEBUG(3, "  Seg contains first point");
+
 				/*
 				 * Our start is between first and
 				 * second point
@@ -576,9 +556,9 @@
 
 		if ( state == 1 ) /* inside */
 		{
-#ifdef PGIS_DEBUG
-			lwnotice(" Inside");
-#endif
+
+			LWDEBUG(3, " Inside");
+
 			/*
 			 * Didn't reach the 'end' point,
 			 * just copy second point
@@ -594,9 +574,9 @@
 			 */
 			else if ( to == tlength + slength )
 			{
-#ifdef PGIS_DEBUG
-				lwnotice(" Second point is our end");
-#endif
+
+				LWDEBUG(3, " Second point is our end");
+
 				dynptarray_addPoint4d(dpa, &p2, 0);
 				break; /* substring complete */
 			}
@@ -607,10 +587,9 @@
 			 */
 			else if ( to == tlength )
 			{
-#ifdef PGIS_DEBUG
-				lwnotice(" First point is our end");
-#endif
 
+				LWDEBUG(3, " First point is our end");
+
 				dynptarray_addPoint4d(dpa, &p1, 0);
 
 				break; /* substring complete */
@@ -622,9 +601,9 @@
 			 */
 			else if ( to < tlength + slength )
 			{
-#ifdef PGIS_DEBUG
-				lwnotice(" Seg contains our end");
-#endif
+
+				LWDEBUG(3, " Seg contains our end");
+
 				dseg = (to - tlength) / slength;
 				interpolate_point4d(&p1, &p2, &pt, dseg);
 
@@ -635,7 +614,7 @@
 
 			else
 			{
-				lwnotice("Unhandled case");
+				LWDEBUG(3, "Unhandled case");
 			}
 		}
 
@@ -652,9 +631,7 @@
 	opa = dpa->pa;
 	lwfree(dpa);
 
-#ifdef PGIS_DEBUG
-	lwnotice("Out of loop, ptarray has %d points", opa->npoints);
-#endif
+	LWDEBUGF(3, "Out of loop, ptarray has %d points", opa->npoints);
 
 	return opa;
 }
@@ -731,9 +708,7 @@
 		start = end;
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("Closest segment: %d", seg);
-#endif
+	LWDEBUGF(3, "Closest segment: %d", seg);
 
 	/*
 	 * If mindist is not 0 we need to project the 
@@ -748,32 +723,26 @@
 		proj = *p;
 	}
 
-#ifdef PGIS_DEBUG
-	lwnotice("Closest point on segment: %g,%g", proj.x, proj.y);
-#endif
+	LWDEBUGF(3, "Closest point on segment: %g,%g", proj.x, proj.y);
 
 	tlen = lwgeom_pointarray_length2d(pa);
-#ifdef PGIS_DEBUG
-	lwnotice("tlen %g", tlen);
-#endif
 
+	LWDEBUGF(3, "tlen %g", tlen);
+
 	plen=0;
 	getPoint2d_p(pa, 0, &start);
 	for (t=0; t<seg; t++, start=end)
 	{
 		getPoint2d_p(pa, t+1, &end);
 		plen += distance2d_pt_pt(&start, &end);
-#if PGIS_DEBUG > 1
-		lwnotice("Segment %d made plen %g", t, plen);
-#endif
+
+		LWDEBUGF(4, "Segment %d made plen %g", t, plen);
 	}
 
 	plen+=distance2d_pt_pt(&proj, &start);
 
-#ifdef PGIS_DEBUG
-	lwnotice("plen %g, tlen %g", plen, tlen);
-	lwnotice("mindist: %g", mindist);
-#endif
+	LWDEBUGF(3, "plen %g, tlen %g", plen, tlen);
+	LWDEBUGF(3, "mindist: %g", mindist);
 
 	return plen/tlen;
 }
@@ -806,9 +775,7 @@
 {
 	DYNPTARRAY *ret=lwalloc(sizeof(DYNPTARRAY));
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("dynptarray_create called, dims=%d.", dims);
-#endif
+        LWDEBUGF(3, "dynptarray_create called, dims=%d.", dims);
 
 	if ( initial_capacity < 1 ) initial_capacity=1;
 
@@ -840,9 +807,7 @@
 	POINTARRAY *pa=dpa->pa;
 	POINT4D tmp;
 
-#ifdef PGIS_DEBUG_CALLS
-        lwnotice("dynptarray_addPoint4d called.");
-#endif
+        LWDEBUG(3, "dynptarray_addPoint4d called.");
 
 	if ( ! allow_duplicates && pa->npoints > 0 )
 	{

Modified: trunk/postgis_config.h.in
===================================================================
--- trunk/postgis_config.h.in	2008-05-28 23:03:11 UTC (rev 2796)
+++ trunk/postgis_config.h.in	2008-05-31 09:56:44 UTC (rev 2797)
@@ -45,6 +45,9 @@
 /* PostGIS build date */
 #undef POSTGIS_BUILD_DATE
 
+/* PostGIS library debug level (0=disabled) */
+#undef POSTGIS_DEBUG_LEVEL
+
 /* GEOS library version */
 #undef POSTGIS_GEOS_VERSION
 



More information about the postgis-commits mailing list